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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.976.2.9! raeburn     4: # $Id: lonnet.pm,v 1.976.2.8 2009/05/13 03:28:41 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.976.2.9! raeburn  2718:     my %privileged;
1.800     albertel 2719:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2720:         my ($role,$tend,$tstart);
                   2721:         if ($context eq 'userroles') {
                   2722: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2723:         } else {
                   2724:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2725:         }
1.400     www      2726:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2727:         my $status = 'active';
1.939     raeburn  2728:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2729:             $status = 'previous';
                   2730:         } 
                   2731:         if (($tstart) && ($now<$tstart)) {
                   2732:             $status = 'future';
                   2733:         }
                   2734:         if (ref($types) eq 'ARRAY') {
                   2735:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2736:                 next;
                   2737:             } 
                   2738:         } else {
                   2739:             if ($status ne 'active') {
                   2740:                 next;
                   2741:             }
                   2742:         }
1.867     raeburn  2743:         my ($rolecode,$username,$domain,$section,$area);
                   2744:         if ($context eq 'userroles') {
                   2745:             ($area,$rolecode) = split(/_/,$entry);
                   2746:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2747:         } else {
                   2748:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2749:         }
1.832     raeburn  2750:         if (ref($roledoms) eq 'ARRAY') {
                   2751:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2752:                 next;
                   2753:             }
                   2754:         }
                   2755:         if (ref($roles) eq 'ARRAY') {
                   2756:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2757:                 if ($role =~ /^cr\//) {
                   2758:                     if (!grep(/^cr$/,@{$roles})) {
                   2759:                         next;
                   2760:                     }
                   2761:                 } else {
                   2762:                     next;
                   2763:                 }
1.832     raeburn  2764:             }
1.867     raeburn  2765:         }
1.937     raeburn  2766:         if ($hidepriv) {
1.976.2.8  raeburn  2767:             if ($context eq 'userroles') {
                   2768:                 if ((&privileged($username,$domain)) &&
                   2769:                     (!$nothide{$username.':'.$domain})) {
                   2770:                     next;
                   2771:                 }
                   2772:             } else {
                   2773:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   2774:                     my %dompersonnel =
                   2775:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   2776:                     $privileged{$domain} = {};
                   2777:                     if (keys(%dompersonnel)) {
                   2778:                         foreach my $server (keys(%dompersonnel)) {
                   2779:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   2780:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   2781:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   2782:                                     $privileged{$udom}{$uname} = $trole;
                   2783:                                 }
                   2784:                             }
                   2785:                         }
                   2786:                     }
                   2787:                 }
                   2788:                 if (exists($privileged{$domain}{$username})) {
                   2789:                     if (!$nothide{$username.':'.$domain}) {
                   2790:                         next;
                   2791:                     }
                   2792:                 }
1.937     raeburn  2793:             }
                   2794:         }
1.933     raeburn  2795:         if ($withsec) {
                   2796:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2797:                 $tstart.':'.$tend;
                   2798:         } else {
                   2799:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2800:         }
1.832     raeburn  2801:     }
1.373     www      2802:     return %returnhash;
1.399     www      2803: }
                   2804: 
                   2805: # ----------------------------------------------------- Frontpage Announcements
                   2806: #
                   2807: #
                   2808: 
                   2809: sub postannounce {
                   2810:     my ($server,$text)=@_;
1.844     albertel 2811:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2812:     unless ($text=~/\w/) { $text=''; }
                   2813:     return &reply('setannounce:'.&escape($text),$server);
                   2814: }
                   2815: 
                   2816: sub getannounce {
1.448     albertel 2817: 
                   2818:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2819: 	my $announcement='';
1.800     albertel 2820: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2821: 	close($fh);
1.399     www      2822: 	if ($announcement=~/\w/) { 
                   2823: 	    return 
                   2824:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2825:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2826: 	} else {
                   2827: 	    return '';
                   2828: 	}
                   2829:     } else {
                   2830: 	return '';
                   2831:     }
1.351     www      2832: }
1.353     www      2833: 
                   2834: # ---------------------------------------------------------- Course ID routines
                   2835: # Deal with domain's nohist_courseid.db files
                   2836: #
                   2837: 
                   2838: sub courseidput {
1.921     raeburn  2839:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2840:     my $outcome;
                   2841:     if ($caller eq 'timeonly') {
                   2842:         my $cids = '';
                   2843:         foreach my $item (keys(%$storehash)) {
                   2844:             $cids.=&escape($item).'&';
                   2845:         }
                   2846:         $cids=~s/\&$//;
                   2847:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2848:                           $coursehome);       
                   2849:     } else {
                   2850:         my $items = '';
                   2851:         foreach my $item (keys(%$storehash)) {
                   2852:             $items.= &escape($item).'='.
                   2853:                      &freeze_escape($$storehash{$item}).'&';
                   2854:         }
                   2855:         $items=~s/\&$//;
                   2856:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2857:                           $coursehome);
1.918     raeburn  2858:     }
                   2859:     if ($outcome eq 'unknown_cmd') {
                   2860:         my $what;
                   2861:         foreach my $cid (keys(%$storehash)) {
                   2862:             $what .= &escape($cid).'=';
1.921     raeburn  2863:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2864:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2865:             }
                   2866:             $what =~ s/\:$/&/;
                   2867:         }
                   2868:         $what =~ s/\&$//;  
                   2869:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2870:     } else {
                   2871:         return $outcome;
                   2872:     }
1.353     www      2873: }
                   2874: 
                   2875: sub courseiddump {
1.921     raeburn  2876:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  2877:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.962     raeburn  2878:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
1.918     raeburn  2879:     my $as_hash = 1;
                   2880:     my %returnhash;
                   2881:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2882:     my %libserv = &all_library();
                   2883:     foreach my $tryserver (keys(%libserv)) {
                   2884:         if ( (  $hostidflag == 1 
                   2885: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2886: 	     || (!defined($hostidflag)) ) {
                   2887: 
1.918     raeburn  2888: 	    if (($domfilter eq '') ||
                   2889: 		(&host_domain($tryserver) eq $domfilter)) {
                   2890:                 my $rep = 
                   2891:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2892:                          $sincefilter.':'.&escape($descfilter).':'.
                   2893:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2894:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  2895:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  2896:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   2897:                          $showhidden.':'.$caller,$tryserver);
1.918     raeburn  2898:                 my @pairs=split(/\&/,$rep);
                   2899:                 foreach my $item (@pairs) {
                   2900:                     my ($key,$value)=split(/\=/,$item,2);
                   2901:                     $key = &unescape($key);
                   2902:                     next if ($key =~ /^error: 2 /);
                   2903:                     my $result = &thaw_unescape($value);
                   2904:                     if (ref($result) eq 'HASH') {
                   2905:                         $returnhash{$key}=$result;
                   2906:                     } else {
1.921     raeburn  2907:                         my @responses = split(/:/,$value);
                   2908:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  2909:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  2910:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  2911:                         }
                   2912:                     } 
1.353     www      2913:                 }
                   2914:             }
                   2915:         }
                   2916:     }
                   2917:     return %returnhash;
                   2918: }
                   2919: 
1.658     raeburn  2920: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2921: 
                   2922: sub dcmailput {
1.685     raeburn  2923:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2924:     my $status = &Apache::lonnet::critical(
1.740     www      2925:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2926:        &escape($message),$server);
1.662     raeburn  2927:     return $status;
                   2928: }
                   2929: 
1.658     raeburn  2930: sub dcmaildump {
                   2931:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2932:     my %returnhash=();
1.846     albertel 2933: 
                   2934:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2935:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2936:                                                          &escape($enddate).':';
                   2937: 	my @esc_senders=map { &escape($_)} @$senders;
                   2938: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2939: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2940:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2941:             if (($key) && ($value)) {
                   2942:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2943:             }
                   2944:         }
                   2945:     }
                   2946:     return %returnhash;
                   2947: }
1.662     raeburn  2948: # ---------------------------------------------------------- Domain roles
                   2949: 
                   2950: sub get_domain_roles {
                   2951:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2952:     if (undef($startdate) || $startdate eq '') {
                   2953:         $startdate = '.';
                   2954:     }
                   2955:     if (undef($enddate) || $enddate eq '') {
                   2956:         $enddate = '.';
                   2957:     }
1.922     raeburn  2958:     my $rolelist;
                   2959:     if (ref($roles) eq 'ARRAY') {
                   2960:         $rolelist = join(':',@{$roles});
                   2961:     }
1.662     raeburn  2962:     my %personnel = ();
1.841     albertel 2963: 
                   2964:     my %servers = &get_servers($dom,'library');
                   2965:     foreach my $tryserver (keys(%servers)) {
                   2966: 	%{$personnel{$tryserver}}=();
                   2967: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2968: 					    &escape($startdate).':'.
                   2969: 					    &escape($enddate).':'.
                   2970: 					    &escape($rolelist), $tryserver))) {
                   2971: 	    my ($key,$value) = split(/\=/,$line,2);
                   2972: 	    if (($key) && ($value)) {
                   2973: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2974: 	    }
                   2975: 	}
1.662     raeburn  2976:     }
                   2977:     return %personnel;
                   2978: }
1.658     raeburn  2979: 
1.149     www      2980: # ----------------------------------------------------------- Check out an item
                   2981: 
1.504     albertel 2982: sub get_first_access {
                   2983:     my ($type,$argsymb)=@_;
1.790     albertel 2984:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2985:     if ($argsymb) { $symb=$argsymb; }
                   2986:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 2987:     if ($type eq 'course') {
                   2988: 	$res='course';
                   2989:     } elsif ($type eq 'map') {
1.588     albertel 2990: 	$res=&symbread($map);
                   2991:     } else {
                   2992: 	$res=$symb;
                   2993:     }
                   2994:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2995:     return $times{"$courseid\0$res"};
1.504     albertel 2996: }
                   2997: 
                   2998: sub set_first_access {
                   2999:     my ($type)=@_;
1.790     albertel 3000:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3001:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3002:     if ($type eq 'course') {
                   3003: 	$res='course';
                   3004:     } elsif ($type eq 'map') {
1.588     albertel 3005: 	$res=&symbread($map);
                   3006:     } else {
                   3007: 	$res=$symb;
                   3008:     }
                   3009:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3010:     if (!$firstaccess) {
1.588     albertel 3011: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3012:     }
                   3013:     return 'already_set';
1.504     albertel 3014: }
                   3015: 
1.149     www      3016: sub checkout {
                   3017:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   3018:     my $now=time;
                   3019:     my $lonhost=$perlvar{'lonHostID'};
                   3020:     my $infostr=&escape(
1.234     www      3021:                  'CHECKOUTTOKEN&'.
1.149     www      3022:                  $tuname.'&'.
                   3023:                  $tudom.'&'.
                   3024:                  $tcrsid.'&'.
                   3025:                  $symb.'&'.
                   3026: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   3027:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      3028:     if ($token=~/^error\:/) { 
1.672     albertel 3029:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3030:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3031:                  "</font>");
                   3032:         return ''; 
                   3033:     }
                   3034: 
1.149     www      3035:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   3036:     $token=~tr/a-z/A-Z/;
                   3037: 
1.153     www      3038:     my %infohash=('resource.0.outtoken' => $token,
                   3039:                   'resource.0.checkouttime' => $now,
                   3040:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      3041: 
                   3042:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3043:        return '';
1.151     www      3044:     } else {
1.672     albertel 3045:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3046:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3047:                  "</font>");
1.149     www      3048:     }    
                   3049: 
                   3050:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3051:                          &escape('Checkout '.$infostr.' - '.
                   3052:                                                  $token)) ne 'ok') {
                   3053: 	return '';
1.151     www      3054:     } else {
1.672     albertel 3055:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3056:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3057:                  "</font>");
1.149     www      3058:     }
1.151     www      3059:     return $token;
1.149     www      3060: }
                   3061: 
                   3062: # ------------------------------------------------------------ Check in an item
                   3063: 
                   3064: sub checkin {
                   3065:     my $token=shift;
1.150     www      3066:     my $now=time;
                   3067:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3068:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3069:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3070:     $dtoken=~s/\W/\_/g;
1.234     www      3071:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3072:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3073: 
1.154     www      3074:     unless (($tuname) && ($tudom)) {
                   3075:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3076:         return '';
                   3077:     }
                   3078:     
                   3079:     unless (&allowed('mgr',$tcrsid)) {
                   3080:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3081:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3082:         return '';
                   3083:     }
                   3084: 
1.153     www      3085:     my %infohash=('resource.0.intoken' => $token,
                   3086:                   'resource.0.checkintime' => $now,
                   3087:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3088: 
                   3089:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3090:        return '';
                   3091:     }    
                   3092: 
                   3093:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3094:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3095: 	return '';
                   3096:     }
                   3097: 
                   3098:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3099: }
                   3100: 
                   3101: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3102: 
                   3103: sub expirespread {
                   3104:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3105:     my $cid=$env{'request.course.id'}; 
1.110     www      3106:     if ($cid) {
                   3107:        my $now=time;
                   3108:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3109:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3110:                             $env{'course.'.$cid.'.num'}.
1.110     www      3111: 	        	    ':nohist_expirationdates:'.
                   3112:                             &escape($key).'='.$now,
1.620     albertel 3113:                             $env{'course.'.$cid.'.home'})
1.110     www      3114:     }
                   3115:     return 'ok';
1.14      www      3116: }
                   3117: 
1.109     www      3118: # ----------------------------------------------------- Devalidate Spreadsheets
                   3119: 
                   3120: sub devalidate {
1.325     www      3121:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3122:     my $cid=$env{'request.course.id'}; 
1.109     www      3123:     if ($cid) {
1.391     matthew  3124:         # delete the stored spreadsheets for
                   3125:         # - the student level sheet of this user in course's homespace
                   3126:         # - the assessment level sheet for this resource 
                   3127:         #   for this user in user's homespace
1.553     albertel 3128: 	# - current conditional state info
1.325     www      3129: 	my $key=$uname.':'.$udom.':';
1.109     www      3130:         my $status=
1.299     matthew  3131: 	    &del('nohist_calculatedsheets',
1.391     matthew  3132: 		 [$key.'studentcalc:'],
1.620     albertel 3133: 		 $env{'course.'.$cid.'.domain'},
                   3134: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3135: 		.' '.
                   3136: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3137: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3138:         unless ($status eq 'ok ok') {
                   3139:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3140:                     $uname.' at '.$udom.' for '.
1.109     www      3141: 		    $symb.': '.$status);
1.133     albertel 3142:         }
1.553     albertel 3143: 	&delenv('user.state.'.$cid);
1.109     www      3144:     }
                   3145: }
                   3146: 
1.265     albertel 3147: sub get_scalar {
                   3148:     my ($string,$end) = @_;
                   3149:     my $value;
                   3150:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3151: 	$value = $1;
                   3152:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3153: 	$value = $1;
                   3154:     }
                   3155:     return &unescape($value);
                   3156: }
                   3157: 
                   3158: sub array2str {
                   3159:   my (@array) = @_;
                   3160:   my $result=&arrayref2str(\@array);
                   3161:   $result=~s/^__ARRAY_REF__//;
                   3162:   $result=~s/__END_ARRAY_REF__$//;
                   3163:   return $result;
                   3164: }
                   3165: 
1.204     albertel 3166: sub arrayref2str {
                   3167:   my ($arrayref) = @_;
1.265     albertel 3168:   my $result='__ARRAY_REF__';
1.204     albertel 3169:   foreach my $elem (@$arrayref) {
1.265     albertel 3170:     if(ref($elem) eq 'ARRAY') {
                   3171:       $result.=&arrayref2str($elem).'&';
                   3172:     } elsif(ref($elem) eq 'HASH') {
                   3173:       $result.=&hashref2str($elem).'&';
                   3174:     } elsif(ref($elem)) {
                   3175:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3176:     } else {
                   3177:       $result.=&escape($elem).'&';
                   3178:     }
                   3179:   }
                   3180:   $result=~s/\&$//;
1.265     albertel 3181:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3182:   return $result;
                   3183: }
                   3184: 
1.168     albertel 3185: sub hash2str {
1.204     albertel 3186:   my (%hash) = @_;
                   3187:   my $result=&hashref2str(\%hash);
1.265     albertel 3188:   $result=~s/^__HASH_REF__//;
                   3189:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3190:   return $result;
                   3191: }
                   3192: 
                   3193: sub hashref2str {
                   3194:   my ($hashref)=@_;
1.265     albertel 3195:   my $result='__HASH_REF__';
1.800     albertel 3196:   foreach my $key (sort(keys(%$hashref))) {
                   3197:     if (ref($key) eq 'ARRAY') {
                   3198:       $result.=&arrayref2str($key).'=';
                   3199:     } elsif (ref($key) eq 'HASH') {
                   3200:       $result.=&hashref2str($key).'=';
                   3201:     } elsif (ref($key)) {
1.265     albertel 3202:       $result.='=';
1.800     albertel 3203:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3204:     } else {
1.800     albertel 3205: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3206:     }
                   3207: 
1.800     albertel 3208:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3209:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3210:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3211:       $result.=&hashref2str($hashref->{$key}).'&';
                   3212:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3213:        $result.='&';
1.800     albertel 3214:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3215:     } else {
1.800     albertel 3216:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3217:     }
                   3218:   }
1.168     albertel 3219:   $result=~s/\&$//;
1.265     albertel 3220:   $result .= '__END_HASH_REF__';
1.168     albertel 3221:   return $result;
                   3222: }
                   3223: 
                   3224: sub str2hash {
1.265     albertel 3225:     my ($string)=@_;
                   3226:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3227:     return %$hash;
                   3228: }
                   3229: 
                   3230: sub str2hashref {
1.168     albertel 3231:   my ($string) = @_;
1.265     albertel 3232: 
                   3233:   my %hash;
                   3234: 
                   3235:   if($string !~ /^__HASH_REF__/) {
                   3236:       if (! ($string eq '' || !defined($string))) {
                   3237: 	  $hash{'error'}='Not hash reference';
                   3238:       }
                   3239:       return (\%hash, $string);
                   3240:   }
                   3241: 
                   3242:   $string =~ s/^__HASH_REF__//;
                   3243: 
                   3244:   while($string !~ /^__END_HASH_REF__/) {
                   3245:       #key
                   3246:       my $key='';
                   3247:       if($string =~ /^__HASH_REF__/) {
                   3248:           ($key, $string)=&str2hashref($string);
                   3249:           if(defined($key->{'error'})) {
                   3250:               $hash{'error'}='Bad data';
                   3251:               return (\%hash, $string);
                   3252:           }
                   3253:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3254:           ($key, $string)=&str2arrayref($string);
                   3255:           if($key->[0] eq 'Array reference error') {
                   3256:               $hash{'error'}='Bad data';
                   3257:               return (\%hash, $string);
                   3258:           }
                   3259:       } else {
                   3260:           $string =~ s/^(.*?)=//;
1.267     albertel 3261: 	  $key=&unescape($1);
1.265     albertel 3262:       }
                   3263:       $string =~ s/^=//;
                   3264: 
                   3265:       #value
                   3266:       my $value='';
                   3267:       if($string =~ /^__HASH_REF__/) {
                   3268:           ($value, $string)=&str2hashref($string);
                   3269:           if(defined($value->{'error'})) {
                   3270:               $hash{'error'}='Bad data';
                   3271:               return (\%hash, $string);
                   3272:           }
                   3273:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3274:           ($value, $string)=&str2arrayref($string);
                   3275:           if($value->[0] eq 'Array reference error') {
                   3276:               $hash{'error'}='Bad data';
                   3277:               return (\%hash, $string);
                   3278:           }
                   3279:       } else {
                   3280: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3281:       }
                   3282:       $string =~ s/^&//;
                   3283: 
                   3284:       $hash{$key}=$value;
1.204     albertel 3285:   }
1.265     albertel 3286: 
                   3287:   $string =~ s/^__END_HASH_REF__//;
                   3288: 
                   3289:   return (\%hash, $string);
1.204     albertel 3290: }
                   3291: 
                   3292: sub str2array {
1.265     albertel 3293:     my ($string)=@_;
                   3294:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3295:     return @$array;
                   3296: }
                   3297: 
                   3298: sub str2arrayref {
1.204     albertel 3299:   my ($string) = @_;
1.265     albertel 3300:   my @array;
                   3301: 
                   3302:   if($string !~ /^__ARRAY_REF__/) {
                   3303:       if (! ($string eq '' || !defined($string))) {
                   3304: 	  $array[0]='Array reference error';
                   3305:       }
                   3306:       return (\@array, $string);
                   3307:   }
                   3308: 
                   3309:   $string =~ s/^__ARRAY_REF__//;
                   3310: 
                   3311:   while($string !~ /^__END_ARRAY_REF__/) {
                   3312:       my $value='';
                   3313:       if($string =~ /^__HASH_REF__/) {
                   3314:           ($value, $string)=&str2hashref($string);
                   3315:           if(defined($value->{'error'})) {
                   3316:               $array[0] ='Array reference error';
                   3317:               return (\@array, $string);
                   3318:           }
                   3319:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3320:           ($value, $string)=&str2arrayref($string);
                   3321:           if($value->[0] eq 'Array reference error') {
                   3322:               $array[0] ='Array reference error';
                   3323:               return (\@array, $string);
                   3324:           }
                   3325:       } else {
                   3326: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3327:       }
                   3328:       $string =~ s/^&//;
                   3329: 
                   3330:       push(@array, $value);
1.191     harris41 3331:   }
1.265     albertel 3332: 
                   3333:   $string =~ s/^__END_ARRAY_REF__//;
                   3334: 
                   3335:   return (\@array, $string);
1.168     albertel 3336: }
                   3337: 
1.167     albertel 3338: # -------------------------------------------------------------------Temp Store
                   3339: 
1.168     albertel 3340: sub tmpreset {
                   3341:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3342:   if (!$symb) {
                   3343:     $symb=&symbread();
1.620     albertel 3344:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3345:   }
                   3346:   $symb=escape($symb);
                   3347: 
1.620     albertel 3348:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3349:   $namespace=~s/\//\_/g;
                   3350:   $namespace=~s/\W//g;
                   3351: 
1.620     albertel 3352:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3353:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3354:   if ($domain eq 'public' && $stuname eq 'public') {
                   3355:       $stuname=$ENV{'REMOTE_ADDR'};
                   3356:   }
1.168     albertel 3357:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3358:   my %hash;
                   3359:   if (tie(%hash,'GDBM_File',
                   3360: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3361: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3362:     foreach my $key (keys %hash) {
1.180     albertel 3363:       if ($key=~ /:$symb/) {
1.168     albertel 3364: 	delete($hash{$key});
                   3365:       }
                   3366:     }
                   3367:   }
                   3368: }
                   3369: 
1.167     albertel 3370: sub tmpstore {
1.168     albertel 3371:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3372: 
                   3373:   if (!$symb) {
                   3374:     $symb=&symbread();
1.620     albertel 3375:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3376:   }
                   3377:   $symb=escape($symb);
                   3378: 
                   3379:   if (!$namespace) {
                   3380:     # I don't think we would ever want to store this for a course.
                   3381:     # it seems this will only be used if we don't have a course.
1.620     albertel 3382:     #$namespace=$env{'request.course.id'};
1.168     albertel 3383:     #if (!$namespace) {
1.620     albertel 3384:       $namespace=$env{'request.state'};
1.168     albertel 3385:     #}
                   3386:   }
                   3387:   $namespace=~s/\//\_/g;
                   3388:   $namespace=~s/\W//g;
1.620     albertel 3389:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3390:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3391:   if ($domain eq 'public' && $stuname eq 'public') {
                   3392:       $stuname=$ENV{'REMOTE_ADDR'};
                   3393:   }
1.168     albertel 3394:   my $now=time;
                   3395:   my %hash;
                   3396:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3397:   if (tie(%hash,'GDBM_File',
                   3398: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3399: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3400:     $hash{"version:$symb"}++;
                   3401:     my $version=$hash{"version:$symb"};
                   3402:     my $allkeys=''; 
                   3403:     foreach my $key (keys(%$storehash)) {
                   3404:       $allkeys.=$key.':';
1.591     albertel 3405:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3406:     }
                   3407:     $hash{"$version:$symb:timestamp"}=$now;
                   3408:     $allkeys.='timestamp';
                   3409:     $hash{"$version:keys:$symb"}=$allkeys;
                   3410:     if (untie(%hash)) {
                   3411:       return 'ok';
                   3412:     } else {
                   3413:       return "error:$!";
                   3414:     }
                   3415:   } else {
                   3416:     return "error:$!";
                   3417:   }
                   3418: }
1.167     albertel 3419: 
1.168     albertel 3420: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3421: 
1.168     albertel 3422: sub tmprestore {
                   3423:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3424: 
1.168     albertel 3425:   if (!$symb) {
                   3426:     $symb=&symbread();
1.620     albertel 3427:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3428:   }
                   3429:   $symb=escape($symb);
                   3430: 
1.620     albertel 3431:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3432: 
1.620     albertel 3433:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3434:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3435:   if ($domain eq 'public' && $stuname eq 'public') {
                   3436:       $stuname=$ENV{'REMOTE_ADDR'};
                   3437:   }
1.168     albertel 3438:   my %returnhash;
                   3439:   $namespace=~s/\//\_/g;
                   3440:   $namespace=~s/\W//g;
                   3441:   my %hash;
                   3442:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3443:   if (tie(%hash,'GDBM_File',
                   3444: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3445: 	  &GDBM_READER(),0640)) {
1.168     albertel 3446:     my $version=$hash{"version:$symb"};
                   3447:     $returnhash{'version'}=$version;
                   3448:     my $scope;
                   3449:     for ($scope=1;$scope<=$version;$scope++) {
                   3450:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3451:       my @keys=split(/:/,$vkeys);
                   3452:       my $key;
                   3453:       $returnhash{"$scope:keys"}=$vkeys;
                   3454:       foreach $key (@keys) {
1.591     albertel 3455: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3456: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3457:       }
                   3458:     }
1.168     albertel 3459:     if (!(untie(%hash))) {
                   3460:       return "error:$!";
                   3461:     }
                   3462:   } else {
                   3463:     return "error:$!";
                   3464:   }
                   3465:   return %returnhash;
1.167     albertel 3466: }
                   3467: 
1.9       www      3468: # ----------------------------------------------------------------------- Store
                   3469: 
                   3470: sub store {
1.124     www      3471:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3472:     my $home='';
                   3473: 
1.168     albertel 3474:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3475: 
1.213     www      3476:     $symb=&symbclean($symb);
1.122     albertel 3477:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3478: 
1.620     albertel 3479:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3480:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3481: 
                   3482:     &devalidate($symb,$stuname,$domain);
1.109     www      3483: 
                   3484:     $symb=escape($symb);
1.187     www      3485:     if (!$namespace) { 
1.620     albertel 3486:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3487:           return ''; 
                   3488:        } 
                   3489:     }
1.620     albertel 3490:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3491: 
                   3492:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3493:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3494: 
1.12      www      3495:     my $namevalue='';
1.800     albertel 3496:     foreach my $key (keys(%$storehash)) {
                   3497:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3498:     }
1.12      www      3499:     $namevalue=~s/\&$//;
1.187     www      3500:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3501:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3502: }
                   3503: 
1.47      www      3504: # -------------------------------------------------------------- Critical Store
                   3505: 
                   3506: sub cstore {
1.124     www      3507:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3508:     my $home='';
                   3509: 
1.168     albertel 3510:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3511: 
1.213     www      3512:     $symb=&symbclean($symb);
1.122     albertel 3513:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3514: 
1.620     albertel 3515:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3516:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3517: 
                   3518:     &devalidate($symb,$stuname,$domain);
1.109     www      3519: 
                   3520:     $symb=escape($symb);
1.187     www      3521:     if (!$namespace) { 
1.620     albertel 3522:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3523:           return ''; 
                   3524:        } 
                   3525:     }
1.620     albertel 3526:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3527: 
                   3528:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3529:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3530: 
1.47      www      3531:     my $namevalue='';
1.800     albertel 3532:     foreach my $key (keys(%$storehash)) {
                   3533:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3534:     }
1.47      www      3535:     $namevalue=~s/\&$//;
1.187     www      3536:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3537:     return critical
                   3538:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3539: }
                   3540: 
1.9       www      3541: # --------------------------------------------------------------------- Restore
                   3542: 
                   3543: sub restore {
1.124     www      3544:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3545:     my $home='';
                   3546: 
1.168     albertel 3547:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3548: 
1.122     albertel 3549:     if (!$symb) {
                   3550:       unless ($symb=escape(&symbread())) { return ''; }
                   3551:     } else {
1.213     www      3552:       $symb=&escape(&symbclean($symb));
1.122     albertel 3553:     }
1.188     www      3554:     if (!$namespace) { 
1.620     albertel 3555:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3556:           return ''; 
                   3557:        } 
                   3558:     }
1.620     albertel 3559:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3560:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3561:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3562:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3563: 
1.12      www      3564:     my %returnhash=();
1.800     albertel 3565:     foreach my $line (split(/\&/,$answer)) {
                   3566: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3567:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3568:     }
1.75      www      3569:     my $version;
                   3570:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3571:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3572:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3573:        }
1.75      www      3574:     }
1.13      www      3575:     return %returnhash;
1.34      www      3576: }
                   3577: 
                   3578: # ---------------------------------------------------------- Course Description
                   3579: 
                   3580: sub coursedescription {
1.731     albertel 3581:     my ($courseid,$args)=@_;
1.34      www      3582:     $courseid=~s/^\///;
1.49      www      3583:     $courseid=~s/\_/\//g;
1.34      www      3584:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3585:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3586:     my $normalid=$cdomain.'_'.$cnum;
                   3587:     # need to always cache even if we get errors otherwise we keep 
                   3588:     # trying and trying and trying to get the course description.
                   3589:     my %envhash=();
                   3590:     my %returnhash=();
1.731     albertel 3591:     
                   3592:     my $expiretime=600;
                   3593:     if ($env{'request.course.id'} eq $normalid) {
                   3594: 	$expiretime=120;
                   3595:     }
                   3596: 
                   3597:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3598:     if (!$args->{'freshen_cache'}
                   3599: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3600: 	foreach my $key (keys(%env)) {
                   3601: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3602: 	    my ($setting) = $1;
                   3603: 	    $returnhash{$setting} = $env{$key};
                   3604: 	}
                   3605: 	return %returnhash;
                   3606:     }
                   3607: 
                   3608:     # get the data agin
                   3609:     if (!$args->{'one_time'}) {
                   3610: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3611:     }
1.811     albertel 3612: 
1.34      www      3613:     if ($chome ne 'no_host') {
1.302     albertel 3614:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3615:        if (!exists($returnhash{'con_lost'})) {
                   3616:            $returnhash{'home'}= $chome;
                   3617: 	   $returnhash{'domain'} = $cdomain;
                   3618: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3619:            if (!defined($returnhash{'type'})) {
                   3620:                $returnhash{'type'} = 'Course';
                   3621:            }
1.130     albertel 3622:            while (my ($name,$value) = each %returnhash) {
1.53      www      3623:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3624:            }
1.270     www      3625:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3626:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3627: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3628:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3629:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3630:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3631:        }
                   3632:     }
1.731     albertel 3633:     if (!$args->{'one_time'}) {
1.949     raeburn  3634: 	&appenv(\%envhash);
1.731     albertel 3635:     }
1.302     albertel 3636:     return %returnhash;
1.461     www      3637: }
                   3638: 
                   3639: # -------------------------------------------------See if a user is privileged
                   3640: 
                   3641: sub privileged {
                   3642:     my ($username,$domain)=@_;
                   3643:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3644: 			&homeserver($username,$domain));
                   3645:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3646:     my $now=time;
                   3647:     if ($rolesdump ne '') {
1.800     albertel 3648:         foreach my $entry (split(/&/,$rolesdump)) {
                   3649: 	    if ($entry!~/^rolesdef_/) {
                   3650: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3651: 		$area=~s/\_\w\w$//;
                   3652: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3653: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3654: 		    my $active=1;
                   3655: 		    if ($tend) {
                   3656: 			if ($tend<$now) { $active=0; }
                   3657: 		    }
                   3658: 		    if ($tstart) {
                   3659: 			if ($tstart>$now) { $active=0; }
                   3660: 		    }
                   3661: 		    if ($active) { return 1; }
                   3662: 		}
                   3663: 	    }
                   3664: 	}
                   3665:     }
                   3666:     return 0;
1.9       www      3667: }
1.1       albertel 3668: 
1.103     harris41 3669: # -------------------------------------------------------- Get user privileges
1.11      www      3670: 
                   3671: sub rolesinit {
                   3672:     my ($domain,$username,$authhost)=@_;
1.966     raeburn  3673:     my %userroles;
1.11      www      3674:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.966     raeburn  3675:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
1.11      www      3676:     my %allroles=();
1.678     raeburn  3677:     my %allgroups=();   
1.11      www      3678:     my $now=time;
1.966     raeburn  3679:     %userroles = ('user.login.time' => $now);
1.678     raeburn  3680:     my $group_privs;
1.11      www      3681: 
                   3682:     if ($rolesdump ne '') {
1.800     albertel 3683:         foreach my $entry (split(/&/,$rolesdump)) {
                   3684: 	  if ($entry!~/^rolesdef_/) {
                   3685:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3686: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3687:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3688: 	    if ($role=~/^cr/) { 
1.807     albertel 3689: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3690: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3691: 		    ($tend,$tstart)=split('_',$trest);
                   3692: 		} else {
                   3693: 		    $trole=$role;
                   3694: 		}
1.678     raeburn  3695:             } elsif ($role =~ m|^gr/|) {
                   3696:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3697:                 ($trole,$group_privs) = split(/\//,$trole);
                   3698:                 $group_privs = &unescape($group_privs);
1.587     albertel 3699: 	    } else {
                   3700: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3701: 	    }
1.743     albertel 3702: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3703: 					 $username);
                   3704: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3705:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3706:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3707:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3708: 		my $spec=$trole.'.'.$area;
                   3709: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3710: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3711:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3712:                 } elsif ($trole eq 'gr') {
                   3713:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3714: 		} else {
1.567     raeburn  3715:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3716: 		}
1.12      www      3717:             }
1.662     raeburn  3718:           }
1.191     harris41 3719:         }
1.743     albertel 3720:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3721:         $userroles{'user.adv'}    = $adv;
                   3722: 	$userroles{'user.author'} = $author;
1.620     albertel 3723:         $env{'user.adv'}=$adv;
1.11      www      3724:     }
1.743     albertel 3725:     return \%userroles;  
1.11      www      3726: }
                   3727: 
1.567     raeburn  3728: sub set_arearole {
                   3729:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3730: # log the associated role with the area
                   3731:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3732:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3733: }
                   3734: 
                   3735: sub custom_roleprivs {
                   3736:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3737:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3738:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3739:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3740:         my ($rdummy,$roledef)=
                   3741:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3742:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3743:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3744:             if (defined($syspriv)) {
                   3745:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3746:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3747:             }
                   3748:             if ($tdomain ne '') {
                   3749:                 if (defined($dompriv)) {
                   3750:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3751:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3752:                 }
                   3753:                 if (($trest ne '') && (defined($coursepriv))) {
                   3754:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3755:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3756:                 }
                   3757:             }
                   3758:         }
                   3759:     }
                   3760: }
                   3761: 
1.678     raeburn  3762: sub group_roleprivs {
                   3763:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3764:     my $access = 1;
                   3765:     my $now = time;
                   3766:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3767:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3768:     if ($access) {
1.811     albertel 3769:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3770:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3771:     }
                   3772: }
1.567     raeburn  3773: 
                   3774: sub standard_roleprivs {
                   3775:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3776:     if (defined($pr{$trole.':s'})) {
                   3777:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3778:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3779:     }
                   3780:     if ($tdomain ne '') {
                   3781:         if (defined($pr{$trole.':d'})) {
                   3782:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3783:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3784:         }
                   3785:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3786:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3787:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3788:         }
                   3789:     }
                   3790: }
                   3791: 
                   3792: sub set_userprivs {
1.678     raeburn  3793:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3794:     my $author=0;
                   3795:     my $adv=0;
1.678     raeburn  3796:     my %grouproles = ();
                   3797:     if (keys(%{$allgroups}) > 0) {
                   3798:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3799:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3800:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3801:                 $trole = $1;
                   3802:                 $area = $2;
1.681     raeburn  3803:                 $sec = $3;
                   3804:                 $extendedarea = $area.$sec;
                   3805:                 if (exists($$allgroups{$area})) {
                   3806:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3807:                         my $spec = $trole.'.'.$extendedarea;
                   3808:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3809:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3810:                     }
                   3811:                 }
                   3812:             }
                   3813:         }
                   3814:     }
1.800     albertel 3815:     foreach my $group (keys(%grouproles)) {
                   3816:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3817:     }
1.800     albertel 3818:     foreach my $role (keys(%{$allroles})) {
                   3819:         my %thesepriv;
1.941     raeburn  3820:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3821:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3822:             if ($item ne '') {
                   3823:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3824:                 if ($restrictions eq '') {
                   3825:                     $thesepriv{$privilege}='F';
                   3826:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3827:                     $thesepriv{$privilege}.=$restrictions;
                   3828:                 }
                   3829:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3830:             }
                   3831:         }
                   3832:         my $thesestr='';
1.800     albertel 3833:         foreach my $priv (keys(%thesepriv)) {
                   3834: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3835: 	}
                   3836:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3837:     }
                   3838:     return ($author,$adv);
                   3839: }
                   3840: 
1.12      www      3841: # --------------------------------------------------------------- get interface
                   3842: 
                   3843: sub get {
1.131     albertel 3844:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3845:    my $items='';
1.800     albertel 3846:    foreach my $item (@$storearr) {
                   3847:        $items.=&escape($item).'&';
1.191     harris41 3848:    }
1.12      www      3849:    $items=~s/\&$//;
1.620     albertel 3850:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3851:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3852:    my $uhome=&homeserver($uname,$udomain);
                   3853: 
1.133     albertel 3854:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3855:    my @pairs=split(/\&/,$rep);
1.273     albertel 3856:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3857:      return @pairs;
                   3858:    }
1.15      www      3859:    my %returnhash=();
1.42      www      3860:    my $i=0;
1.800     albertel 3861:    foreach my $item (@$storearr) {
                   3862:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3863:       $i++;
1.191     harris41 3864:    }
1.15      www      3865:    return %returnhash;
1.27      www      3866: }
                   3867: 
                   3868: # --------------------------------------------------------------- del interface
                   3869: 
                   3870: sub del {
1.133     albertel 3871:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3872:    my $items='';
1.800     albertel 3873:    foreach my $item (@$storearr) {
                   3874:        $items.=&escape($item).'&';
1.191     harris41 3875:    }
1.27      www      3876:    $items=~s/\&$//;
1.620     albertel 3877:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3878:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3879:    my $uhome=&homeserver($uname,$udomain);
                   3880: 
                   3881:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3882: }
                   3883: 
                   3884: # -------------------------------------------------------------- dump interface
                   3885: 
                   3886: sub dump {
1.755     albertel 3887:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3888:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3889:     if (!$uname) { $uname=$env{'user.name'}; }
                   3890:     my $uhome=&homeserver($uname,$udomain);
                   3891:     if ($regexp) {
                   3892: 	$regexp=&escape($regexp);
                   3893:     } else {
                   3894: 	$regexp='.';
                   3895:     }
                   3896:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3897:     my @pairs=split(/\&/,$rep);
                   3898:     my %returnhash=();
                   3899:     foreach my $item (@pairs) {
                   3900: 	my ($key,$value)=split(/=/,$item,2);
                   3901: 	$key = &unescape($key);
                   3902: 	next if ($key =~ /^error: 2 /);
                   3903: 	$returnhash{$key}=&thaw_unescape($value);
                   3904:     }
                   3905:     return %returnhash;
1.407     www      3906: }
                   3907: 
1.717     albertel 3908: # --------------------------------------------------------- dumpstore interface
                   3909: 
                   3910: sub dumpstore {
                   3911:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3912:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3913:    if (!$uname) { $uname=$env{'user.name'}; }
                   3914:    my $uhome=&homeserver($uname,$udomain);
                   3915:    if ($regexp) {
                   3916:        $regexp=&escape($regexp);
                   3917:    } else {
                   3918:        $regexp='.';
                   3919:    }
                   3920:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3921:    my @pairs=split(/\&/,$rep);
                   3922:    my %returnhash=();
                   3923:    foreach my $item (@pairs) {
                   3924:        my ($key,$value)=split(/=/,$item,2);
                   3925:        next if ($key =~ /^error: 2 /);
                   3926:        $returnhash{$key}=&thaw_unescape($value);
                   3927:    }
                   3928:    return %returnhash;
1.717     albertel 3929: }
                   3930: 
1.407     www      3931: # -------------------------------------------------------------- keys interface
                   3932: 
                   3933: sub getkeys {
                   3934:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3935:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3936:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3937:    my $uhome=&homeserver($uname,$udomain);
                   3938:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3939:    my @keyarray=();
1.800     albertel 3940:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3941:       next if ($key =~ /^error: 2 /);
1.800     albertel 3942:       push(@keyarray,&unescape($key));
1.407     www      3943:    }
                   3944:    return @keyarray;
1.318     matthew  3945: }
                   3946: 
1.319     matthew  3947: # --------------------------------------------------------------- currentdump
                   3948: sub currentdump {
1.328     matthew  3949:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3950:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3951:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3952:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3953:    my $uhome = &homeserver($sname,$sdom);
                   3954:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3955:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3956:    #
1.318     matthew  3957:    my %returnhash=();
1.319     matthew  3958:    #
                   3959:    if ($rep eq "unknown_cmd") { 
                   3960:        # an old lond will not know currentdump
                   3961:        # Do a dump and make it look like a currentdump
1.822     albertel 3962:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3963:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3964:        my %hash = @tmp;
                   3965:        @tmp=();
1.424     matthew  3966:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3967:    } else {
                   3968:        my @pairs=split(/\&/,$rep);
1.800     albertel 3969:        foreach my $pair (@pairs) {
                   3970:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3971:            my ($symb,$param) = split(/:/,$key);
                   3972:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3973:                                                         &thaw_unescape($value);
1.319     matthew  3974:        }
1.191     harris41 3975:    }
1.12      www      3976:    return %returnhash;
1.424     matthew  3977: }
                   3978: 
                   3979: sub convert_dump_to_currentdump{
                   3980:     my %hash = %{shift()};
                   3981:     my %returnhash;
                   3982:     # Code ripped from lond, essentially.  The only difference
                   3983:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3984:     # we might run in to problems with parameter names =~ /^v\./
                   3985:     while (my ($key,$value) = each(%hash)) {
                   3986:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3987: 	$symb  = &unescape($symb);
                   3988: 	$param = &unescape($param);
1.424     matthew  3989:         next if ($v eq 'version' || $symb eq 'keys');
                   3990:         next if (exists($returnhash{$symb}) &&
                   3991:                  exists($returnhash{$symb}->{$param}) &&
                   3992:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3993:         $returnhash{$symb}->{$param}=$value;
                   3994:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3995:     }
                   3996:     #
                   3997:     # Remove all of the keys in the hashes which keep track of
                   3998:     # the version of the parameter.
                   3999:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4000:         # use a foreach because we are going to delete from the hash.
                   4001:         foreach my $key (keys(%$param_hash)) {
                   4002:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4003:         }
                   4004:     }
                   4005:     return \%returnhash;
1.12      www      4006: }
                   4007: 
1.627     albertel 4008: # ------------------------------------------------------ critical inc interface
                   4009: 
                   4010: sub cinc {
                   4011:     return &inc(@_,'critical');
                   4012: }
                   4013: 
1.449     matthew  4014: # --------------------------------------------------------------- inc interface
                   4015: 
                   4016: sub inc {
1.627     albertel 4017:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4018:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4019:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4020:     my $uhome=&homeserver($uname,$udomain);
                   4021:     my $items='';
                   4022:     if (! ref($store)) {
                   4023:         # got a single value, so use that instead
                   4024:         $items = &escape($store).'=&';
                   4025:     } elsif (ref($store) eq 'SCALAR') {
                   4026:         $items = &escape($$store).'=&';        
                   4027:     } elsif (ref($store) eq 'ARRAY') {
                   4028:         $items = join('=&',map {&escape($_);} @{$store});
                   4029:     } elsif (ref($store) eq 'HASH') {
                   4030:         while (my($key,$value) = each(%{$store})) {
                   4031:             $items.= &escape($key).'='.&escape($value).'&';
                   4032:         }
                   4033:     }
                   4034:     $items=~s/\&$//;
1.627     albertel 4035:     if ($critical) {
                   4036: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4037:     } else {
                   4038: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4039:     }
1.449     matthew  4040: }
                   4041: 
1.12      www      4042: # --------------------------------------------------------------- put interface
                   4043: 
                   4044: sub put {
1.134     albertel 4045:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4046:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4047:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4048:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4049:    my $items='';
1.800     albertel 4050:    foreach my $item (keys(%$storehash)) {
                   4051:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4052:    }
1.12      www      4053:    $items=~s/\&$//;
1.134     albertel 4054:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4055: }
                   4056: 
1.631     albertel 4057: # ------------------------------------------------------------ newput interface
                   4058: 
                   4059: sub newput {
                   4060:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4061:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4062:    if (!$uname) { $uname=$env{'user.name'}; }
                   4063:    my $uhome=&homeserver($uname,$udomain);
                   4064:    my $items='';
                   4065:    foreach my $key (keys(%$storehash)) {
                   4066:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4067:    }
                   4068:    $items=~s/\&$//;
                   4069:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4070: }
                   4071: 
                   4072: # ---------------------------------------------------------  putstore interface
                   4073: 
1.524     raeburn  4074: sub putstore {
1.715     albertel 4075:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4076:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4077:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4078:    my $uhome=&homeserver($uname,$udomain);
                   4079:    my $items='';
1.715     albertel 4080:    foreach my $key (keys(%$storehash)) {
                   4081:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4082:    }
1.715     albertel 4083:    $items=~s/\&$//;
1.716     albertel 4084:    my $esc_symb=&escape($symb);
                   4085:    my $esc_v=&escape($version);
1.715     albertel 4086:    my $reply =
1.716     albertel 4087:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4088: 	      $uhome);
                   4089:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4090:        # gfall back to way things use to be done
1.715     albertel 4091:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4092: 			    $uname);
1.524     raeburn  4093:    }
1.715     albertel 4094:    return $reply;
                   4095: }
                   4096: 
                   4097: sub old_putstore {
1.716     albertel 4098:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4099:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4100:     if (!$uname) { $uname=$env{'user.name'}; }
                   4101:     my $uhome=&homeserver($uname,$udomain);
                   4102:     my %newstorehash;
1.800     albertel 4103:     foreach my $item (keys(%$storehash)) {
                   4104: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4105: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4106:     }
                   4107:     my $items='';
                   4108:     my %allitems = ();
1.800     albertel 4109:     foreach my $item (keys(%newstorehash)) {
                   4110: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4111: 	    my $key = $1.':keys:'.$2;
                   4112: 	    $allitems{$key} .= $3.':';
                   4113: 	}
1.800     albertel 4114: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4115:     }
1.800     albertel 4116:     foreach my $item (keys(%allitems)) {
                   4117: 	$allitems{$item} =~ s/\:$//;
                   4118: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4119:     }
                   4120:     $items=~s/\&$//;
                   4121:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4122: }
                   4123: 
1.47      www      4124: # ------------------------------------------------------ critical put interface
                   4125: 
                   4126: sub cput {
1.134     albertel 4127:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4128:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4129:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4130:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4131:    my $items='';
1.800     albertel 4132:    foreach my $item (keys(%$storehash)) {
                   4133:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4134:    }
1.47      www      4135:    $items=~s/\&$//;
1.134     albertel 4136:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4137: }
                   4138: 
                   4139: # -------------------------------------------------------------- eget interface
                   4140: 
                   4141: sub eget {
1.133     albertel 4142:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4143:    my $items='';
1.800     albertel 4144:    foreach my $item (@$storearr) {
                   4145:        $items.=&escape($item).'&';
1.191     harris41 4146:    }
1.12      www      4147:    $items=~s/\&$//;
1.620     albertel 4148:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4149:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4150:    my $uhome=&homeserver($uname,$udomain);
                   4151:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4152:    my @pairs=split(/\&/,$rep);
                   4153:    my %returnhash=();
1.42      www      4154:    my $i=0;
1.800     albertel 4155:    foreach my $item (@$storearr) {
                   4156:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4157:       $i++;
1.191     harris41 4158:    }
1.12      www      4159:    return %returnhash;
                   4160: }
                   4161: 
1.667     albertel 4162: # ------------------------------------------------------------ tmpput interface
                   4163: sub tmpput {
1.802     raeburn  4164:     my ($storehash,$server,$context)=@_;
1.667     albertel 4165:     my $items='';
1.800     albertel 4166:     foreach my $item (keys(%$storehash)) {
                   4167: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4168:     }
                   4169:     $items=~s/\&$//;
1.802     raeburn  4170:     if (defined($context)) {
                   4171:         $items .= ':'.&escape($context);
                   4172:     }
1.667     albertel 4173:     return &reply("tmpput:$items",$server);
                   4174: }
                   4175: 
                   4176: # ------------------------------------------------------------ tmpget interface
                   4177: sub tmpget {
1.688     albertel 4178:     my ($token,$server)=@_;
                   4179:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4180:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4181:     my %returnhash;
                   4182:     foreach my $item (split(/\&/,$rep)) {
                   4183: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4184:         next if ($key =~ /^error: 2 /);
1.667     albertel 4185: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4186:     }
                   4187:     return %returnhash;
                   4188: }
                   4189: 
1.688     albertel 4190: # ------------------------------------------------------------ tmpget interface
                   4191: sub tmpdel {
                   4192:     my ($token,$server)=@_;
                   4193:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4194:     return &reply("tmpdel:$token",$server);
                   4195: }
                   4196: 
1.765     albertel 4197: # -------------------------------------------------- portfolio access checking
                   4198: 
                   4199: sub portfolio_access {
1.766     albertel 4200:     my ($requrl) = @_;
1.765     albertel 4201:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4202:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4203:     if ($result) {
                   4204:         my %setters;
                   4205:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4206:             my ($startblock,$endblock) =
                   4207:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4208:             if ($startblock && $endblock) {
                   4209:                 return 'B';
                   4210:             }
                   4211:         } else {
                   4212:             my ($startblock,$endblock) =
                   4213:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4214:             if ($startblock && $endblock) {
                   4215:                 return 'B';
                   4216:             }
                   4217:         }
                   4218:     }
1.765     albertel 4219:     if ($result eq 'ok') {
1.766     albertel 4220:        return 'F';
1.765     albertel 4221:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4222:        return 'A';
1.765     albertel 4223:     }
1.766     albertel 4224:     return '';
1.765     albertel 4225: }
                   4226: 
                   4227: sub get_portfolio_access {
1.767     albertel 4228:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4229: 
                   4230:     if (!ref($access_hash)) {
                   4231: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4232: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4233: 						   $file_name);
                   4234: 	$access_hash = $access_controls{$file_name};
                   4235:     }
                   4236: 
1.765     albertel 4237:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4238:     my $now = time;
                   4239:     if (ref($access_hash) eq 'HASH') {
                   4240:         foreach my $key (keys(%{$access_hash})) {
                   4241:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4242:             if ($start > $now) {
                   4243:                 next;
                   4244:             }
                   4245:             if ($end && $end<$now) {
                   4246:                 next;
                   4247:             }
                   4248:             if ($scope eq 'public') {
                   4249:                 $public = $key;
                   4250:                 last;
                   4251:             } elsif ($scope eq 'guest') {
                   4252:                 $guest = $key;
                   4253:             } elsif ($scope eq 'domains') {
                   4254:                 push(@domains,$key);
                   4255:             } elsif ($scope eq 'users') {
                   4256:                 push(@users,$key);
                   4257:             } elsif ($scope eq 'course') {
                   4258:                 push(@courses,$key);
                   4259:             } elsif ($scope eq 'group') {
                   4260:                 push(@groups,$key);
                   4261:             }
                   4262:         }
                   4263:         if ($public) {
                   4264:             return 'ok';
                   4265:         }
                   4266:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4267:             if ($guest) {
                   4268:                 return $guest;
                   4269:             }
                   4270:         } else {
                   4271:             if (@domains > 0) {
                   4272:                 foreach my $domkey (@domains) {
                   4273:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4274:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4275:                             return 'ok';
                   4276:                         }
                   4277:                     }
                   4278:                 }
                   4279:             }
                   4280:             if (@users > 0) {
                   4281:                 foreach my $userkey (@users) {
1.865     raeburn  4282:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4283:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4284:                             if (ref($item) eq 'HASH') {
                   4285:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4286:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4287:                                     return 'ok';
                   4288:                                 }
                   4289:                             }
                   4290:                         }
                   4291:                     } 
1.765     albertel 4292:                 }
                   4293:             }
                   4294:             my %roleshash;
                   4295:             my @courses_and_groups = @courses;
                   4296:             push(@courses_and_groups,@groups); 
                   4297:             if (@courses_and_groups > 0) {
                   4298:                 my (%allgroups,%allroles); 
                   4299:                 my ($start,$end,$role,$sec,$group);
                   4300:                 foreach my $envkey (%env) {
1.811     albertel 4301:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4302:                         my $cid = $2.'_'.$3; 
                   4303:                         if ($1 eq 'gr') {
                   4304:                             $group = $4;
                   4305:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4306:                         } else {
                   4307:                             if ($4 eq '') {
                   4308:                                 $sec = 'none';
                   4309:                             } else {
                   4310:                                 $sec = $4;
                   4311:                             }
                   4312:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4313:                         }
1.811     albertel 4314:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4315:                         my $cid = $2.'_'.$3;
                   4316:                         if ($4 eq '') {
                   4317:                             $sec = 'none';
                   4318:                         } else {
                   4319:                             $sec = $4;
                   4320:                         }
                   4321:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4322:                     }
                   4323:                 }
                   4324:                 if (keys(%allroles) == 0) {
                   4325:                     return;
                   4326:                 }
                   4327:                 foreach my $key (@courses_and_groups) {
                   4328:                     my %content = %{$$access_hash{$key}};
                   4329:                     my $cnum = $content{'number'};
                   4330:                     my $cdom = $content{'domain'};
                   4331:                     my $cid = $cdom.'_'.$cnum;
                   4332:                     if (!exists($allroles{$cid})) {
                   4333:                         next;
                   4334:                     }    
                   4335:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4336:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4337:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4338:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4339:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4340:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4341:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4342:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4343:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4344:                                         if (grep/^all$/,@sections) {
                   4345:                                             return 'ok';
                   4346:                                         } else {
                   4347:                                             if (grep/^$sec$/,@sections) {
                   4348:                                                 return 'ok';
                   4349:                                             }
                   4350:                                         }
                   4351:                                     }
                   4352:                                 }
                   4353:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4354:                                     if (grep/^none$/,@groups) {
                   4355:                                         return 'ok';
                   4356:                                     }
                   4357:                                 } else {
                   4358:                                     if (grep/^all$/,@groups) {
                   4359:                                         return 'ok';
                   4360:                                     } 
                   4361:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4362:                                         if (grep/^$group$/,@groups) {
                   4363:                                             return 'ok';
                   4364:                                         }
                   4365:                                     }
                   4366:                                 } 
                   4367:                             }
                   4368:                         }
                   4369:                     }
                   4370:                 }
                   4371:             }
                   4372:             if ($guest) {
                   4373:                 return $guest;
                   4374:             }
                   4375:         }
                   4376:     }
                   4377:     return;
                   4378: }
                   4379: 
                   4380: sub course_group_datechecker {
                   4381:     my ($dates,$now,$status) = @_;
                   4382:     my ($start,$end) = split(/\./,$dates);
                   4383:     if (!$start && !$end) {
                   4384:         return 'ok';
                   4385:     }
                   4386:     if (grep/^active$/,@{$status}) {
                   4387:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4388:             return 'ok';
                   4389:         }
                   4390:     }
                   4391:     if (grep/^previous$/,@{$status}) {
                   4392:         if ($end > $now ) {
                   4393:             return 'ok';
                   4394:         }
                   4395:     }
                   4396:     if (grep/^future$/,@{$status}) {
                   4397:         if ($start > $now) {
                   4398:             return 'ok';
                   4399:         }
                   4400:     }
                   4401:     return; 
                   4402: }
                   4403: 
                   4404: sub parse_portfolio_url {
                   4405:     my ($url) = @_;
                   4406: 
                   4407:     my ($type,$udom,$unum,$group,$file_name);
                   4408:     
1.823     albertel 4409:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4410: 	$type = 1;
                   4411:         $udom = $1;
                   4412:         $unum = $2;
                   4413:         $file_name = $3;
1.823     albertel 4414:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4415: 	$type = 2;
                   4416:         $udom = $1;
                   4417:         $unum = $2;
                   4418:         $group = $3;
                   4419:         $file_name = $3.'/'.$4;
                   4420:     }
                   4421:     if (wantarray) {
                   4422: 	return ($type,$udom,$unum,$file_name,$group);
                   4423:     }
                   4424:     return $type;
                   4425: }
                   4426: 
                   4427: sub is_portfolio_url {
                   4428:     my ($url) = @_;
                   4429:     return scalar(&parse_portfolio_url($url));
                   4430: }
                   4431: 
1.798     raeburn  4432: sub is_portfolio_file {
                   4433:     my ($file) = @_;
1.820     raeburn  4434:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4435:         return 1;
                   4436:     }
                   4437:     return;
                   4438: }
                   4439: 
1.976     raeburn  4440: sub usertools_access {
1.976.2.1  raeburn  4441:     my ($uname,$udom,$tool,$action) = @_;
1.976     raeburn  4442:     my $access;
                   4443:     my %tools = (
                   4444:                   aboutme   => 1,
                   4445:                   blog      => 1,
                   4446:                   portfolio => 1,
                   4447:                 );
                   4448:     return if (!defined($tools{$tool}));
                   4449: 
                   4450:     if ((!defined($udom)) || (!defined($uname))) {
                   4451:         $udom = $env{'user.domain'};
                   4452:         $uname = $env{'user.name'};
                   4453:     }
                   4454: 
1.976.2.1  raeburn  4455:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4456:         if ($action ne 'reload') {
                   4457:             return $env{'environment.availabletools.'.$tool};
                   4458:         }
1.976     raeburn  4459:     }
                   4460: 
                   4461:     my ($toolstatus,$inststatus);
                   4462: 
                   4463:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4464:         $toolstatus = $env{'environment.tools.'.$tool};
                   4465:         $inststatus = $env{'environment.inststatus'};
                   4466:     } else {
                   4467:         my %userenv = &userenvironment($udom,$uname,'tools.'.$tool);
                   4468:         $toolstatus = $userenv{'tools.'.$tool};
                   4469:         $inststatus = $userenv{'inststatus'};
                   4470:     }
                   4471: 
                   4472:     if ($toolstatus ne '') {
                   4473:         if ($toolstatus) {
                   4474:             $access = 1;
                   4475:         } else {
                   4476:             $access = 0;
                   4477:         }
                   4478:         return $access;
                   4479:     }
                   4480: 
                   4481:     my $is_adv = &is_advanced_user($udom,$uname);
                   4482:     my %domdef = &get_domain_defaults($udom);
                   4483:     if (ref($domdef{$tool}) eq 'HASH') {
                   4484:         if ($is_adv) {
                   4485:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   4486:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   4487:                     $access = 1;
                   4488:                 } else {
                   4489:                     $access = 0;
                   4490:                 }
                   4491:                 return $access;
                   4492:             }
                   4493:         }
                   4494:         if ($inststatus ne '') {
                   4495:             my ($hasaccess,$hasnoaccess);
                   4496:             foreach my $affiliation (split(/:/,$inststatus)) {
                   4497:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   4498:                     if ($domdef{$tool}{$affiliation}) {
                   4499:                         $hasaccess = 1;
                   4500:                     } else {
                   4501:                         $hasnoaccess = 1;
                   4502:                     }
                   4503:                 }
                   4504:             }
                   4505:             if ($hasaccess || $hasnoaccess) {
                   4506:                 if ($hasaccess) {
                   4507:                     $access = 1;
                   4508:                 } elsif ($hasnoaccess) {
                   4509:                     $access = 0; 
                   4510:                 }
                   4511:                 return $access;
                   4512:             }
                   4513:         } else {
                   4514:             if ($domdef{$tool}{'default'} ne '') {
                   4515:                 if ($domdef{$tool}{'default'}) {
                   4516:                     $access = 1;
                   4517:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   4518:                     $access = 0;
                   4519:                 }
                   4520:                 return $access;
                   4521:             }
                   4522:         }
                   4523:     } else {
                   4524:         $access = 1;
                   4525:         return $access;
                   4526:     }
                   4527: }
                   4528: 
                   4529: sub is_advanced_user {
                   4530:     my ($udom,$uname) = @_;
                   4531:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   4532:     my %allroles;
                   4533:     my $is_adv;
                   4534:     foreach my $role (keys(%roleshash)) {
                   4535:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   4536:         my $area = '/'.$tdomain.'/'.$trest;
                   4537:         if ($sec ne '') {
                   4538:             $area .= '/'.$sec;
                   4539:         }
                   4540:         if (($area ne '') && ($trole ne '')) {
                   4541:             my $spec=$trole.'.'.$area;
                   4542:             if ($trole =~ /^cr\//) {
                   4543:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4544:             } elsif ($trole ne 'gr') {
                   4545:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4546:             }
                   4547:         }
                   4548:     }
                   4549:     foreach my $role (keys(%allroles)) {
                   4550:         last if ($is_adv);
                   4551:         foreach my $item (split(/:/,$allroles{$role})) {
                   4552:             if ($item ne '') {
                   4553:                 my ($privilege,$restrictions)=split(/&/,$item);
                   4554:                 if ($privilege eq 'adv') {
                   4555:                     $is_adv = 1;
                   4556:                     last;
                   4557:                 }
                   4558:             }
                   4559:         }
                   4560:     }
                   4561:     return $is_adv;
                   4562: }
1.798     raeburn  4563: 
1.341     www      4564: # ---------------------------------------------- Custom access rule evaluation
                   4565: 
                   4566: sub customaccess {
                   4567:     my ($priv,$uri)=@_;
1.807     albertel 4568:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4569:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4570:     $udom = &LONCAPA::clean_domain($udom);
                   4571:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4572:     my $access=0;
1.800     albertel 4573:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4574: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4575: 	if ($type eq 'user') {
                   4576: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4577: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4578: 		if ($tdom) {
                   4579: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4580: 		}
1.896     albertel 4581: 		if ($tuname) {
                   4582: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4583: 		}
                   4584: 		$access=($effect eq 'allow');
                   4585: 		last;
                   4586: 	    }
                   4587: 	} else {
                   4588: 	    if ($role) {
                   4589: 		if ($role ne $urole) { next; }
                   4590: 	    }
                   4591: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4592: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4593: 		if ($tdom) {
                   4594: 		    if ($tdom ne $udom) { next; }
                   4595: 		}
                   4596: 		if ($tcrs) {
                   4597: 		    if ($tcrs ne $ucrs) { next; }
                   4598: 		}
                   4599: 		if ($tsec) {
                   4600: 		    if ($tsec ne $usec) { next; }
                   4601: 		}
                   4602: 		$access=($effect eq 'allow');
                   4603: 		last;
                   4604: 	    }
                   4605: 	    if ($realm eq '' && $role eq '') {
                   4606: 		$access=($effect eq 'allow');
                   4607: 	    }
1.402     bowersj2 4608: 	}
1.341     www      4609:     }
                   4610:     return $access;
                   4611: }
                   4612: 
1.103     harris41 4613: # ------------------------------------------------- Check for a user privilege
1.12      www      4614: 
                   4615: sub allowed {
1.810     raeburn  4616:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4617:     my $ver_orguri=$uri;
1.439     www      4618:     $uri=&deversion($uri);
1.152     www      4619:     my $orguri=$uri;
1.52      www      4620:     $uri=&declutter($uri);
1.809     raeburn  4621: 
1.810     raeburn  4622:     if ($priv eq 'evb') {
                   4623: # Evade communication block restrictions for specified role in a course
                   4624:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4625:             return $1;
                   4626:         } else {
                   4627:             return;
                   4628:         }
                   4629:     }
                   4630: 
1.620     albertel 4631:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4632: # Free bre access to adm and meta resources
1.775     albertel 4633:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4634: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4635: 	&& ($priv eq 'bre')) {
1.14      www      4636: 	return 'F';
1.159     www      4637:     }
                   4638: 
1.545     banghart 4639: # Free bre access to user's own portfolio contents
1.714     raeburn  4640:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4641:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4642: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4643:         my %setters;
                   4644:         my ($startblock,$endblock) = 
                   4645:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4646:         if ($startblock && $endblock) {
                   4647:             return 'B';
                   4648:         } else {
                   4649:             return 'F';
                   4650:         }
1.545     banghart 4651:     }
                   4652: 
1.762     raeburn  4653: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4654:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4655:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4656:         if (exists($env{'request.course.id'})) {
                   4657:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4658:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4659:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4660:                 my $courseprivid=$env{'request.course.id'};
                   4661:                 $courseprivid=~s/\_/\//;
                   4662:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4663:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4664:                     return $1; 
1.762     raeburn  4665:                 } else {
                   4666:                     if ($env{'request.course.sec'}) {
                   4667:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4668:                     }
                   4669:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4670:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4671:                         return $2;
                   4672:                     }
1.714     raeburn  4673:                 }
                   4674:             }
                   4675:         }
                   4676:     }
                   4677: 
1.159     www      4678: # Free bre to public access
                   4679: 
                   4680:     if ($priv eq 'bre') {
1.238     www      4681:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4682: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4683:            return 'F'; 
                   4684:         }
1.238     www      4685:         if ($copyright eq 'priv') {
                   4686:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4687: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4688: 		return '';
                   4689:             }
                   4690:         }
                   4691:         if ($copyright eq 'domain') {
                   4692:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4693: 	    unless (($env{'user.domain'} eq $1) ||
                   4694:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4695: 		return '';
                   4696:             }
1.262     matthew  4697:         }
1.620     albertel 4698:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4699:             # Library role, so allow browsing of resources in this domain.
                   4700:             return 'F';
1.238     www      4701:         }
1.341     www      4702:         if ($copyright eq 'custom') {
                   4703: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4704:         }
1.14      www      4705:     }
1.264     matthew  4706:     # Domain coordinator is trying to create a course
1.620     albertel 4707:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4708:         # uri is the requested domain in this case.
                   4709:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4710:         # a role of dc for the domain in question.
1.620     albertel 4711:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4712:     }
1.29      www      4713: 
1.52      www      4714:     my $thisallowed='';
                   4715:     my $statecond=0;
                   4716:     my $courseprivid='';
                   4717: 
                   4718: # Course
                   4719: 
1.620     albertel 4720:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4721:        $thisallowed.=$1;
                   4722:     }
1.29      www      4723: 
1.52      www      4724: # Domain
                   4725: 
1.620     albertel 4726:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4727:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4728:        $thisallowed.=$1;
                   4729:     }
1.52      www      4730: 
                   4731: # Course: uri itself is a course
1.66      www      4732:     my $courseuri=$uri;
                   4733:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4734:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4735: 
1.620     albertel 4736:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4737:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4738:        $thisallowed.=$1;
                   4739:     }
1.29      www      4740: 
1.665     albertel 4741: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4742: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4743:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4744: 	$thisallowed='';
1.671     raeburn  4745:         my ($match)=&is_on_map($uri);
                   4746:         if ($match) {
                   4747:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4748:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4749:                 $thisallowed.=$1;
                   4750:             }
                   4751:         } else {
1.705     albertel 4752:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4753:             if ($refuri) {
                   4754:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4755:                     $thisallowed='F';
1.671     raeburn  4756:                 } else {
                   4757:                     $refuri=&declutter($refuri);
                   4758:                     my ($match) = &is_on_map($refuri);
                   4759:                     if ($match) {
                   4760:                         $thisallowed='F';
                   4761:                     }
1.669     raeburn  4762:                 }
1.671     raeburn  4763:             }
                   4764:         }
1.314     www      4765:     }
1.492     albertel 4766: 
1.766     albertel 4767:     if ($priv eq 'bre'
                   4768: 	&& $thisallowed ne 'F' 
                   4769: 	&& $thisallowed ne '2'
                   4770: 	&& &is_portfolio_url($uri)) {
                   4771: 	$thisallowed = &portfolio_access($uri);
                   4772:     }
                   4773:     
1.52      www      4774: # Full access at system, domain or course-wide level? Exit.
1.29      www      4775:     if ($thisallowed=~/F/) {
                   4776: 	return 'F';
                   4777:     }
                   4778: 
1.52      www      4779: # If this is generating or modifying users, exit with special codes
1.29      www      4780: 
1.643     www      4781:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4782: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4783: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4784: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4785: 	    unless ($auname) { return $thisallowed; }
                   4786: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4787: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4788: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4789: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4790: 	}
1.52      www      4791: 	return $thisallowed;
                   4792:     }
                   4793: #
1.103     harris41 4794: # Gathered so far: system, domain and course wide privileges
1.52      www      4795: #
                   4796: # Course: See if uri or referer is an individual resource that is part of 
                   4797: # the course
                   4798: 
1.620     albertel 4799:     if ($env{'request.course.id'}) {
1.232     www      4800: 
1.620     albertel 4801:        $courseprivid=$env{'request.course.id'};
                   4802:        if ($env{'request.course.sec'}) {
                   4803:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4804:        }
                   4805:        $courseprivid=~s/\_/\//;
                   4806:        my $checkreferer=1;
1.232     www      4807:        my ($match,$cond)=&is_on_map($uri);
                   4808:        if ($match) {
                   4809:            $statecond=$cond;
1.620     albertel 4810:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4811:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4812:                $thisallowed.=$1;
                   4813:                $checkreferer=0;
                   4814:            }
1.29      www      4815:        }
1.83      www      4816:        
1.148     www      4817:        if ($checkreferer) {
1.620     albertel 4818: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4819:             unless ($refuri) {
1.800     albertel 4820:                 foreach my $key (keys(%env)) {
                   4821: 		    if ($key=~/^httpref\..*\*/) {
                   4822: 			my $pattern=$key;
1.156     www      4823:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4824:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4825:                         $pattern=~s/\//\\\//g;
1.152     www      4826:                         if ($orguri=~/$pattern/) {
1.800     albertel 4827: 			    $refuri=$env{$key};
1.148     www      4828:                         }
                   4829:                     }
1.191     harris41 4830:                 }
1.148     www      4831:             }
1.232     www      4832: 
1.148     www      4833:          if ($refuri) { 
1.152     www      4834: 	  $refuri=&declutter($refuri);
1.232     www      4835:           my ($match,$cond)=&is_on_map($refuri);
                   4836:             if ($match) {
                   4837:               my $refstatecond=$cond;
1.620     albertel 4838:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4839:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4840:                   $thisallowed.=$1;
1.53      www      4841:                   $uri=$refuri;
                   4842:                   $statecond=$refstatecond;
1.52      www      4843:               }
                   4844:           }
1.148     www      4845:         }
1.29      www      4846:        }
1.52      www      4847:    }
1.29      www      4848: 
1.52      www      4849: #
1.103     harris41 4850: # Gathered now: all privileges that could apply, and condition number
1.52      www      4851: # 
                   4852: #
                   4853: # Full or no access?
                   4854: #
1.29      www      4855: 
1.52      www      4856:     if ($thisallowed=~/F/) {
                   4857: 	return 'F';
                   4858:     }
1.29      www      4859: 
1.52      www      4860:     unless ($thisallowed) {
                   4861:         return '';
                   4862:     }
1.29      www      4863: 
1.52      www      4864: # Restrictions exist, deal with them
                   4865: #
                   4866: #   C:according to course preferences
                   4867: #   R:according to resource settings
                   4868: #   L:unless locked
                   4869: #   X:according to user session state
                   4870: #
                   4871: 
                   4872: # Possibly locked functionality, check all courses
1.54      www      4873: # Locks might take effect only after 10 minutes cache expiration for other
                   4874: # courses, and 2 minutes for current course
1.52      www      4875: 
                   4876:     my $envkey;
                   4877:     if ($thisallowed=~/L/) {
1.620     albertel 4878:         foreach $envkey (keys %env) {
1.54      www      4879:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4880:                my $courseid=$2;
                   4881:                my $roleid=$1.'.'.$2;
1.92      www      4882:                $courseid=~s/^\///;
1.54      www      4883:                my $expiretime=600;
1.620     albertel 4884:                if ($env{'request.role'} eq $roleid) {
1.54      www      4885: 		  $expiretime=120;
                   4886:                }
                   4887: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4888:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4889:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4890: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4891:                }
1.620     albertel 4892:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4893:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4894: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4895:                        &log($env{'user.domain'},$env{'user.name'},
                   4896:                             $env{'user.home'},
1.57      www      4897:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4898:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4899:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4900: 		       return '';
                   4901:                    }
                   4902:                }
1.620     albertel 4903:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4904:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4905: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4906:                        &log($env{'user.domain'},$env{'user.name'},
                   4907:                             $env{'user.home'},
1.57      www      4908:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4909:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4910:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4911: 		       return '';
                   4912:                    }
                   4913:                }
                   4914: 	   }
1.29      www      4915:        }
1.52      www      4916:     }
                   4917:    
                   4918: #
                   4919: # Rest of the restrictions depend on selected course
                   4920: #
                   4921: 
1.620     albertel 4922:     unless ($env{'request.course.id'}) {
1.766     albertel 4923: 	if ($thisallowed eq 'A') {
                   4924: 	    return 'A';
1.814     raeburn  4925:         } elsif ($thisallowed eq 'B') {
                   4926:             return 'B';
1.766     albertel 4927: 	} else {
                   4928: 	    return '1';
                   4929: 	}
1.52      www      4930:     }
1.29      www      4931: 
1.52      www      4932: #
                   4933: # Now user is definitely in a course
                   4934: #
1.53      www      4935: 
                   4936: 
                   4937: # Course preferences
                   4938: 
                   4939:    if ($thisallowed=~/C/) {
1.620     albertel 4940:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4941:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4942:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4943: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4944: 	   if ($priv ne 'pch') { 
                   4945: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4946: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4947: 			$env{'request.course.id'});
                   4948: 	   }
1.237     www      4949:            return '';
                   4950:        }
                   4951: 
1.620     albertel 4952:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4953: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4954: 	   if ($priv ne 'pch') { 
                   4955: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4956: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4957: 			$env{'request.course.id'});
                   4958: 	   }
1.54      www      4959:            return '';
                   4960:        }
1.53      www      4961:    }
                   4962: 
                   4963: # Resource preferences
                   4964: 
                   4965:    if ($thisallowed=~/R/) {
1.620     albertel 4966:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4967:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4968: 	   if ($priv ne 'pch') { 
                   4969: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4970: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4971: 	   }
                   4972: 	   return '';
1.54      www      4973:        }
1.53      www      4974:    }
1.30      www      4975: 
1.246     www      4976: # Restricted by state or randomout?
1.30      www      4977: 
1.52      www      4978:    if ($thisallowed=~/X/) {
1.620     albertel 4979:       if ($env{'acc.randomout'}) {
1.579     albertel 4980: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4981:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4982:             return ''; 
                   4983:          }
1.247     www      4984:       }
                   4985:       if (&condval($statecond)) {
1.52      www      4986: 	 return '2';
                   4987:       } else {
                   4988:          return '';
                   4989:       }
                   4990:    }
1.30      www      4991: 
1.766     albertel 4992:     if ($thisallowed eq 'A') {
                   4993: 	return 'A';
1.814     raeburn  4994:     } elsif ($thisallowed eq 'B') {
                   4995:         return 'B';
1.766     albertel 4996:     }
1.52      www      4997:    return 'F';
1.232     www      4998: }
                   4999: 
1.710     albertel 5000: sub split_uri_for_cond {
                   5001:     my $uri=&deversion(&declutter(shift));
                   5002:     my @uriparts=split(/\//,$uri);
                   5003:     my $filename=pop(@uriparts);
                   5004:     my $pathname=join('/',@uriparts);
                   5005:     return ($pathname,$filename);
                   5006: }
1.232     www      5007: # --------------------------------------------------- Is a resource on the map?
                   5008: 
                   5009: sub is_on_map {
1.710     albertel 5010:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5011:     #Trying to find the conditional for the file
1.620     albertel 5012:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5013: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5014:     if ($match) {
1.289     bowersj2 5015: 	return (1,$1);
                   5016:     } else {
1.434     www      5017: 	return (0,0);
1.289     bowersj2 5018:     }
1.12      www      5019: }
                   5020: 
1.427     www      5021: # --------------------------------------------------------- Get symb from alias
                   5022: 
                   5023: sub get_symb_from_alias {
                   5024:     my $symb=shift;
                   5025:     my ($map,$resid,$url)=&decode_symb($symb);
                   5026: # Already is a symb
                   5027:     if ($url) { return $symb; }
                   5028: # Must be an alias
                   5029:     my $aliassymb='';
                   5030:     my %bighash;
1.620     albertel 5031:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5032:                             &GDBM_READER(),0640)) {
                   5033:         my $rid=$bighash{'mapalias_'.$symb};
                   5034: 	if ($rid) {
                   5035: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5036: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5037: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5038: 	}
                   5039:         untie %bighash;
                   5040:     }
                   5041:     return $aliassymb;
                   5042: }
                   5043: 
1.12      www      5044: # ----------------------------------------------------------------- Define Role
                   5045: 
                   5046: sub definerole {
                   5047:   if (allowed('mcr','/')) {
                   5048:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5049:     foreach my $role (split(':',$sysrole)) {
                   5050: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5051:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5052:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5053: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5054:                return "refused:s:$crole&$cqual"; 
                   5055:             }
                   5056:         }
1.191     harris41 5057:     }
1.800     albertel 5058:     foreach my $role (split(':',$domrole)) {
                   5059: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5060:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5061:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5062: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5063:                return "refused:d:$crole&$cqual"; 
                   5064:             }
                   5065:         }
1.191     harris41 5066:     }
1.800     albertel 5067:     foreach my $role (split(':',$courole)) {
                   5068: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5069:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5070:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5071: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5072:                return "refused:c:$crole&$cqual"; 
                   5073:             }
                   5074:         }
1.191     harris41 5075:     }
1.620     albertel 5076:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5077:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5078: 	        "rolesdef_$rolename=".
                   5079:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5080:     return reply($command,$env{'user.home'});
1.12      www      5081:   } else {
                   5082:     return 'refused';
                   5083:   }
1.105     harris41 5084: }
                   5085: 
                   5086: # ---------------- Make a metadata query against the network of library servers
                   5087: 
                   5088: sub metadata_query {
1.244     matthew  5089:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5090:     my %rhash;
1.845     albertel 5091:     my %libserv = &all_library();
1.244     matthew  5092:     my @server_list = (defined($server_array) ? @$server_array
                   5093:                                               : keys(%libserv) );
                   5094:     for my $server (@server_list) {
1.118     harris41 5095: 	unless ($custom or $customshow) {
                   5096: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5097: 	    $rhash{$server}=$reply;
                   5098: 	}
                   5099: 	else {
                   5100: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5101: 			     &escape($custom).':'.&escape($customshow),
                   5102: 			     $server);
                   5103: 	    $rhash{$server}=$reply;
                   5104: 	}
1.112     harris41 5105:     }
1.118     harris41 5106:     return \%rhash;
1.240     www      5107: }
                   5108: 
                   5109: # ----------------------------------------- Send log queries and wait for reply
                   5110: 
                   5111: sub log_query {
                   5112:     my ($uname,$udom,$query,%filters)=@_;
                   5113:     my $uhome=&homeserver($uname,$udom);
                   5114:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5115:     my $uhost=&hostname($uhome);
1.800     albertel 5116:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5117:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5118:                        $uhome);
1.479     albertel 5119:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5120:     return get_query_reply($queryid);
                   5121: }
                   5122: 
1.818     raeburn  5123: # -------------------------- Update MySQL table for portfolio file
                   5124: 
                   5125: sub update_portfolio_table {
1.821     raeburn  5126:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5127:     if ($group ne '') {
                   5128:         $file_name =~s /^\Q$group\E//;
                   5129:     }
1.818     raeburn  5130:     my $homeserver = &homeserver($uname,$udom);
                   5131:     my $queryid=
1.821     raeburn  5132:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5133:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5134:     my $reply = &get_query_reply($queryid);
                   5135:     return $reply;
                   5136: }
                   5137: 
1.899     raeburn  5138: # -------------------------- Update MySQL allusers table
                   5139: 
                   5140: sub update_allusers_table {
                   5141:     my ($uname,$udom,$names) = @_;
                   5142:     my $homeserver = &homeserver($uname,$udom);
                   5143:     my $queryid=
                   5144:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5145:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5146:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5147:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5148:                'generation='.&escape($names->{'generation'}).'%%'.
                   5149:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5150:                'id='.&escape($names->{'id'}),$homeserver);
                   5151:     my $reply = &get_query_reply($queryid);
                   5152:     return $reply;
                   5153: }
                   5154: 
1.508     raeburn  5155: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5156: 
                   5157: sub fetch_enrollment_query {
1.511     raeburn  5158:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5159:     my $homeserver;
1.547     raeburn  5160:     my $maxtries = 1;
1.508     raeburn  5161:     if ($context eq 'automated') {
                   5162:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5163:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5164:     } else {
                   5165:         $homeserver = &homeserver($cnum,$dom);
                   5166:     }
1.838     albertel 5167:     my $host=&hostname($homeserver);
1.506     raeburn  5168:     my $cmd = '';
1.800     albertel 5169:     foreach my $affiliate (keys %{$affiliatesref}) {
                   5170:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5171:     }
                   5172:     $cmd =~ s/%%$//;
                   5173:     $cmd = &escape($cmd);
                   5174:     my $query = 'fetchenrollment';
1.620     albertel 5175:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5176:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5177:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5178:         return 'error: '.$queryid;
                   5179:     }
1.506     raeburn  5180:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5181:     my $tries = 1;
                   5182:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5183:         $reply = &get_query_reply($queryid);
                   5184:         $tries ++;
                   5185:     }
1.526     raeburn  5186:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5187:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5188:     } else {
1.901     albertel 5189:         my @responses = split(/:/,$reply);
1.515     raeburn  5190:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5191:             foreach my $line (@responses) {
                   5192:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5193:                 $$replyref{$key} = $value;
                   5194:             }
                   5195:         } else {
1.506     raeburn  5196:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5197:             foreach my $line (@responses) {
                   5198:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5199:                 $$replyref{$key} = $value;
                   5200:                 if ($value > 0) {
1.800     albertel 5201:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5202:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5203:                         my $destname = $pathname.'/'.$filename;
                   5204:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5205:                         if ($xml_classlist =~ /^error/) {
                   5206:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5207:                         } else {
1.506     raeburn  5208:                             if ( open(FILE,">$destname") ) {
                   5209:                                 print FILE &unescape($xml_classlist);
                   5210:                                 close(FILE);
1.526     raeburn  5211:                             } else {
                   5212:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5213:                             }
                   5214:                         }
                   5215:                     }
                   5216:                 }
                   5217:             }
                   5218:         }
                   5219:         return 'ok';
                   5220:     }
                   5221:     return 'error';
                   5222: }
                   5223: 
1.242     www      5224: sub get_query_reply {
                   5225:     my $queryid=shift;
1.240     www      5226:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5227:     my $reply='';
                   5228:     for (1..100) {
                   5229: 	sleep 2;
                   5230:         if (-e $replyfile.'.end') {
1.448     albertel 5231: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5232: 		$reply = join('',<$fh>);
                   5233: 		close($fh);
1.240     www      5234: 	   } else { return 'error: reply_file_error'; }
1.242     www      5235:            return &unescape($reply);
                   5236: 	}
1.240     www      5237:     }
1.242     www      5238:     return 'timeout:'.$queryid;
1.240     www      5239: }
                   5240: 
                   5241: sub courselog_query {
1.241     www      5242: #
                   5243: # possible filters:
                   5244: # url: url or symb
                   5245: # username
                   5246: # domain
                   5247: # action: view, submit, grade
                   5248: # start: timestamp
                   5249: # end: timestamp
                   5250: #
1.240     www      5251:     my (%filters)=@_;
1.620     albertel 5252:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5253:     if ($filters{'url'}) {
                   5254: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5255:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5256:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5257:     }
1.620     albertel 5258:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5259:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5260:     return &log_query($cname,$cdom,'courselog',%filters);
                   5261: }
                   5262: 
                   5263: sub userlog_query {
1.858     raeburn  5264: #
                   5265: # possible filters:
                   5266: # action: log check role
                   5267: # start: timestamp
                   5268: # end: timestamp
                   5269: #
1.240     www      5270:     my ($uname,$udom,%filters)=@_;
                   5271:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5272: }
                   5273: 
1.506     raeburn  5274: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5275: 
                   5276: sub auto_run {
1.508     raeburn  5277:     my ($cnum,$cdom) = @_;
1.876     raeburn  5278:     my $response = 0;
                   5279:     my $settings;
                   5280:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5281:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5282:         $settings = $domconfig{'autoenroll'};
                   5283:         if ($settings->{'run'} eq '1') {
                   5284:             $response = 1;
                   5285:         }
                   5286:     } else {
1.934     raeburn  5287:         my $homeserver;
                   5288:         if (&is_course($cdom,$cnum)) {
                   5289:             $homeserver = &homeserver($cnum,$cdom);
                   5290:         } else {
                   5291:             $homeserver = &domain($cdom,'primary');
                   5292:         }
                   5293:         if ($homeserver ne 'no_host') {
                   5294:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5295:         }
1.876     raeburn  5296:     }
1.506     raeburn  5297:     return $response;
                   5298: }
1.776     albertel 5299: 
1.506     raeburn  5300: sub auto_get_sections {
1.508     raeburn  5301:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   5302:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  5303:     my @secs = ();
1.511     raeburn  5304:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  5305:     unless ($response eq 'refused') {
1.901     albertel 5306:         @secs = split(/:/,$response);
1.506     raeburn  5307:     }
                   5308:     return @secs;
                   5309: }
1.776     albertel 5310: 
1.506     raeburn  5311: sub auto_new_course {
1.508     raeburn  5312:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5313:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5314:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5315:     return $response;
                   5316: }
1.776     albertel 5317: 
1.506     raeburn  5318: sub auto_validate_courseID {
1.508     raeburn  5319:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5320:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5321:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5322:     return $response;
                   5323: }
1.776     albertel 5324: 
1.506     raeburn  5325: sub auto_create_password {
1.873     raeburn  5326:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5327:     my ($homeserver,$response);
1.506     raeburn  5328:     my $create_passwd = 0;
                   5329:     my $authchk = '';
1.873     raeburn  5330:     if ($udom =~ /^$match_domain$/) {
                   5331:         $homeserver = &domain($udom,'primary');
                   5332:     }
                   5333:     if ($homeserver eq '') {
                   5334:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5335:             $homeserver = &homeserver($cnum,$cdom);
                   5336:         }
                   5337:     }
                   5338:     if ($homeserver eq '') {
                   5339:         $authchk = 'nodomain';
1.506     raeburn  5340:     } else {
1.873     raeburn  5341:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5342:         if ($response eq 'refused') {
                   5343:             $authchk = 'refused';
                   5344:         } else {
1.901     albertel 5345:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5346:         }
1.506     raeburn  5347:     }
                   5348:     return ($authparam,$create_passwd,$authchk);
                   5349: }
                   5350: 
1.706     raeburn  5351: sub auto_photo_permission {
                   5352:     my ($cnum,$cdom,$students) = @_;
                   5353:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5354:     my ($outcome,$perm_reqd,$conditions) = 
                   5355: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5356:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5357: 	return (undef,undef);
                   5358:     }
1.706     raeburn  5359:     return ($outcome,$perm_reqd,$conditions);
                   5360: }
                   5361: 
                   5362: sub auto_checkphotos {
                   5363:     my ($uname,$udom,$pid) = @_;
                   5364:     my $homeserver = &homeserver($uname,$udom);
                   5365:     my ($result,$resulttype);
                   5366:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5367: 				   &escape($uname).':'.&escape($pid),
                   5368: 				   $homeserver));
1.709     albertel 5369:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5370: 	return (undef,undef);
                   5371:     }
1.706     raeburn  5372:     if ($outcome) {
                   5373:         ($result,$resulttype) = split(/:/,$outcome);
                   5374:     } 
                   5375:     return ($result,$resulttype);
                   5376: }
                   5377: 
                   5378: sub auto_photochoice {
                   5379:     my ($cnum,$cdom) = @_;
                   5380:     my $homeserver = &homeserver($cnum,$cdom);
                   5381:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5382: 						       &escape($cdom),
                   5383: 						       $homeserver)));
1.709     albertel 5384:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5385: 	return (undef,undef);
                   5386:     }
1.706     raeburn  5387:     return ($update,$comment);
                   5388: }
                   5389: 
                   5390: sub auto_photoupdate {
                   5391:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5392:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5393:     my $host=&hostname($homeserver);
1.706     raeburn  5394:     my $cmd = '';
                   5395:     my $maxtries = 1;
1.800     albertel 5396:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5397:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5398:     }
                   5399:     $cmd =~ s/%%$//;
                   5400:     $cmd = &escape($cmd);
                   5401:     my $query = 'institutionalphotos';
                   5402:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5403:     unless ($queryid=~/^\Q$host\E\_/) {
                   5404:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5405:         return 'error: '.$queryid;
                   5406:     }
                   5407:     my $reply = &get_query_reply($queryid);
                   5408:     my $tries = 1;
                   5409:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5410:         $reply = &get_query_reply($queryid);
                   5411:         $tries ++;
                   5412:     }
                   5413:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5414:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5415:     } else {
                   5416:         my @responses = split(/:/,$reply);
                   5417:         my $outcome = shift(@responses); 
                   5418:         foreach my $item (@responses) {
                   5419:             my ($key,$value) = split(/=/,$item);
                   5420:             $$photo{$key} = $value;
                   5421:         }
                   5422:         return $outcome;
                   5423:     }
                   5424:     return 'error';
                   5425: }
                   5426: 
1.521     raeburn  5427: sub auto_instcode_format {
1.793     albertel 5428:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5429: 	$cat_order) = @_;
1.521     raeburn  5430:     my $courses = '';
1.772     raeburn  5431:     my @homeservers;
1.521     raeburn  5432:     if ($caller eq 'global') {
1.841     albertel 5433: 	my %servers = &get_servers($codedom,'library');
                   5434: 	foreach my $tryserver (keys(%servers)) {
                   5435: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5436: 		push(@homeservers,$tryserver);
                   5437: 	    }
1.584     raeburn  5438:         }
1.521     raeburn  5439:     } else {
1.772     raeburn  5440:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5441:     }
1.793     albertel 5442:     foreach my $code (keys(%{$instcodes})) {
                   5443:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5444:     }
                   5445:     chop($courses);
1.772     raeburn  5446:     my $ok_response = 0;
                   5447:     my $response;
                   5448:     while (@homeservers > 0 && $ok_response == 0) {
                   5449:         my $server = shift(@homeservers); 
                   5450:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5451:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5452:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5453: 		split(/:/,$response);
1.772     raeburn  5454:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5455:             push(@{$codetitles},&str2array($codetitles_str));
                   5456:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5457:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5458:             $ok_response = 1;
                   5459:         }
                   5460:     }
                   5461:     if ($ok_response) {
1.521     raeburn  5462:         return 'ok';
1.772     raeburn  5463:     } else {
                   5464:         return $response;
1.521     raeburn  5465:     }
                   5466: }
                   5467: 
1.792     raeburn  5468: sub auto_instcode_defaults {
                   5469:     my ($domain,$returnhash,$code_order) = @_;
                   5470:     my @homeservers;
1.841     albertel 5471: 
                   5472:     my %servers = &get_servers($domain,'library');
                   5473:     foreach my $tryserver (keys(%servers)) {
                   5474: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5475: 	    push(@homeservers,$tryserver);
                   5476: 	}
1.792     raeburn  5477:     }
1.841     albertel 5478: 
1.792     raeburn  5479:     my $response;
1.841     albertel 5480:     foreach my $server (@homeservers) {
1.792     raeburn  5481:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5482:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5483: 	
                   5484: 	foreach my $pair (split(/\&/,$response)) {
                   5485: 	    my ($name,$value)=split(/\=/,$pair);
                   5486: 	    if ($name eq 'code_order') {
                   5487: 		@{$code_order} = split(/\&/,&unescape($value));
                   5488: 	    } else {
                   5489: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5490: 	    }
                   5491: 	}
                   5492: 	return 'ok';
1.792     raeburn  5493:     }
1.841     albertel 5494: 
                   5495:     return $response;
1.792     raeburn  5496: } 
                   5497: 
1.777     albertel 5498: sub auto_validate_class_sec {
1.918     raeburn  5499:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5500:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5501:     my $ownerlist;
                   5502:     if (ref($owners) eq 'ARRAY') {
                   5503:         $ownerlist = join(',',@{$owners});
                   5504:     } else {
                   5505:         $ownerlist = $owners;
                   5506:     }
1.773     raeburn  5507:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5508:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5509:     return $response;
                   5510: }
                   5511: 
1.679     raeburn  5512: # ------------------------------------------------------- Course Group routines
                   5513: 
                   5514: sub get_coursegroups {
1.809     raeburn  5515:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5516:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5517: }
                   5518: 
1.679     raeburn  5519: sub modify_coursegroup {
                   5520:     my ($cdom,$cnum,$groupsettings) = @_;
                   5521:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5522: }
                   5523: 
1.809     raeburn  5524: sub toggle_coursegroup_status {
                   5525:     my ($cdom,$cnum,$group,$action) = @_;
                   5526:     my ($from_namespace,$to_namespace);
                   5527:     if ($action eq 'delete') {
                   5528:         $from_namespace = 'coursegroups';
                   5529:         $to_namespace = 'deleted_groups';
                   5530:     } else {
                   5531:         $from_namespace = 'deleted_groups';
                   5532:         $to_namespace = 'coursegroups';
                   5533:     }
                   5534:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5535:     if (my $tmp = &error(%curr_group)) {
                   5536:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5537:         return ('read error',$tmp);
                   5538:     } else {
                   5539:         my %savedsettings = %curr_group; 
1.809     raeburn  5540:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5541:         my $deloutcome;
                   5542:         if ($result eq 'ok') {
1.809     raeburn  5543:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5544:         } else {
                   5545:             return ('write error',$result);
                   5546:         }
                   5547:         if ($deloutcome eq 'ok') {
                   5548:             return 'ok';
                   5549:         } else {
                   5550:             return ('delete error',$deloutcome);
                   5551:         }
                   5552:     }
                   5553: }
                   5554: 
1.679     raeburn  5555: sub modify_group_roles {
1.957     raeburn  5556:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  5557:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5558:     my $role = 'gr/'.&escape($userprivs);
                   5559:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  5560:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  5561:     if ($result eq 'ok') {
                   5562:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5563:     }
1.679     raeburn  5564:     return $result;
                   5565: }
                   5566: 
                   5567: sub modify_coursegroup_membership {
                   5568:     my ($cdom,$cnum,$membership) = @_;
                   5569:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5570:     return $result;
                   5571: }
                   5572: 
1.682     raeburn  5573: sub get_active_groups {
                   5574:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5575:     my $now = time;
                   5576:     my %groups = ();
                   5577:     foreach my $key (keys(%env)) {
1.811     albertel 5578:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5579:             my ($start,$end) = split(/\./,$env{$key});
                   5580:             if (($end!=0) && ($end<$now)) { next; }
                   5581:             if (($start!=0) && ($start>$now)) { next; }
                   5582:             if ($1 eq $cdom && $2 eq $cnum) {
                   5583:                 $groups{$3} = $env{$key} ;
                   5584:             }
                   5585:         }
                   5586:     }
                   5587:     return %groups;
                   5588: }
                   5589: 
1.683     raeburn  5590: sub get_group_membership {
                   5591:     my ($cdom,$cnum,$group) = @_;
                   5592:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5593: }
                   5594: 
                   5595: sub get_users_groups {
                   5596:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5597:     my @usersgroups;
1.683     raeburn  5598:     my $cachetime=1800;
                   5599: 
                   5600:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5601:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5602:     if (defined($cached)) {
1.734     albertel 5603:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5604:     } else {  
                   5605:         $grouplist = '';
1.816     raeburn  5606:         my $courseurl = &courseid_to_courseurl($courseid);
                   5607:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5608:         my $access_end = $env{'course.'.$courseid.
                   5609:                               '.default_enrollment_end_date'};
                   5610:         my $now = time;
                   5611:         foreach my $key (keys(%roleshash)) {
                   5612:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5613:                 my $group = $1;
                   5614:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5615:                     my $start = $2;
                   5616:                     my $end = $1;
                   5617:                     if ($start == -1) { next; } # deleted from group
                   5618:                     if (($start!=0) && ($start>$now)) { next; }
                   5619:                     if (($end!=0) && ($end<$now)) {
                   5620:                         if ($access_end && $access_end < $now) {
                   5621:                             if ($access_end - $end < 86400) {
                   5622:                                 push(@usersgroups,$group);
1.733     raeburn  5623:                             }
                   5624:                         }
1.817     raeburn  5625:                         next;
1.733     raeburn  5626:                     }
1.817     raeburn  5627:                     push(@usersgroups,$group);
1.683     raeburn  5628:                 }
                   5629:             }
                   5630:         }
1.817     raeburn  5631:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5632:         $grouplist = join(':',@usersgroups);
                   5633:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5634:     }
1.733     raeburn  5635:     return @usersgroups;
1.683     raeburn  5636: }
                   5637: 
                   5638: sub devalidate_getgroups_cache {
                   5639:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5640:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5641: 
1.683     raeburn  5642:     my $hashid="$udom:$uname:$courseid";
                   5643:     &devalidate_cache_new('getgroups',$hashid);
                   5644: }
                   5645: 
1.12      www      5646: # ------------------------------------------------------------------ Plain Text
                   5647: 
                   5648: sub plaintext {
1.742     raeburn  5649:     my ($short,$type,$cid) = @_;
1.758     albertel 5650:     if ($short =~ /^cr/) {
                   5651: 	return (split('/',$short))[-1];
                   5652:     }
1.742     raeburn  5653:     if (!defined($cid)) {
                   5654:         $cid = $env{'request.course.id'};
                   5655:     }
                   5656:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5657:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5658:                                           '.plaintext'});
                   5659:     }
                   5660:     my %rolenames = (
                   5661:                       Course => 'std',
                   5662:                       Group => 'alt1',
                   5663:                     );
                   5664:     if (defined($type) && 
                   5665:          defined($rolenames{$type}) && 
                   5666:          defined($prp{$short}{$rolenames{$type}})) {
                   5667:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5668:     } else {
                   5669:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5670:     }
1.12      www      5671: }
                   5672: 
                   5673: # ----------------------------------------------------------------- Assign Role
                   5674: 
                   5675: sub assignrole {
1.957     raeburn  5676:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   5677:         $context)=@_;
1.21      www      5678:     my $mrole;
                   5679:     if ($role =~ /^cr\//) {
1.393     www      5680:         my $cwosec=$url;
1.811     albertel 5681:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5682: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5683:            &logthis('Refused custom assignrole: '.
                   5684:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5685: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5686:            return 'refused'; 
                   5687:         }
1.21      www      5688:         $mrole='cr';
1.678     raeburn  5689:     } elsif ($role =~ /^gr\//) {
                   5690:         my $cwogrp=$url;
1.811     albertel 5691:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5692:         unless (&allowed('mdg',$cwogrp)) {
                   5693:             &logthis('Refused group assignrole: '.
                   5694:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5695:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5696:             return 'refused';
                   5697:         }
                   5698:         $mrole='gr';
1.21      www      5699:     } else {
1.82      www      5700:         my $cwosec=$url;
1.811     albertel 5701:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5702:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5703:             my $refused;
                   5704:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5705:                 if (!(&allowed('c'.$role,$url))) {
                   5706:                     $refused = 1;
                   5707:                 }
                   5708:             } else {
                   5709:                 $refused = 1;
                   5710:             }
1.947     raeburn  5711:             if ($refused) {
                   5712:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5713:                     $refused = '';
                   5714:                 } else {
                   5715:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   5716:                              ' '.$role.' '.$end.' '.$start.' by '.
                   5717: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   5718:                     return 'refused';
                   5719:                 }
1.932     raeburn  5720:             }
1.104     www      5721:         }
1.21      www      5722:         $mrole=$role;
                   5723:     }
1.620     albertel 5724:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5725:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5726:     if ($end) { $command.='_'.$end; }
1.21      www      5727:     if ($start) {
                   5728: 	if ($end) { 
1.81      www      5729:            $command.='_'.$start; 
1.21      www      5730:         } else {
1.81      www      5731:            $command.='_0_'.$start;
1.21      www      5732:         }
                   5733:     }
1.739     raeburn  5734:     my $origstart = $start;
                   5735:     my $origend = $end;
1.957     raeburn  5736:     my $delflag;
1.357     www      5737: # actually delete
                   5738:     if ($deleteflag) {
1.373     www      5739: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5740: # modify command to delete the role
1.620     albertel 5741:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5742:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5743: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5744: # set start and finish to negative values for userrolelog
                   5745:            $start=-1;
                   5746:            $end=-1;
1.957     raeburn  5747:            $delflag = 1;
1.357     www      5748:         }
                   5749:     }
                   5750: # send command
1.349     www      5751:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5752: # log new user role if status is ok
1.349     www      5753:     if ($answer eq 'ok') {
1.663     raeburn  5754: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5755: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  5756:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  5757:         unless ($role =~ /^gr/) {
                   5758:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  5759:                                              $origstart,$selfenroll,$context);
1.739     raeburn  5760:         }
1.349     www      5761:     }
                   5762:     return $answer;
1.169     harris41 5763: }
                   5764: 
                   5765: # -------------------------------------------------- Modify user authentication
1.197     www      5766: # Overrides without validation
                   5767: 
1.169     harris41 5768: sub modifyuserauth {
                   5769:     my ($udom,$uname,$umode,$upass)=@_;
                   5770:     my $uhome=&homeserver($uname,$udom);
1.197     www      5771:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5772:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5773:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5774:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5775:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5776: 		     &escape($upass),$uhome);
1.620     albertel 5777:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5778:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5779:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5780:     &log($udom,,$uname,$uhome,
1.620     albertel 5781:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5782:                                      $env{'user.name'}.', '.$umode.
1.197     www      5783:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5784:     unless ($reply eq 'ok') {
1.197     www      5785:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5786: 	return 'error: '.$reply;
                   5787:     }   
1.170     harris41 5788:     return 'ok';
1.80      www      5789: }
                   5790: 
1.81      www      5791: # --------------------------------------------------------------- Modify a user
1.80      www      5792: 
1.81      www      5793: sub modifyuser {
1.206     matthew  5794:     my ($udom,    $uname, $uid,
                   5795:         $umode,   $upass, $first,
                   5796:         $middle,  $last,  $gene,
1.963     raeburn  5797:         $forceid, $desiredhome, $email, $inststatus)=@_;
1.807     albertel 5798:     $udom= &LONCAPA::clean_domain($udom);
                   5799:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5800:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5801:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5802: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5803:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5804:                                      ' desiredhome not specified'). 
1.620     albertel 5805:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5806:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5807:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5808: # ----------------------------------------------------------------- Create User
1.406     albertel 5809:     if (($uhome eq 'no_host') && 
                   5810: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5811:         my $unhome='';
1.844     albertel 5812:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5813:             $unhome = $desiredhome;
1.620     albertel 5814: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5815: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5816:         } else { # load balancing routine for determining $unhome
1.81      www      5817:             my $loadm=10000000;
1.841     albertel 5818: 	    my %servers = &get_servers($udom,'library');
                   5819: 	    foreach my $tryserver (keys(%servers)) {
                   5820: 		my $answer=reply('load',$tryserver);
                   5821: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5822: 		    $loadm=$answer;
                   5823: 		    $unhome=$tryserver;
                   5824: 		}
1.80      www      5825: 	    }
                   5826:         }
                   5827:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5828: 	    return 'error: unable to find a home server for '.$uname.
                   5829:                    ' in domain '.$udom;
1.80      www      5830:         }
                   5831:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5832:                          &escape($upass),$unhome);
                   5833: 	unless ($reply eq 'ok') {
                   5834:             return 'error: '.$reply;
                   5835:         }   
1.230     stredwic 5836:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5837:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5838: 	    return 'error: unable verify users home machine.';
1.80      www      5839:         }
1.209     matthew  5840:     }   # End of creation of new user
1.80      www      5841: # ---------------------------------------------------------------------- Add ID
                   5842:     if ($uid) {
                   5843:        $uid=~tr/A-Z/a-z/;
                   5844:        my %uidhash=&idrget($udom,$uname);
1.196     www      5845:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5846:          && (!$forceid)) {
1.80      www      5847: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5848: 	      return 'error: user id "'.$uid.'" does not match '.
                   5849:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5850:           }
                   5851:        } else {
                   5852: 	  &idput($udom,($uname => $uid));
                   5853:        }
                   5854:     }
                   5855: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5856:     my @tmp=&get('environment',
1.899     raeburn  5857: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  5858:                     'permanentemail','inststatus'],
1.134     albertel 5859: 		   $udom,$uname);
1.313     matthew  5860:     my %names;
                   5861:     if ($tmp[0] =~ m/^error:.*/) { 
                   5862:         %names=(); 
                   5863:     } else {
                   5864:         %names = @tmp;
                   5865:     }
1.388     www      5866: #
                   5867: # Make sure to not trash student environment if instructor does not bother
                   5868: # to supply name and email information
                   5869: #
                   5870:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5871:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5872:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5873:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5874:     if ($email) {
                   5875:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  5876:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      5877:     }
1.899     raeburn  5878:     if ($uid) { $names{'id'}  = $uid; }
1.963     raeburn  5879:     if (defined($inststatus)) { $names{'inststatus'} = $inststatus; } 
1.134     albertel 5880:     my $reply = &put('environment', \%names, $udom,$uname);
                   5881:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5882:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5883:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963     raeburn  5884:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
                   5885:                  $umode.', '.$first.', '.$middle.', '.
                   5886: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
                   5887:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   5888:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   5889:     } else {
                   5890:         $logmsg .= ' during self creation';
                   5891:     }
                   5892:     &logthis($logmsg);
1.134     albertel 5893:     return 'ok';
1.80      www      5894: }
                   5895: 
1.81      www      5896: # -------------------------------------------------------------- Modify student
1.80      www      5897: 
1.81      www      5898: sub modifystudent {
                   5899:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  5900:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
                   5901:         $selfenroll,$context)=@_;
1.455     albertel 5902:     if (!$cid) {
1.620     albertel 5903: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5904: 	    return 'not_in_class';
                   5905: 	}
1.80      www      5906:     }
                   5907: # --------------------------------------------------------------- Make the user
1.81      www      5908:     my $reply=&modifyuser
1.209     matthew  5909: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5910:          $desiredhome,$email);
1.80      www      5911:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5912:     # This will cause &modify_student_enrollment to get the uid from the
                   5913:     # students environment
                   5914:     $uid = undef if (!$forceid);
1.455     albertel 5915:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  5916: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  5917:     return $reply;
                   5918: }
                   5919: 
                   5920: sub modify_student_enrollment {
1.957     raeburn  5921:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 5922:     my ($cdom,$cnum,$chome);
                   5923:     if (!$cid) {
1.620     albertel 5924: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5925: 	    return 'not_in_class';
                   5926: 	}
1.620     albertel 5927: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5928: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5929:     } else {
                   5930: 	($cdom,$cnum)=split(/_/,$cid);
                   5931:     }
1.620     albertel 5932:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5933:     if (!$chome) {
1.457     raeburn  5934: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5935:     }
1.455     albertel 5936:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5937:     # Make sure the user exists
1.81      www      5938:     my $uhome=&homeserver($uname,$udom);
                   5939:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5940: 	return 'error: no such user';
                   5941:     }
1.297     matthew  5942:     # Get student data if we were not given enough information
                   5943:     if (!defined($first)  || $first  eq '' || 
                   5944:         !defined($last)   || $last   eq '' || 
                   5945:         !defined($uid)    || $uid    eq '' || 
                   5946:         !defined($middle) || $middle eq '' || 
                   5947:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5948:         # They did not supply us with enough data to enroll the student, so
                   5949:         # we need to pick up more information.
1.297     matthew  5950:         my %tmp = &get('environment',
1.294     matthew  5951:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5952:                        ,$udom,$uname);
                   5953: 
1.800     albertel 5954:         #foreach my $key (keys(%tmp)) {
                   5955:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5956:         #}
1.294     matthew  5957:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5958:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5959:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5960:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5961:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5962:     }
1.556     albertel 5963:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5964:     my $reply=cput('classlist',
                   5965: 		   {"$uname:$udom" => 
1.515     raeburn  5966: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5967: 		   $cdom,$cnum);
1.81      www      5968:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5969: 	return 'error: '.$reply;
1.652     albertel 5970:     } else {
                   5971: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5972:     }
1.297     matthew  5973:     # Add student role to user
1.83      www      5974:     my $uurl='/'.$cid;
1.81      www      5975:     $uurl=~s/\_/\//g;
                   5976:     if ($usec) {
                   5977: 	$uurl.='/'.$usec;
                   5978:     }
1.957     raeburn  5979:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      5980: }
                   5981: 
1.556     albertel 5982: sub format_name {
                   5983:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5984:     my $name;
                   5985:     if ($first ne 'lastname') {
                   5986: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5987:     } else {
                   5988: 	if ($lastname=~/\S/) {
                   5989: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5990: 	    $name=~s/\s+,/,/;
                   5991: 	} else {
                   5992: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5993: 	}
                   5994:     }
                   5995:     $name=~s/^\s+//;
                   5996:     $name=~s/\s+$//;
                   5997:     $name=~s/\s+/ /g;
                   5998:     return $name;
                   5999: }
                   6000: 
1.84      www      6001: # ------------------------------------------------- Write to course preferences
                   6002: 
                   6003: sub writecoursepref {
                   6004:     my ($courseid,%prefs)=@_;
                   6005:     $courseid=~s/^\///;
                   6006:     $courseid=~s/\_/\//g;
                   6007:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   6008:     my $chome=homeserver($cnum,$cdomain);
                   6009:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   6010: 	return 'error: no such course';
                   6011:     }
                   6012:     my $cstring='';
1.800     albertel 6013:     foreach my $pref (keys(%prefs)) {
                   6014: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 6015:     }
1.84      www      6016:     $cstring=~s/\&$//;
                   6017:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   6018: }
                   6019: 
                   6020: # ---------------------------------------------------------- Make/modify course
                   6021: 
                   6022: sub createcourse {
1.741     raeburn  6023:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   6024:         $course_owner,$crstype)=@_;
1.84      www      6025:     $url=&declutter($url);
                   6026:     my $cid='';
1.264     matthew  6027:     unless (&allowed('ccc',$udom)) {
1.84      www      6028:         return 'refused';
                   6029:     }
                   6030: # ------------------------------------------------------------------- Create ID
1.674     www      6031:    my $uname=int(1+rand(9)).
                   6032:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   6033:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      6034:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   6035: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 6036:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      6037:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6038:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   6039:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 6040:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      6041:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6042:            return 'error: unable to generate unique course-ID';
                   6043:        } 
                   6044:    }
1.264     matthew  6045: # ------------------------------------------------ Check supplied server name
1.620     albertel 6046:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 6047:     if (! &is_library($course_server)) {
1.264     matthew  6048:         return 'error:bad server name '.$course_server;
                   6049:     }
1.84      www      6050: # ------------------------------------------------------------- Make the course
                   6051:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  6052:                       $course_server);
1.84      www      6053:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 6054:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      6055:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6056: 	return 'error: no such course';
                   6057:     }
1.271     www      6058: # ----------------------------------------------------------------- Course made
1.516     raeburn  6059: # log existence
1.918     raeburn  6060:     my $newcourse = {
                   6061:                     $udom.'_'.$uname => {
1.921     raeburn  6062:                                      description => $description,
                   6063:                                      inst_code   => $inst_code,
                   6064:                                      owner       => $course_owner,
                   6065:                                      type        => $crstype,
1.918     raeburn  6066:                                                 },
                   6067:                     };
1.921     raeburn  6068:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      6069: # set toplevel url
1.271     www      6070:     my $topurl=$url;
                   6071:     unless ($nonstandard) {
                   6072: # ------------------------------------------ For standard courses, make top url
                   6073:         my $mapurl=&clutter($url);
1.278     www      6074:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 6075:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      6076: <map>
                   6077: <resource id="1" type="start"></resource>
                   6078: <resource id="2" src="$mapurl"></resource>
                   6079: <resource id="3" type="finish"></resource>
                   6080: <link index="1" from="1" to="2"></link>
                   6081: <link index="2" from="2" to="3"></link>
                   6082: </map>
                   6083: ENDINITMAP
                   6084:         $topurl=&declutter(
1.638     albertel 6085:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      6086:                           );
                   6087:     }
                   6088: # ----------------------------------------------------------- Write preferences
1.84      www      6089:     &writecoursepref($udom.'_'.$uname,
                   6090:                      ('description' => $description,
1.271     www      6091:                       'url'         => $topurl));
1.84      www      6092:     return '/'.$udom.'/'.$uname;
                   6093: }
                   6094: 
1.813     albertel 6095: sub is_course {
                   6096:     my ($cdom,$cnum) = @_;
                   6097:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  6098: 				undef,'.');
1.813     albertel 6099:     if (exists($courses{$cdom.'_'.$cnum})) {
                   6100:         return 1;
                   6101:     }
                   6102:     return 0;
                   6103: }
                   6104: 
1.21      www      6105: # ---------------------------------------------------------- Assign Custom Role
                   6106: 
                   6107: sub assigncustomrole {
1.957     raeburn  6108:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6109:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  6110:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      6111: }
                   6112: 
                   6113: # ----------------------------------------------------------------- Revoke Role
                   6114: 
                   6115: sub revokerole {
1.957     raeburn  6116:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6117:     my $now=time;
1.965     raeburn  6118:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      6119: }
                   6120: 
                   6121: # ---------------------------------------------------------- Revoke Custom Role
                   6122: 
                   6123: sub revokecustomrole {
1.957     raeburn  6124:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6125:     my $now=time;
1.357     www      6126:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  6127:            $deleteflag,$selfenroll,$context);
1.17      www      6128: }
                   6129: 
1.533     banghart 6130: # ------------------------------------------------------------ Disk usage
1.535     albertel 6131: sub diskusage {
1.955     raeburn  6132:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   6133:     $directorypath =~ s/\/$//;
                   6134:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   6135:                        .&escape($getpropath).':'.&escape($uname).':'
                   6136:                        .&escape($udom),homeserver($uname,$udom));
                   6137:     if ($listing eq 'unknown_cmd') {
                   6138:         if ($getpropath) {
                   6139:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   6140:         }
                   6141:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   6142:     }
1.514     albertel 6143:     return $listing;
1.512     banghart 6144: }
                   6145: 
1.566     banghart 6146: sub is_locked {
                   6147:     my ($file_name, $domain, $user) = @_;
                   6148:     my @check;
                   6149:     my $is_locked;
                   6150:     push @check, $file_name;
1.613     albertel 6151:     my %locked = &get('file_permissions',\@check,
1.620     albertel 6152: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 6153:     my ($tmp)=keys(%locked);
                   6154:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  6155:     
1.566     banghart 6156:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  6157:         $is_locked = 'false';
                   6158:         foreach my $entry (@{$locked{$file_name}}) {
                   6159:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  6160:                $is_locked = 'true';
                   6161:                last;
1.745     raeburn  6162:            }
                   6163:        }
1.566     banghart 6164:     } else {
                   6165:         $is_locked = 'false';
                   6166:     }
                   6167: }
                   6168: 
1.759     albertel 6169: sub declutter_portfile {
                   6170:     my ($file) = @_;
1.833     albertel 6171:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 6172:     return $file;
                   6173: }
                   6174: 
1.559     banghart 6175: # ------------------------------------------------------------- Mark as Read Only
                   6176: 
                   6177: sub mark_as_readonly {
                   6178:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 6179:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6180:     my ($tmp)=keys(%current_permissions);
                   6181:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 6182:     foreach my $file (@{$files}) {
1.759     albertel 6183: 	$file = &declutter_portfile($file);
1.561     banghart 6184:         push(@{$current_permissions{$file}},$what);
1.559     banghart 6185:     }
1.613     albertel 6186:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6187:     return;
                   6188: }
                   6189: 
1.572     banghart 6190: # ------------------------------------------------------------Save Selected Files
                   6191: 
                   6192: sub save_selected_files {
                   6193:     my ($user, $path, @files) = @_;
                   6194:     my $filename = $user."savedfiles";
1.573     banghart 6195:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 6196:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 6197:     foreach my $file (@files) {
1.620     albertel 6198:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 6199:     }
                   6200:     foreach my $file (@other_files) {
1.574     banghart 6201:         print (OUT $file."\n");
1.572     banghart 6202:     }
1.574     banghart 6203:     close (OUT);
1.572     banghart 6204:     return 'ok';
                   6205: }
                   6206: 
1.574     banghart 6207: sub clear_selected_files {
                   6208:     my ($user) = @_;
                   6209:     my $filename = $user."savedfiles";
                   6210:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6211:     print (OUT undef);
                   6212:     close (OUT);
                   6213:     return ("ok");    
                   6214: }
                   6215: 
1.572     banghart 6216: sub files_in_path {
                   6217:     my ($user, $path) = @_;
                   6218:     my $filename = $user."savedfiles";
                   6219:     my %return_files;
1.574     banghart 6220:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 6221:     while (my $line_in = <IN>) {
1.574     banghart 6222:         chomp ($line_in);
                   6223:         my @paths_and_file = split (m!/!, $line_in);
                   6224:         my $file_part = pop (@paths_and_file);
                   6225:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 6226:         $path_part.='/';
                   6227:         my $path_and_file = $path_part.$file_part;
                   6228:         if ($path_part eq $path) {
                   6229:             $return_files{$file_part}= 'selected';
                   6230:         }
                   6231:     }
1.574     banghart 6232:     close (IN);
                   6233:     return (\%return_files);
1.572     banghart 6234: }
                   6235: 
                   6236: # called in portfolio select mode, to show files selected NOT in current directory
                   6237: sub files_not_in_path {
                   6238:     my ($user, $path) = @_;
                   6239:     my $filename = $user."savedfiles";
                   6240:     my @return_files;
                   6241:     my $path_part;
1.800     albertel 6242:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6243:     while (my $line = <IN>) {
1.572     banghart 6244:         #ok, I know it's clunky, but I want it to work
1.800     albertel 6245:         my @paths_and_file = split(m|/|, $line);
                   6246:         my $file_part = pop(@paths_and_file);
                   6247:         chomp($file_part);
                   6248:         my $path_part = join('/', @paths_and_file);
1.572     banghart 6249:         $path_part .= '/';
                   6250:         my $path_and_file = $path_part.$file_part;
                   6251:         if ($path_part ne $path) {
1.800     albertel 6252:             push(@return_files, ($path_and_file));
1.572     banghart 6253:         }
                   6254:     }
1.800     albertel 6255:     close(OUT);
1.574     banghart 6256:     return (@return_files);
1.572     banghart 6257: }
                   6258: 
1.745     raeburn  6259: #----------------------------------------------Get portfolio file permissions
1.629     banghart 6260: 
1.745     raeburn  6261: sub get_portfile_permissions {
                   6262:     my ($domain,$user) = @_;
1.613     albertel 6263:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6264:     my ($tmp)=keys(%current_permissions);
                   6265:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6266:     return \%current_permissions;
                   6267: }
                   6268: 
                   6269: #---------------------------------------------Get portfolio file access controls
                   6270: 
1.749     raeburn  6271: sub get_access_controls {
1.745     raeburn  6272:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 6273:     my %access;
                   6274:     my $real_file = $file;
                   6275:     $file =~ s/\.meta$//;
1.745     raeburn  6276:     if (defined($file)) {
1.749     raeburn  6277:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   6278:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 6279:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  6280:             }
                   6281:         }
1.745     raeburn  6282:     } else {
1.749     raeburn  6283:         foreach my $key (keys(%{$current_permissions})) {
                   6284:             if ($key =~ /\0accesscontrol$/) {
                   6285:                 if (defined($group)) {
                   6286:                     if ($key !~ m-^\Q$group\E/-) {
                   6287:                         next;
                   6288:                     }
                   6289:                 }
                   6290:                 my ($fullpath) = split(/\0/,$key);
                   6291:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   6292:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   6293:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   6294:                     }
                   6295:                 }
                   6296:             }
                   6297:         }
                   6298:     }
                   6299:     return %access;
                   6300: }
                   6301: 
                   6302: sub modify_access_controls {
                   6303:     my ($file_name,$changes,$domain,$user)=@_;
                   6304:     my ($outcome,$deloutcome);
                   6305:     my %store_permissions;
                   6306:     my %new_values;
                   6307:     my %new_control;
                   6308:     my %translation;
                   6309:     my @deletions = ();
                   6310:     my $now = time;
                   6311:     if (exists($$changes{'activate'})) {
                   6312:         if (ref($$changes{'activate'}) eq 'HASH') {
                   6313:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   6314:             my $numnew = scalar(@newitems);
                   6315:             for (my $i=0; $i<$numnew; $i++) {
                   6316:                 my $newkey = $newitems[$i];
                   6317:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  6318:                 if ($newkey =~ /^\d+:/) { 
                   6319:                     $newkey =~ s/^(\d+)/$newid/;
                   6320:                     $translation{$1} = $newid;
                   6321:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   6322:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   6323:                     $translation{$1} = $newid;
                   6324:                 }
1.749     raeburn  6325:                 $new_values{$file_name."\0".$newkey} = 
                   6326:                                           $$changes{'activate'}{$newitems[$i]};
                   6327:                 $new_control{$newkey} = $now;
                   6328:             }
                   6329:         }
                   6330:     }
                   6331:     my %todelete;
                   6332:     my %changed_items;
                   6333:     foreach my $action ('delete','update') {
                   6334:         if (exists($$changes{$action})) {
                   6335:             if (ref($$changes{$action}) eq 'HASH') {
                   6336:                 foreach my $key (keys(%{$$changes{$action}})) {
                   6337:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   6338:                     if ($action eq 'delete') { 
                   6339:                         $todelete{$itemnum} = 1;
                   6340:                     } else {
                   6341:                         $changed_items{$itemnum} = $key;
                   6342:                     }
                   6343:                 }
1.745     raeburn  6344:             }
                   6345:         }
1.749     raeburn  6346:     }
                   6347:     # get lock on access controls for file.
                   6348:     my $lockhash = {
                   6349:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   6350:                                                        ':'.$env{'user.domain'},
                   6351:                    }; 
                   6352:     my $tries = 0;
                   6353:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6354:    
                   6355:     while (($gotlock ne 'ok') && $tries <3) {
                   6356:         $tries ++;
                   6357:         sleep 1;
                   6358:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6359:     }
                   6360:     if ($gotlock eq 'ok') {
                   6361:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6362:         my ($tmp)=keys(%curr_permissions);
                   6363:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6364:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6365:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6366:             if (ref($curr_controls) eq 'HASH') {
                   6367:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6368:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6369:                     if (defined($todelete{$itemnum})) {
                   6370:                         push(@deletions,$file_name."\0".$control_item);
                   6371:                     } else {
                   6372:                         if (defined($changed_items{$itemnum})) {
                   6373:                             $new_control{$changed_items{$itemnum}} = $now;
                   6374:                             push(@deletions,$file_name."\0".$control_item);
                   6375:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6376:                         } else {
                   6377:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6378:                         }
                   6379:                     }
1.745     raeburn  6380:                 }
                   6381:             }
                   6382:         }
1.970     raeburn  6383:         my ($group);
                   6384:         if (&is_course($domain,$user)) {
                   6385:             ($group,my $file) = split(/\//,$file_name,2);
                   6386:         }
1.749     raeburn  6387:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6388:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6389:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6390:         #  remove lock
                   6391:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6392:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6393:         my $sqlresult =
1.970     raeburn  6394:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  6395:                                     $group);
1.749     raeburn  6396:     } else {
                   6397:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6398:     }
1.749     raeburn  6399:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6400: }
                   6401: 
1.827     raeburn  6402: sub make_public_indefinitely {
                   6403:     my ($requrl) = @_;
                   6404:     my $now = time;
                   6405:     my $action = 'activate';
                   6406:     my $aclnum = 0;
                   6407:     if (&is_portfolio_url($requrl)) {
                   6408:         my (undef,$udom,$unum,$file_name,$group) =
                   6409:             &parse_portfolio_url($requrl);
                   6410:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6411:         my %access_controls = &get_access_controls($current_perms,
                   6412:                                                    $group,$file_name);
                   6413:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6414:             my ($num,$scope,$end,$start) = 
                   6415:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6416:             if ($scope eq 'public') {
                   6417:                 if ($start <= $now && $end == 0) {
                   6418:                     $action = 'none';
                   6419:                 } else {
                   6420:                     $action = 'update';
                   6421:                     $aclnum = $num;
                   6422:                 }
                   6423:                 last;
                   6424:             }
                   6425:         }
                   6426:         if ($action eq 'none') {
                   6427:              return 'ok';
                   6428:         } else {
                   6429:             my %changes;
                   6430:             my $newend = 0;
                   6431:             my $newstart = $now;
                   6432:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6433:             $changes{$action}{$newkey} = {
                   6434:                 type => 'public',
                   6435:                 time => {
                   6436:                     start => $newstart,
                   6437:                     end   => $newend,
                   6438:                 },
                   6439:             };
                   6440:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6441:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6442:             return $outcome;
                   6443:         }
                   6444:     } else {
                   6445:         return 'invalid';
                   6446:     }
                   6447: }
                   6448: 
1.745     raeburn  6449: #------------------------------------------------------Get Marked as Read Only
                   6450: 
                   6451: sub get_marked_as_readonly {
                   6452:     my ($domain,$user,$what,$group) = @_;
                   6453:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6454:     my @readonly_files;
1.629     banghart 6455:     my $cmp1=$what;
                   6456:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6457:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6458:         if (defined($group)) {
                   6459:             if ($file_name !~ m-^\Q$group\E/-) {
                   6460:                 next;
                   6461:             }
                   6462:         }
1.561     banghart 6463:         if (ref($value) eq "ARRAY"){
                   6464:             foreach my $stored_what (@{$value}) {
1.629     banghart 6465:                 my $cmp2=$stored_what;
1.759     albertel 6466:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6467:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6468:                 }
1.629     banghart 6469:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6470:                     push(@readonly_files, $file_name);
1.745     raeburn  6471:                     last;
1.563     banghart 6472:                 } elsif (!defined($what)) {
                   6473:                     push(@readonly_files, $file_name);
1.745     raeburn  6474:                     last;
1.561     banghart 6475:                 }
                   6476:             }
1.745     raeburn  6477:         }
1.561     banghart 6478:     }
                   6479:     return @readonly_files;
                   6480: }
1.577     banghart 6481: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6482: 
1.577     banghart 6483: sub get_marked_as_readonly_hash {
1.745     raeburn  6484:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6485:     my %readonly_files;
1.745     raeburn  6486:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6487:         if (defined($group)) {
                   6488:             if ($file_name !~ m-^\Q$group\E/-) {
                   6489:                 next;
                   6490:             }
                   6491:         }
1.577     banghart 6492:         if (ref($value) eq "ARRAY"){
                   6493:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6494:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6495:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6496:                         if ($lock_descriptor eq 'graded') {
                   6497:                             $readonly_files{$file_name} = 'graded';
                   6498:                         } elsif ($lock_descriptor eq 'handback') {
                   6499:                             $readonly_files{$file_name} = 'handback';
                   6500:                         } else {
                   6501:                             if (!exists($readonly_files{$file_name})) {
                   6502:                                 $readonly_files{$file_name} = 'locked';
                   6503:                             }
                   6504:                         }
1.745     raeburn  6505:                     }
1.750     banghart 6506:                 } 
1.577     banghart 6507:             }
                   6508:         } 
                   6509:     }
                   6510:     return %readonly_files;
                   6511: }
1.559     banghart 6512: # ------------------------------------------------------------ Unmark as Read Only
                   6513: 
                   6514: sub unmark_as_readonly {
1.629     banghart 6515:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6516:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6517:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6518:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6519:     my $symb_crs = $what;
                   6520:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6521:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6522:     my ($tmp)=keys(%current_permissions);
                   6523:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6524:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6525:     foreach my $file (@readonly_files) {
1.759     albertel 6526: 	my $clean_file = &declutter_portfile($file);
                   6527: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6528: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6529:         my @new_locks;
                   6530:         my @del_keys;
                   6531:         if (ref($current_locks) eq "ARRAY"){
                   6532:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6533:                 my $compare=$locker;
1.749     raeburn  6534:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6535:                     $compare=join('',@{$locker});
1.746     raeburn  6536:                     if ($compare ne $symb_crs) {
                   6537:                         push(@new_locks, $locker);
                   6538:                     }
1.563     banghart 6539:                 }
                   6540:             }
1.650     albertel 6541:             if (scalar(@new_locks) > 0) {
1.563     banghart 6542:                 $current_permissions{$file} = \@new_locks;
                   6543:             } else {
                   6544:                 push(@del_keys, $file);
1.613     albertel 6545:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6546:                 delete($current_permissions{$file});
1.563     banghart 6547:             }
                   6548:         }
1.561     banghart 6549:     }
1.613     albertel 6550:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6551:     return;
                   6552: }
1.512     banghart 6553: 
1.17      www      6554: # ------------------------------------------------------------ Directory lister
                   6555: 
                   6556: sub dirlist {
1.955     raeburn  6557:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      6558:     $uri=~s/^\///;
                   6559:     $uri=~s/\/$//;
1.253     stredwic 6560:     my ($udom, $uname);
1.955     raeburn  6561:     if ($getuserdir) {
1.253     stredwic 6562:         $udom = $userdomain;
                   6563:         $uname = $username;
1.955     raeburn  6564:     } else {
                   6565:         (undef,$udom,$uname)=split(/\//,$uri);
                   6566:         if(defined($userdomain)) {
                   6567:             $udom = $userdomain;
                   6568:         }
                   6569:         if(defined($username)) {
                   6570:             $uname = $username;
                   6571:         }
1.253     stredwic 6572:     }
1.955     raeburn  6573:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 6574: 
1.955     raeburn  6575:     $dirRoot = $perlvar{'lonDocRoot'};
                   6576:     if (defined($getpropath)) {
                   6577:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 6578:         $dirRoot =~ s/\/$//;
1.955     raeburn  6579:     } elsif (defined($getuserdir)) {
                   6580:         my $subdir=$uname.'__';
                   6581:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6582:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   6583:                    ."/$udom/$subdir/$uname";
                   6584:     } elsif (defined($alternateRoot)) {
                   6585:         $dirRoot = $alternateRoot;
1.751     banghart 6586:     }
1.253     stredwic 6587: 
                   6588:     if($udom) {
                   6589:         if($uname) {
1.955     raeburn  6590:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  6591:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  6592:                               .':'.&escape($uname).':'.&escape($udom),
                   6593:                               &homeserver($uname,$udom));
                   6594:             if ($listing eq 'unknown_cmd') {
                   6595:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6596:                                   &homeserver($uname,$udom));
                   6597:             } else {
                   6598:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6599:             }
1.605     matthew  6600:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6601:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6602: 				  &homeserver($uname,$udom));
1.605     matthew  6603:                 @listing_results = split(/:/,$listing);
                   6604:             } else {
                   6605:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6606:             }
                   6607:             return @listing_results;
1.955     raeburn  6608:         } elsif(!$alternateRoot) {
1.800     albertel 6609:             my %allusers;
1.841     albertel 6610: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  6611:  	    foreach my $tryserver (keys(%servers)) {
                   6612:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   6613:                                   &escape($udom),$tryserver);
                   6614:                 if ($listing eq 'unknown_cmd') {
                   6615: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6616: 				      $udom, $tryserver);
                   6617:                 } else {
                   6618:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6619:                 }
1.841     albertel 6620: 		if ($listing eq 'unknown_cmd') {
                   6621: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6622: 				      $udom, $tryserver);
                   6623: 		    @listing_results = split(/:/,$listing);
                   6624: 		} else {
                   6625: 		    @listing_results =
                   6626: 			map { &unescape($_); } split(/:/,$listing);
                   6627: 		}
                   6628: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6629: 		    $listing_results[0] ne 'empty'       &&
                   6630: 		    $listing_results[0] ne 'con_lost') {
                   6631: 		    foreach my $line (@listing_results) {
                   6632: 			my ($entry) = split(/&/,$line,2);
                   6633: 			$allusers{$entry} = 1;
                   6634: 		    }
                   6635: 		}
1.253     stredwic 6636:             }
                   6637:             my $alluserstr='';
1.800     albertel 6638:             foreach my $user (sort(keys(%allusers))) {
                   6639:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6640:             }
                   6641:             $alluserstr=~s/:$//;
                   6642:             return split(/:/,$alluserstr);
                   6643:         } else {
1.800     albertel 6644:             return ('missing user name');
1.253     stredwic 6645:         }
1.955     raeburn  6646:     } elsif(!defined($getpropath)) {
1.841     albertel 6647:         my @all_domains = sort(&all_domains());
1.955     raeburn  6648:         foreach my $domain (@all_domains) {
                   6649:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6650:         }
                   6651:         return @all_domains;
                   6652:     } else {
1.800     albertel 6653:         return ('missing domain');
1.275     stredwic 6654:     }
                   6655: }
                   6656: 
                   6657: # --------------------------------------------- GetFileTimestamp
                   6658: # This function utilizes dirlist and returns the date stamp for
                   6659: # when it was last modified.  It will also return an error of -1
                   6660: # if an error occurs
                   6661: 
                   6662: sub GetFileTimestamp {
1.955     raeburn  6663:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 6664:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6665:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  6666:     my ($fileStat) = 
                   6667:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   6668:                                  undef,$getuserdir);
1.275     stredwic 6669:     my @stats = split('&', $fileStat);
                   6670:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6671:         # @stats contains first the filename, then the stat output
                   6672:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6673:     } else {
                   6674:         return -1;
1.253     stredwic 6675:     }
1.26      www      6676: }
                   6677: 
1.712     albertel 6678: sub stat_file {
                   6679:     my ($uri) = @_;
1.787     albertel 6680:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6681: 
1.955     raeburn  6682:     my ($udom,$uname,$file);
1.712     albertel 6683:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6684: 	($udom,$uname,$file) =
1.811     albertel 6685: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6686: 	$file = 'userfiles/'.$file;
                   6687:     }
                   6688:     if ($uri =~ m-^/res/-) {
                   6689: 	($udom,$uname) = 
1.807     albertel 6690: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6691: 	$file = $uri;
                   6692:     }
                   6693: 
                   6694:     if (!$udom || !$uname || !$file) {
                   6695: 	# unable to handle the uri
                   6696: 	return ();
                   6697:     }
1.956     raeburn  6698:     my $getpropath;
                   6699:     if ($file =~ /^userfiles\//) {
                   6700:         $getpropath = 1;
                   6701:     }
1.955     raeburn  6702:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 6703:     my @stats = split('&', $result);
1.721     banghart 6704:     
1.712     albertel 6705:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6706: 	shift(@stats); #filename is first
                   6707: 	return @stats;
                   6708:     }
                   6709:     return ();
                   6710: }
                   6711: 
1.26      www      6712: # -------------------------------------------------------- Value of a Condition
                   6713: 
1.713     albertel 6714: # gets the value of a specific preevaluated condition
                   6715: #    stored in the string  $env{user.state.<cid>}
                   6716: # or looks up a condition reference in the bighash and if if hasn't
                   6717: # already been evaluated recurses into docondval to get the value of
                   6718: # the condition, then memoizing it to 
                   6719: #   $env{user.state.<cid>.<condition>}
1.40      www      6720: sub directcondval {
                   6721:     my $number=shift;
1.620     albertel 6722:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6723: 	&Apache::lonuserstate::evalstate();
                   6724:     }
1.713     albertel 6725:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6726: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6727:     } elsif ($number =~ /^_/) {
                   6728: 	my $sub_condition;
                   6729: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6730: 		&GDBM_READER(),0640)) {
                   6731: 	    $sub_condition=$bighash{'conditions'.$number};
                   6732: 	    untie(%bighash);
                   6733: 	}
                   6734: 	my $value = &docondval($sub_condition);
1.949     raeburn  6735: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 6736: 	return $value;
                   6737:     }
1.620     albertel 6738:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6739:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6740:     } else {
                   6741:        return 2;
                   6742:     }
                   6743: }
                   6744: 
1.713     albertel 6745: # get the collection of conditions for this resource
1.26      www      6746: sub condval {
                   6747:     my $condidx=shift;
1.54      www      6748:     my $allpathcond='';
1.713     albertel 6749:     foreach my $cond (split(/\|/,$condidx)) {
                   6750: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6751: 	    $allpathcond.=
                   6752: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6753: 	}
1.191     harris41 6754:     }
1.54      www      6755:     $allpathcond=~s/\|$//;
1.713     albertel 6756:     return &docondval($allpathcond);
                   6757: }
                   6758: 
                   6759: #evaluates an expression of conditions
                   6760: sub docondval {
                   6761:     my ($allpathcond) = @_;
                   6762:     my $result=0;
                   6763:     if ($env{'request.course.id'}
                   6764: 	&& defined($allpathcond)) {
                   6765: 	my $operand='|';
                   6766: 	my @stack;
                   6767: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6768: 	    if ($chunk eq '(') {
                   6769: 		push @stack,($operand,$result);
                   6770: 	    } elsif ($chunk eq ')') {
                   6771: 		my $before=pop @stack;
                   6772: 		if (pop @stack eq '&') {
                   6773: 		    $result=$result>$before?$before:$result;
                   6774: 		} else {
                   6775: 		    $result=$result>$before?$result:$before;
                   6776: 		}
                   6777: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6778: 		$operand=$chunk;
                   6779: 	    } else {
                   6780: 		my $new=directcondval($chunk);
                   6781: 		if ($operand eq '&') {
                   6782: 		    $result=$result>$new?$new:$result;
                   6783: 		} else {
                   6784: 		    $result=$result>$new?$result:$new;
                   6785: 		}
                   6786: 	    }
                   6787: 	}
1.26      www      6788:     }
                   6789:     return $result;
1.421     albertel 6790: }
                   6791: 
                   6792: # ---------------------------------------------------- Devalidate courseresdata
                   6793: 
                   6794: sub devalidatecourseresdata {
                   6795:     my ($coursenum,$coursedomain)=@_;
                   6796:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6797:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6798: }
                   6799: 
1.763     www      6800: 
1.200     www      6801: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6802: #
                   6803: #  Parameters:
                   6804: #      $coursenum    - Number of the course.
                   6805: #      $coursedomain - Domain at which the course was created.
                   6806: #  Returns:
                   6807: #     A hash of the course parameters along (I think) with timestamps
                   6808: #     and version info.
1.877     foxr     6809: 
1.624     albertel 6810: sub get_courseresdata {
                   6811:     my ($coursenum,$coursedomain)=@_;
1.200     www      6812:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6813:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6814:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6815:     my %dumpreply;
1.417     albertel 6816:     unless (defined($cached)) {
1.624     albertel 6817: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6818: 	$result=\%dumpreply;
1.251     albertel 6819: 	my ($tmp) = keys(%dumpreply);
                   6820: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6821: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6822: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6823: 	    return $tmp;
1.416     albertel 6824: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6825: 	    $result=undef;
1.599     albertel 6826: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6827: 	}
                   6828:     }
1.624     albertel 6829:     return $result;
                   6830: }
                   6831: 
1.633     albertel 6832: sub devalidateuserresdata {
                   6833:     my ($uname,$udom)=@_;
                   6834:     my $hashid="$udom:$uname";
                   6835:     &devalidate_cache_new('userres',$hashid);
                   6836: }
                   6837: 
1.624     albertel 6838: sub get_userresdata {
                   6839:     my ($uname,$udom)=@_;
                   6840:     #most student don\'t have any data set, check if there is some data
                   6841:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6842: 
                   6843:     my $hashid="$udom:$uname";
                   6844:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6845:     if (!defined($cached)) {
                   6846: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6847: 	$result=\%resourcedata;
                   6848: 	&do_cache_new('userres',$hashid,$result,600);
                   6849:     }
                   6850:     my ($tmp)=keys(%$result);
                   6851:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6852: 	return $result;
                   6853:     }
                   6854:     #error 2 occurs when the .db doesn't exist
                   6855:     if ($tmp!~/error: 2 /) {
1.672     albertel 6856: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6857: 		 " Trying to get resource data for ".
                   6858: 		 $uname." at ".$udom.": ".
                   6859: 		 $tmp."</font>");
                   6860:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6861: 	#&EXT_cache_set($udom,$uname);
                   6862: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6863: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6864:     }
                   6865:     return $tmp;
                   6866: }
1.879     foxr     6867: #----------------------------------------------- resdata - return resource data
                   6868: #  Purpose:
                   6869: #    Return resource data for either users or for a course.
                   6870: #  Parameters:
                   6871: #     $name      - Course/user name.
                   6872: #     $domain    - Name of the domain the user/course is registered on.
                   6873: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6874: #     @which     - Array of names of resources desired.
                   6875: #  Returns:
                   6876: #     The value of the first reasource in @which that is found in the
                   6877: #     resource hash.
                   6878: #  Exceptional Conditions:
                   6879: #     If the $type passed in is not valid (not the string 'course' or 
                   6880: #     'user', an undefined  reference is returned.
                   6881: #     If none of the resources are found, an undef is returned
1.624     albertel 6882: sub resdata {
                   6883:     my ($name,$domain,$type,@which)=@_;
                   6884:     my $result;
                   6885:     if ($type eq 'course') {
                   6886: 	$result=&get_courseresdata($name,$domain);
                   6887:     } elsif ($type eq 'user') {
                   6888: 	$result=&get_userresdata($name,$domain);
                   6889:     }
                   6890:     if (!ref($result)) { return $result; }    
1.251     albertel 6891:     foreach my $item (@which) {
1.927     albertel 6892: 	if (defined($result->{$item->[0]})) {
                   6893: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 6894: 	}
1.250     albertel 6895:     }
1.291     albertel 6896:     return undef;
1.200     www      6897: }
                   6898: 
1.379     matthew  6899: #
                   6900: # EXT resource caching routines
                   6901: #
                   6902: 
                   6903: sub clear_EXT_cache_status {
1.383     albertel 6904:     &delenv('cache.EXT.');
1.379     matthew  6905: }
                   6906: 
                   6907: sub EXT_cache_status {
                   6908:     my ($target_domain,$target_user) = @_;
1.383     albertel 6909:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6910:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6911:         # We know already the user has no data
                   6912:         return 1;
                   6913:     } else {
                   6914:         return 0;
                   6915:     }
                   6916: }
                   6917: 
                   6918: sub EXT_cache_set {
                   6919:     my ($target_domain,$target_user) = @_;
1.383     albertel 6920:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  6921:     #&appenv({$cachename => time});
1.379     matthew  6922: }
                   6923: 
1.28      www      6924: # --------------------------------------------------------- Value of a Variable
1.58      www      6925: sub EXT {
1.715     albertel 6926: 
1.395     albertel 6927:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6928:     unless ($varname) { return ''; }
1.218     albertel 6929:     #get real user name/domain, courseid and symb
                   6930:     my $courseid;
1.359     albertel 6931:     my $publicuser;
1.427     www      6932:     if ($symbparm) {
                   6933: 	$symbparm=&get_symb_from_alias($symbparm);
                   6934:     }
1.218     albertel 6935:     if (!($uname && $udom)) {
1.790     albertel 6936:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6937:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6938:     } else {
1.620     albertel 6939: 	$courseid=$env{'request.course.id'};
1.218     albertel 6940:     }
1.48      www      6941:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6942:     my $rest;
1.320     albertel 6943:     if (defined($therest[0])) {
1.48      www      6944:        $rest=join('.',@therest);
                   6945:     } else {
                   6946:        $rest='';
                   6947:     }
1.320     albertel 6948: 
1.57      www      6949:     my $qualifierrest=$qualifier;
                   6950:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6951:     my $spacequalifierrest=$space;
                   6952:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6953:     if ($realm eq 'user') {
1.48      www      6954: # --------------------------------------------------------------- user.resource
                   6955: 	if ($space eq 'resource') {
1.651     albertel 6956: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6957: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6958: 		 &&
1.744     albertel 6959: 		 ($symbparm eq &symbread()) ) {	
                   6960: 		# if we are in the middle of processing the resource the
                   6961: 		# get the value we are planning on committing
                   6962:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6963:                     return $Apache::lonhomework::results{$qualifierrest};
                   6964:                 } else {
                   6965:                     return $Apache::lonhomework::history{$qualifierrest};
                   6966:                 }
1.335     albertel 6967: 	    } else {
1.359     albertel 6968: 		my %restored;
1.620     albertel 6969: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6970: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6971: 		} else {
                   6972: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6973: 		}
1.335     albertel 6974: 		return $restored{$qualifierrest};
                   6975: 	    }
1.48      www      6976: # ----------------------------------------------------------------- user.access
                   6977:         } elsif ($space eq 'access') {
1.218     albertel 6978: 	    # FIXME - not supporting calls for a specific user
1.48      www      6979:             return &allowed($qualifier,$rest);
                   6980: # ------------------------------------------ user.preferences, user.environment
                   6981:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6982: 	    if (($uname eq $env{'user.name'}) &&
                   6983: 		($udom eq $env{'user.domain'})) {
                   6984: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6985: 	    } else {
1.359     albertel 6986: 		my %returnhash;
                   6987: 		if (!$publicuser) {
                   6988: 		    %returnhash=&userenvironment($udom,$uname,
                   6989: 						 $qualifierrest);
                   6990: 		}
1.218     albertel 6991: 		return $returnhash{$qualifierrest};
                   6992: 	    }
1.48      www      6993: # ----------------------------------------------------------------- user.course
                   6994:         } elsif ($space eq 'course') {
1.218     albertel 6995: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6996:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6997: # ------------------------------------------------------------------- user.role
                   6998:         } elsif ($space eq 'role') {
1.218     albertel 6999: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 7000:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      7001:             if ($qualifier eq 'value') {
                   7002: 		return $role;
                   7003:             } elsif ($qualifier eq 'extent') {
                   7004:                 return $where;
                   7005:             }
                   7006: # ----------------------------------------------------------------- user.domain
                   7007:         } elsif ($space eq 'domain') {
1.218     albertel 7008:             return $udom;
1.48      www      7009: # ------------------------------------------------------------------- user.name
                   7010:         } elsif ($space eq 'name') {
1.218     albertel 7011:             return $uname;
1.48      www      7012: # ---------------------------------------------------- Any other user namespace
1.29      www      7013:         } else {
1.359     albertel 7014: 	    my %reply;
                   7015: 	    if (!$publicuser) {
                   7016: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   7017: 	    }
                   7018: 	    return $reply{$qualifierrest};
1.48      www      7019:         }
1.236     www      7020:     } elsif ($realm eq 'query') {
                   7021: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 7022:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   7023: 						[$spacequalifierrest]);
1.620     albertel 7024: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      7025:    } elsif ($realm eq 'request') {
1.48      www      7026: # ------------------------------------------------------------- request.browser
                   7027:         if ($space eq 'browser') {
1.430     www      7028: 	    if ($qualifier eq 'textremote') {
1.676     albertel 7029: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      7030: 		    return 1;
                   7031: 		} else {
                   7032: 		    return 0;
                   7033: 		}
                   7034: 	    } else {
1.620     albertel 7035: 		return $env{'browser.'.$qualifier};
1.430     www      7036: 	    }
1.57      www      7037: # ------------------------------------------------------------ request.filename
                   7038:         } else {
1.620     albertel 7039:             return $env{'request.'.$spacequalifierrest};
1.29      www      7040:         }
1.28      www      7041:     } elsif ($realm eq 'course') {
1.48      www      7042: # ---------------------------------------------------------- course.description
1.620     albertel 7043:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      7044:     } elsif ($realm eq 'resource') {
1.165     www      7045: 
1.620     albertel 7046: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 7047: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   7048: 	}
1.693     albertel 7049: 
                   7050: 	if ($space eq 'title') {
                   7051: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   7052: 	    return &gettitle($symbparm);
                   7053: 	}
                   7054: 	
                   7055: 	if ($space eq 'map') {
                   7056: 	    my ($map) = &decode_symb($symbparm);
                   7057: 	    return &symbread($map);
                   7058: 	}
1.905     albertel 7059: 	if ($space eq 'filename') {
                   7060: 	    if ($symbparm) {
                   7061: 		return &clutter((&decode_symb($symbparm))[2]);
                   7062: 	    }
                   7063: 	    return &hreflocation('',$env{'request.filename'});
                   7064: 	}
1.693     albertel 7065: 
                   7066: 	my ($section, $group, @groups);
1.593     albertel 7067: 	my ($courselevelm,$courselevel);
1.539     albertel 7068: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7069: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      7070: 
1.218     albertel 7071: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      7072: 
1.60      www      7073: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 7074: 	    my $symbp=$symbparm;
1.735     albertel 7075: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 7076: 
                   7077: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   7078: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   7079: 
1.620     albertel 7080: 	    if (($env{'user.name'} eq $uname) &&
                   7081: 		($env{'user.domain'} eq $udom)) {
                   7082: 		$section=$env{'request.course.sec'};
1.733     raeburn  7083:                 @groups = split(/:/,$env{'request.course.groups'});  
                   7084:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 7085: 	    } else {
1.539     albertel 7086: 		if (! defined($usection)) {
1.551     albertel 7087: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 7088: 		} else {
                   7089: 		    $section = $usection;
                   7090: 		}
1.733     raeburn  7091:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 7092: 	    }
                   7093: 
                   7094: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   7095: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   7096: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   7097: 
1.593     albertel 7098: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 7099: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 7100: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      7101: 
1.60      www      7102: # ----------------------------------------------------------- first, check user
1.624     albertel 7103: 
                   7104: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 7105: 				       ([$courselevelr,'resource'],
                   7106: 					[$courselevelm,'map'     ],
                   7107: 					[$courselevel, 'course'  ]));
1.931     albertel 7108: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      7109: 
1.594     albertel 7110: # ------------------------------------------------ second, check some of course
1.684     raeburn  7111:             my $coursereply;
1.691     raeburn  7112:             if (@groups > 0) {
                   7113:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   7114:                                        $mapparm,$spacequalifierrest);
1.927     albertel 7115:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  7116:             }
1.96      www      7117: 
1.684     raeburn  7118: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 7119: 				  $env{'course.'.$courseid.'.domain'},
                   7120: 				  'course',
                   7121: 				  ([$seclevelr,   'resource'],
                   7122: 				   [$seclevelm,   'map'     ],
                   7123: 				   [$seclevel,    'course'  ],
                   7124: 				   [$courselevelr,'resource']));
                   7125: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      7126: 
1.60      www      7127: # ------------------------------------------------------ third, check map parms
1.218     albertel 7128: 	    my %parmhash=();
                   7129: 	    my $thisparm='';
                   7130: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 7131: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 7132: 		    &GDBM_READER(),0640)) {
1.218     albertel 7133: 		$thisparm=$parmhash{$symbparm};
                   7134: 		untie(%parmhash);
                   7135: 	    }
1.927     albertel 7136: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 7137: 	}
1.594     albertel 7138: # ------------------------------------------ fourth, look in resource metadata
1.71      www      7139: 
1.218     albertel 7140: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 7141: 	my $filename;
                   7142: 	if (!$symbparm) { $symbparm=&symbread(); }
                   7143: 	if ($symbparm) {
1.409     www      7144: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 7145: 	} else {
1.620     albertel 7146: 	    $filename=$env{'request.filename'};
1.282     albertel 7147: 	}
                   7148: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 7149: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 7150: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 7151: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      7152: 
1.927     albertel 7153: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 7154: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7155: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 7156: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   7157: 				     $env{'course.'.$courseid.'.domain'},
                   7158: 				     'course',
1.927     albertel 7159: 				     ([$courselevelm,'map'   ],
                   7160: 				      [$courselevel, 'course']));
                   7161: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 7162: 	}
1.145     www      7163: # ------------------------------------------------------------------ Cascade up
1.218     albertel 7164: 	unless ($space eq '0') {
1.336     albertel 7165: 	    my @parts=split(/_/,$space);
                   7166: 	    my $id=pop(@parts);
                   7167: 	    my $part=join('_',@parts);
                   7168: 	    if ($part eq '') { $part='0'; }
1.927     albertel 7169: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 7170: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  7171: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 7172: 	}
1.395     albertel 7173: 	if ($recurse) { return undef; }
                   7174: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 7175: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      7176: # ---------------------------------------------------- Any other user namespace
                   7177:     } elsif ($realm eq 'environment') {
                   7178: # ----------------------------------------------------------------- environment
1.620     albertel 7179: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   7180: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 7181: 	} else {
1.770     albertel 7182: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   7183: 		return '';
                   7184: 	    }
1.219     albertel 7185: 	    my %returnhash=&userenvironment($udom,$uname,
                   7186: 					    $spacequalifierrest);
                   7187: 	    return $returnhash{$spacequalifierrest};
                   7188: 	}
1.28      www      7189:     } elsif ($realm eq 'system') {
1.48      www      7190: # ----------------------------------------------------------------- system.time
                   7191: 	if ($space eq 'time') {
                   7192: 	    return time;
                   7193:         }
1.696     albertel 7194:     } elsif ($realm eq 'server') {
                   7195: # ----------------------------------------------------------------- system.time
                   7196: 	if ($space eq 'name') {
                   7197: 	    return $ENV{'SERVER_NAME'};
                   7198:         }
1.28      www      7199:     }
1.48      www      7200:     return '';
1.61      www      7201: }
                   7202: 
1.927     albertel 7203: sub get_reply {
                   7204:     my ($reply_value) = @_;
1.940     raeburn  7205:     if (ref($reply_value) eq 'ARRAY') {
                   7206:         if (wantarray) {
                   7207: 	    return @$reply_value;
                   7208:         }
                   7209:         return $reply_value->[0];
                   7210:     } else {
                   7211:         return $reply_value;
1.927     albertel 7212:     }
                   7213: }
                   7214: 
1.691     raeburn  7215: sub check_group_parms {
                   7216:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   7217:     my @groupitems = ();
                   7218:     my $resultitem;
1.927     albertel 7219:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  7220:     foreach my $group (@{$groups}) {
                   7221:         foreach my $level (@levels) {
1.927     albertel 7222:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   7223:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  7224:         }
                   7225:     }
                   7226:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   7227:                             $env{'course.'.$courseid.'.domain'},
                   7228:                                      'course',@groupitems);
                   7229:     return $coursereply;
                   7230: }
                   7231: 
                   7232: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  7233:     my ($courseid,@groups) = @_;
                   7234:     @groups = sort(@groups);
1.691     raeburn  7235:     return @groups;
                   7236: }
                   7237: 
1.395     albertel 7238: sub packages_tab_default {
                   7239:     my ($uri,$varname)=@_;
                   7240:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 7241: 
                   7242:     my (@extension,@specifics,$do_default);
                   7243:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 7244: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 7245: 	if ($pack_type eq 'default') {
                   7246: 	    $do_default=1;
                   7247: 	} elsif ($pack_type eq 'extension') {
                   7248: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 7249: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 7250: 	    # only look at packages defaults for packages that this id is
1.738     albertel 7251: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   7252: 	}
                   7253:     }
                   7254:     # first look for a package that matches the requested part id
                   7255:     foreach my $package (@specifics) {
                   7256: 	my (undef,$pack_type,$pack_part)=@{$package};
                   7257: 	next if ($pack_part ne $part);
                   7258: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7259: 	    return $packagetab{"$pack_type&$name&default"};
                   7260: 	}
                   7261:     }
                   7262:     # look for any possible matching non extension_ package
                   7263:     foreach my $package (@specifics) {
                   7264: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 7265: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7266: 	    return $packagetab{"$pack_type&$name&default"};
                   7267: 	}
1.585     albertel 7268: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 7269: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   7270: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 7271: 	}
                   7272:     }
1.738     albertel 7273:     # look for any posible extension_ match
                   7274:     foreach my $package (@extension) {
                   7275: 	my ($package,$pack_type)=@{$package};
                   7276: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7277: 	    return $packagetab{"$pack_type&$name&default"};
                   7278: 	}
                   7279: 	if (defined($packagetab{$package."&$name&default"})) {
                   7280: 	    return $packagetab{$package."&$name&default"};
                   7281: 	}
                   7282:     }
                   7283:     # look for a global default setting
                   7284:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   7285: 	return $packagetab{"default&$name&default"};
                   7286:     }
1.395     albertel 7287:     return undef;
                   7288: }
                   7289: 
1.334     albertel 7290: sub add_prefix_and_part {
                   7291:     my ($prefix,$part)=@_;
                   7292:     my $keyroot;
                   7293:     if (defined($prefix) && $prefix !~ /^__/) {
                   7294: 	# prefix that has a part already
                   7295: 	$keyroot=$prefix;
                   7296:     } elsif (defined($prefix)) {
                   7297: 	# prefix that is missing a part
                   7298: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   7299:     } else {
                   7300: 	# no prefix at all
                   7301: 	if (defined($part)) { $keyroot='_'.$part; }
                   7302:     }
                   7303:     return $keyroot;
                   7304: }
                   7305: 
1.71      www      7306: # ---------------------------------------------------------------- Get metadata
                   7307: 
1.599     albertel 7308: my %metaentry;
1.71      www      7309: sub metadata {
1.176     www      7310:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      7311:     $uri=&declutter($uri);
1.288     albertel 7312:     # if it is a non metadata possible uri return quickly
1.529     albertel 7313:     if (($uri eq '') || 
                   7314: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 7315: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 7316:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   7317: 	return undef;
                   7318:     }
                   7319:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   7320: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 7321: 	return undef;
1.288     albertel 7322:     }
1.73      www      7323:     my $filename=$uri;
                   7324:     $uri=~s/\.meta$//;
1.172     www      7325: #
                   7326: # Is the metadata already cached?
1.177     www      7327: # Look at timestamp of caching
1.172     www      7328: # Everything is cached by the main uri, libraries are never directly cached
                   7329: #
1.428     albertel 7330:     if (!defined($liburi)) {
1.599     albertel 7331: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 7332: 	if (defined($cached)) { return $result->{':'.$what}; }
                   7333:     }
                   7334:     {
1.172     www      7335: #
                   7336: # Is this a recursive call for a library?
                   7337: #
1.599     albertel 7338: #	if (! exists($metacache{$uri})) {
                   7339: #	    $metacache{$uri}={};
                   7340: #	}
1.924     albertel 7341: 	my $cachetime = 60*60;
1.171     www      7342:         if ($liburi) {
                   7343: 	    $liburi=&declutter($liburi);
                   7344:             $filename=$liburi;
1.401     bowersj2 7345:         } else {
1.599     albertel 7346: 	    &devalidate_cache_new('meta',$uri);
                   7347: 	    undef(%metaentry);
1.401     bowersj2 7348: 	}
1.140     www      7349:         my %metathesekeys=();
1.73      www      7350:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 7351: 	my $metastring;
1.924     albertel 7352: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 7353: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 7354: 	    $metastring = 
1.929     albertel 7355: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 7356: 					  ('grade_target' => 'meta'));
                   7357: 	    $cachetime = 1; # only want this cached in the child not long term
                   7358: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 7359: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 7360: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 7361: 	    $metastring=&getfile($file);
1.489     albertel 7362: 	}
1.208     albertel 7363:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      7364:         my $token;
1.140     www      7365:         undef %metathesekeys;
1.71      www      7366:         while ($token=$parser->get_token) {
1.339     albertel 7367: 	    if ($token->[0] eq 'S') {
                   7368: 		if (defined($token->[2]->{'package'})) {
1.172     www      7369: #
                   7370: # This is a package - get package info
                   7371: #
1.339     albertel 7372: 		    my $package=$token->[2]->{'package'};
                   7373: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7374: 		    if (defined($token->[2]->{'id'})) { 
                   7375: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7376: 		    }
1.599     albertel 7377: 		    if ($metaentry{':packages'}) {
                   7378: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7379: 		    } else {
1.599     albertel 7380: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7381: 		    }
1.736     albertel 7382: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7383: 			my $part=$keyroot;
                   7384: 			$part=~s/^\_//;
1.736     albertel 7385: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7386: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7387: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7388: 			    # ignore package.tab specified default values
                   7389:                             # here &package_tab_default() will fetch those
                   7390: 			    if ($subp eq 'default') { next; }
1.736     albertel 7391: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7392: 			    my $unikey;
                   7393: 			    if ($pack =~ /_0$/) {
                   7394: 				$unikey='parameter_0_'.$name;
                   7395: 				$part=0;
                   7396: 			    } else {
                   7397: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7398: 			    }
1.339     albertel 7399: 			    if ($subp eq 'display') {
                   7400: 				$value.=' [Part: '.$part.']';
                   7401: 			    }
1.599     albertel 7402: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7403: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7404: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7405: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7406: 			    }
1.599     albertel 7407: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7408: 				$metaentry{':'.$unikey}=
                   7409: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7410: 			    }
1.339     albertel 7411: 			}
                   7412: 		    }
                   7413: 		} else {
1.172     www      7414: #
                   7415: # This is not a package - some other kind of start tag
1.339     albertel 7416: #
                   7417: 		    my $entry=$token->[1];
                   7418: 		    my $unikey;
                   7419: 		    if ($entry eq 'import') {
                   7420: 			$unikey='';
                   7421: 		    } else {
                   7422: 			$unikey=$entry;
                   7423: 		    }
                   7424: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7425: 
                   7426: 		    if (defined($token->[2]->{'id'})) { 
                   7427: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7428: 		    }
1.175     www      7429: 
1.339     albertel 7430: 		    if ($entry eq 'import') {
1.175     www      7431: #
                   7432: # Importing a library here
1.339     albertel 7433: #
                   7434: 			if ($depthcount<20) {
                   7435: 			    my $location=$parser->get_text('/import');
                   7436: 			    my $dir=$filename;
                   7437: 			    $dir=~s|[^/]*$||;
                   7438: 			    $location=&filelocation($dir,$location);
1.736     albertel 7439: 			    my $metadata = 
                   7440: 				&metadata($uri,'keys', $location,$unikey,
                   7441: 					  $depthcount+1);
                   7442: 			    foreach my $meta (split(',',$metadata)) {
                   7443: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7444: 				$metathesekeys{$meta}=1;
1.339     albertel 7445: 			    }
                   7446: 			}
                   7447: 		    } else { 
                   7448: 			
                   7449: 			if (defined($token->[2]->{'name'})) { 
                   7450: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7451: 			}
                   7452: 			$metathesekeys{$unikey}=1;
1.736     albertel 7453: 			foreach my $param (@{$token->[3]}) {
                   7454: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7455: 				$token->[2]->{$param};
1.339     albertel 7456: 			}
                   7457: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7458: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7459: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7460: 		 # only ws inside the tag, and not in default, so use default
                   7461: 		 # as value
1.599     albertel 7462: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7463: 			} elsif ( $internaltext =~ /\S/ ) {
                   7464: 		  # something interesting inside the tag
                   7465: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7466: 			} else {
1.908     albertel 7467: 		  # no interesting values, don't set a default
1.339     albertel 7468: 			}
1.172     www      7469: # end of not-a-package not-a-library import
1.339     albertel 7470: 		    }
1.172     www      7471: # end of not-a-package start tag
1.339     albertel 7472: 		}
1.172     www      7473: # the next is the end of "start tag"
1.339     albertel 7474: 	    }
                   7475: 	}
1.483     albertel 7476: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7477: 	$extension = lc($extension);
                   7478: 	if ($extension eq 'htm') { $extension='html'; }
                   7479: 
1.737     albertel 7480: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7481: 	    #no specific packages #how's our extension
                   7482: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7483: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7484: 					 \%metathesekeys);
                   7485: 	}
1.883     albertel 7486: 
                   7487: 	if (!exists($metaentry{':packages'})
                   7488: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7489: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7490: 		#no specific packages well let's get default then
                   7491: 		if ($key!~/^default&/) { next; }
1.488     albertel 7492: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7493: 					     \%metathesekeys);
                   7494: 	    }
                   7495: 	}
1.338     www      7496: # are there custom rights to evaluate
1.599     albertel 7497: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7498: 
1.338     www      7499:     #
                   7500:     # Importing a rights file here
1.339     albertel 7501:     #
                   7502: 	    unless ($depthcount) {
1.599     albertel 7503: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7504: 		my $dir=$filename;
                   7505: 		$dir=~s|[^/]*$||;
                   7506: 		$location=&filelocation($dir,$location);
1.736     albertel 7507: 		my $rights_metadata =
                   7508: 		    &metadata($uri,'keys',$location,'_rights',
                   7509: 			      $depthcount+1);
                   7510: 		foreach my $rights (split(',',$rights_metadata)) {
                   7511: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7512: 		    $metathesekeys{$rights}=1;
1.339     albertel 7513: 		}
                   7514: 	    }
                   7515: 	}
1.737     albertel 7516: 	# uniqifiy package listing
                   7517: 	my %seen;
                   7518: 	my @uniq_packages =
                   7519: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7520: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7521: 
                   7522: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7523: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7524: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7525: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7526: # this is the end of "was not already recently cached
1.71      www      7527:     }
1.599     albertel 7528:     return $metaentry{':'.$what};
1.261     albertel 7529: }
                   7530: 
1.488     albertel 7531: sub metadata_create_package_def {
1.483     albertel 7532:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7533:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7534:     if ($subp eq 'default') { next; }
                   7535:     
1.599     albertel 7536:     if (defined($metaentry{':packages'})) {
                   7537: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7538:     } else {
1.599     albertel 7539: 	$metaentry{':packages'}=$package;
1.483     albertel 7540:     }
                   7541:     my $value=$packagetab{$key};
                   7542:     my $unikey;
                   7543:     $unikey='parameter_0_'.$name;
1.599     albertel 7544:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7545:     $$metathesekeys{$unikey}=1;
1.599     albertel 7546:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7547: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7548:     }
1.599     albertel 7549:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7550: 	$metaentry{':'.$unikey}=
                   7551: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7552:     }
                   7553: }
                   7554: 
1.261     albertel 7555: sub metadata_generate_part0 {
                   7556:     my ($metadata,$metacache,$uri) = @_;
                   7557:     my %allnames;
1.737     albertel 7558:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7559: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7560: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7561: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7562: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7563: 	    $allnames{$name}=$part;
                   7564: 	  }
                   7565: 	}
                   7566:     }
                   7567:     foreach my $name (keys(%allnames)) {
                   7568:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7569:       my $key=":parameter_0_$name";
1.261     albertel 7570:       $$metacache{"$key.part"}='0';
                   7571:       $$metacache{"$key.name"}=$name;
1.428     albertel 7572:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7573: 					   $allnames{$name}.'_'.$name.
                   7574: 					   '.type'};
1.428     albertel 7575:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7576: 			     '.display'};
1.644     www      7577:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7578:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7579:       $$metacache{"$key.display"}=$olddis;
                   7580:     }
1.71      www      7581: }
                   7582: 
1.764     albertel 7583: # ------------------------------------------------------ Devalidate title cache
                   7584: 
                   7585: sub devalidate_title_cache {
                   7586:     my ($url)=@_;
                   7587:     if (!$env{'request.course.id'}) { return; }
                   7588:     my $symb=&symbread($url);
                   7589:     if (!$symb) { return; }
                   7590:     my $key=$env{'request.course.id'}."\0".$symb;
                   7591:     &devalidate_cache_new('title',$key);
                   7592: }
                   7593: 
1.301     www      7594: # ------------------------------------------------- Get the title of a resource
                   7595: 
                   7596: sub gettitle {
                   7597:     my $urlsymb=shift;
                   7598:     my $symb=&symbread($urlsymb);
1.534     albertel 7599:     if ($symb) {
1.620     albertel 7600: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7601: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7602: 	if (defined($cached)) { 
                   7603: 	    return $result;
                   7604: 	}
1.534     albertel 7605: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7606: 	my $title='';
1.907     albertel 7607: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7608: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7609: 	} else {
                   7610: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7611: 		    &GDBM_READER(),0640)) {
                   7612: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7613: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7614: 		untie(%bighash);
                   7615: 	    }
1.534     albertel 7616: 	}
                   7617: 	$title=~s/\&colon\;/\:/gs;
                   7618: 	if ($title) {
1.599     albertel 7619: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7620: 	}
                   7621: 	$urlsymb=$url;
                   7622:     }
                   7623:     my $title=&metadata($urlsymb,'title');
                   7624:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7625:     return $title;
1.301     www      7626: }
1.613     albertel 7627: 
1.614     albertel 7628: sub get_slot {
                   7629:     my ($which,$cnum,$cdom)=@_;
                   7630:     if (!$cnum || !$cdom) {
1.790     albertel 7631: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7632: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7633: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7634:     }
1.703     albertel 7635:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7636:     my %slotinfo;
                   7637:     if (exists($remembered{$key})) {
                   7638: 	$slotinfo{$which} = $remembered{$key};
                   7639:     } else {
                   7640: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7641: 	&Apache::lonhomework::showhash(%slotinfo);
                   7642: 	my ($tmp)=keys(%slotinfo);
                   7643: 	if ($tmp=~/^error:/) { return (); }
                   7644: 	$remembered{$key} = $slotinfo{$which};
                   7645:     }
1.616     albertel 7646:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7647: 	return %{$slotinfo{$which}};
                   7648:     }
                   7649:     return $slotinfo{$which};
1.614     albertel 7650: }
1.31      www      7651: # ------------------------------------------------- Update symbolic store links
                   7652: 
                   7653: sub symblist {
                   7654:     my ($mapname,%newhash)=@_;
1.438     www      7655:     $mapname=&deversion(&declutter($mapname));
1.31      www      7656:     my %hash;
1.620     albertel 7657:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7658:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7659:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7660: 	    foreach my $url (keys %newhash) {
                   7661: 		next if ($url eq 'last_known'
                   7662: 			 && $env{'form.no_update_last_known'});
                   7663: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7664: 						    $newhash{$url}->[1],
                   7665: 						    $newhash{$url}->[0]);
1.191     harris41 7666:             }
1.31      www      7667:             if (untie(%hash)) {
                   7668: 		return 'ok';
                   7669:             }
                   7670:         }
                   7671:     }
                   7672:     return 'error';
1.212     www      7673: }
                   7674: 
                   7675: # --------------------------------------------------------------- Verify a symb
                   7676: 
                   7677: sub symbverify {
1.510     www      7678:     my ($symb,$thisurl)=@_;
                   7679:     my $thisfn=$thisurl;
1.439     www      7680:     $thisfn=&declutter($thisfn);
1.215     www      7681: # direct jump to resource in page or to a sequence - will construct own symbs
                   7682:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7683: # check URL part
1.409     www      7684:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7685: 
1.431     www      7686:     unless ($url eq $thisfn) { return 0; }
1.213     www      7687: 
1.216     www      7688:     $symb=&symbclean($symb);
1.510     www      7689:     $thisurl=&deversion($thisurl);
1.439     www      7690:     $thisfn=&deversion($thisfn);
1.213     www      7691: 
                   7692:     my %bighash;
                   7693:     my $okay=0;
1.431     www      7694: 
1.620     albertel 7695:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7696:                             &GDBM_READER(),0640)) {
1.510     www      7697:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7698:         unless ($ids) { 
1.510     www      7699:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7700:         }
                   7701:         if ($ids) {
                   7702: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7703: 	    foreach my $id (split(/\,/,$ids)) {
                   7704: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7705:                if (
                   7706:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7707:    eq $symb) { 
1.620     albertel 7708: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7709: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7710: 		       $okay=1; 
                   7711: 		   }
                   7712: 	       }
1.216     www      7713: 	   }
                   7714:         }
1.213     www      7715: 	untie(%bighash);
                   7716:     }
                   7717:     return $okay;
1.31      www      7718: }
                   7719: 
1.210     www      7720: # --------------------------------------------------------------- Clean-up symb
                   7721: 
                   7722: sub symbclean {
                   7723:     my $symb=shift;
1.568     albertel 7724:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7725: # remove version from map
                   7726:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7727: 
1.210     www      7728: # remove version from URL
                   7729:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7730: 
1.507     www      7731: # remove wrapper
                   7732: 
1.510     www      7733:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7734:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7735:     return $symb;
1.409     www      7736: }
                   7737: 
                   7738: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7739: 
                   7740: sub encode_symb {
                   7741:     my ($map,$resid,$url)=@_;
                   7742:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7743: }
1.409     www      7744: 
                   7745: sub decode_symb {
1.568     albertel 7746:     my $symb=shift;
                   7747:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7748:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7749:     return (&fixversion($map),$resid,&fixversion($url));
                   7750: }
                   7751: 
                   7752: sub fixversion {
                   7753:     my $fn=shift;
1.609     banghart 7754:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7755:     my %bighash;
                   7756:     my $uri=&clutter($fn);
1.620     albertel 7757:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7758: # is this cached?
1.599     albertel 7759:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7760:     if (defined($cached)) { return $result; }
                   7761: # unfortunately not cached, or expired
1.620     albertel 7762:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7763: 	    &GDBM_READER(),0640)) {
                   7764:  	if ($bighash{'version_'.$uri}) {
                   7765:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7766:  	    unless (($version eq 'mostrecent') || 
                   7767: 		    ($version==&getversion($uri))) {
1.440     www      7768:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7769:  	    }
                   7770:  	}
                   7771:  	untie %bighash;
1.413     www      7772:     }
1.599     albertel 7773:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7774: }
                   7775: 
                   7776: sub deversion {
                   7777:     my $url=shift;
                   7778:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7779:     return $url;
1.210     www      7780: }
                   7781: 
1.31      www      7782: # ------------------------------------------------------ Return symb list entry
                   7783: 
                   7784: sub symbread {
1.249     www      7785:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7786:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7787:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7788: # no filename provided? try from environment
1.44      www      7789:     unless ($thisfn) {
1.620     albertel 7790:         if ($env{'request.symb'}) {
                   7791: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7792: 	}
1.620     albertel 7793: 	$thisfn=$env{'request.filename'};
1.44      www      7794:     }
1.569     albertel 7795:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7796: # is that filename actually a symb? Verify, clean, and return
                   7797:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7798: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7799: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7800: 	}
1.242     www      7801:     }
1.44      www      7802:     $thisfn=declutter($thisfn);
1.31      www      7803:     my %hash;
1.37      www      7804:     my %bighash;
                   7805:     my $syval='';
1.620     albertel 7806:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7807:         my $targetfn = $thisfn;
1.609     banghart 7808:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7809:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7810:         }
1.687     albertel 7811: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7812: 	    $targetfn=$1;
                   7813: 	}
1.620     albertel 7814:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7815:                       &GDBM_READER(),0640)) {
1.481     raeburn  7816: 	    $syval=$hash{$targetfn};
1.37      www      7817:             untie(%hash);
                   7818:         }
                   7819: # ---------------------------------------------------------- There was an entry
                   7820:         if ($syval) {
1.601     albertel 7821: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7822: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  7823: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7824: 		    #return $env{$cache_str}='';
1.601     albertel 7825: 		#}    
                   7826: 		#$syval.=$1;
                   7827: 	    #}
1.37      www      7828:         } else {
                   7829: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7830:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7831:                             &GDBM_READER(),0640)) {
1.37      www      7832: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7833:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7834:               unless ($ids) { 
                   7835:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7836:               }
                   7837:               unless ($ids) {
                   7838: # alias?
                   7839: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7840:               }
1.37      www      7841:               if ($ids) {
                   7842: # ------------------------------------------------------------------- Has ID(s)
                   7843:                  my @possibilities=split(/\,/,$ids);
1.39      www      7844:                  if ($#possibilities==0) {
                   7845: # ----------------------------------------------- There is only one possibility
1.37      www      7846: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7847: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7848: 						    $resid,$thisfn);
1.249     www      7849:                  } elsif (!$donotrecurse) {
1.39      www      7850: # ------------------------------------------ There is more than one possibility
                   7851:                      my $realpossible=0;
1.800     albertel 7852:                      foreach my $id (@possibilities) {
                   7853: 			 my $file=$bighash{'src_'.$id};
1.39      www      7854:                          if (&allowed('bre',$file)) {
1.800     albertel 7855:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7856:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7857: 				$realpossible++;
1.626     albertel 7858:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7859: 						    $resid,$thisfn);
1.39      www      7860:                             }
                   7861: 			 }
1.191     harris41 7862:                      }
1.39      www      7863: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7864:                  } else {
                   7865:                      $syval='';
1.37      www      7866:                  }
                   7867: 	      }
                   7868:               untie(%bighash)
1.481     raeburn  7869:            }
1.31      www      7870:         }
1.62      www      7871:         if ($syval) {
1.620     albertel 7872: 	    return $env{$cache_str}=$syval;
1.62      www      7873:         }
1.31      www      7874:     }
1.949     raeburn  7875:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7876:     return $env{$cache_str}='';
1.31      www      7877: }
                   7878: 
                   7879: # ---------------------------------------------------------- Return random seed
                   7880: 
1.32      www      7881: sub numval {
                   7882:     my $txt=shift;
                   7883:     $txt=~tr/A-J/0-9/;
                   7884:     $txt=~tr/a-j/0-9/;
                   7885:     $txt=~tr/K-T/0-9/;
                   7886:     $txt=~tr/k-t/0-9/;
                   7887:     $txt=~tr/U-Z/0-5/;
                   7888:     $txt=~tr/u-z/0-5/;
                   7889:     $txt=~s/\D//g;
1.564     albertel 7890:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7891:     return int($txt);
1.368     albertel 7892: }
                   7893: 
1.484     albertel 7894: sub numval2 {
                   7895:     my $txt=shift;
                   7896:     $txt=~tr/A-J/0-9/;
                   7897:     $txt=~tr/a-j/0-9/;
                   7898:     $txt=~tr/K-T/0-9/;
                   7899:     $txt=~tr/k-t/0-9/;
                   7900:     $txt=~tr/U-Z/0-5/;
                   7901:     $txt=~tr/u-z/0-5/;
                   7902:     $txt=~s/\D//g;
                   7903:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7904:     my $total;
                   7905:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7906:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7907:     return int($total);
                   7908: }
                   7909: 
1.575     albertel 7910: sub numval3 {
                   7911:     use integer;
                   7912:     my $txt=shift;
                   7913:     $txt=~tr/A-J/0-9/;
                   7914:     $txt=~tr/a-j/0-9/;
                   7915:     $txt=~tr/K-T/0-9/;
                   7916:     $txt=~tr/k-t/0-9/;
                   7917:     $txt=~tr/U-Z/0-5/;
                   7918:     $txt=~tr/u-z/0-5/;
                   7919:     $txt=~s/\D//g;
                   7920:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7921:     my $total;
                   7922:     foreach my $val (@txts) { $total+=$val; }
                   7923:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7924:     return $total;
                   7925: }
                   7926: 
1.675     albertel 7927: sub digest {
                   7928:     my ($data)=@_;
                   7929:     my $digest=&Digest::MD5::md5($data);
                   7930:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7931:     my ($e,$f);
                   7932:     {
                   7933:         use integer;
                   7934:         $e=($a+$b);
                   7935:         $f=($c+$d);
                   7936:         if ($_64bit) {
                   7937:             $e=(($e<<32)>>32);
                   7938:             $f=(($f<<32)>>32);
                   7939:         }
                   7940:     }
                   7941:     if (wantarray) {
                   7942: 	return ($e,$f);
                   7943:     } else {
                   7944: 	my $g;
                   7945: 	{
                   7946: 	    use integer;
                   7947: 	    $g=($e+$f);
                   7948: 	    if ($_64bit) {
                   7949: 		$g=(($g<<32)>>32);
                   7950: 	    }
                   7951: 	}
                   7952: 	return $g;
                   7953:     }
                   7954: }
                   7955: 
1.368     albertel 7956: sub latest_rnd_algorithm_id {
1.675     albertel 7957:     return '64bit5';
1.366     albertel 7958: }
1.32      www      7959: 
1.503     albertel 7960: sub get_rand_alg {
                   7961:     my ($courseid)=@_;
1.790     albertel 7962:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7963:     if ($courseid) {
1.620     albertel 7964: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7965:     }
                   7966:     return &latest_rnd_algorithm_id();
                   7967: }
                   7968: 
1.562     albertel 7969: sub validCODE {
                   7970:     my ($CODE)=@_;
                   7971:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7972:     return 0;
                   7973: }
                   7974: 
1.491     albertel 7975: sub getCODE {
1.620     albertel 7976:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7977:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7978: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7979: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7980: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7981:     }
                   7982:     return undef;
                   7983: }
                   7984: 
1.31      www      7985: sub rndseed {
1.155     albertel 7986:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7987:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7988:     if (!defined($symb)) {
1.366     albertel 7989: 	unless ($symb=$wsymb) { return time; }
                   7990:     }
                   7991:     if (!$courseid) { $courseid=$wcourseid; }
                   7992:     if (!$domain) { $domain=$wdomain; }
                   7993:     if (!$username) { $username=$wusername }
1.503     albertel 7994:     my $which=&get_rand_alg();
1.803     albertel 7995: 
1.491     albertel 7996:     if (defined(&getCODE())) {
1.675     albertel 7997: 	if ($which eq '64bit5') {
                   7998: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7999: 	} elsif ($which eq '64bit4') {
1.575     albertel 8000: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   8001: 	} else {
                   8002: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   8003: 	}
1.675     albertel 8004:     } elsif ($which eq '64bit5') {
                   8005: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 8006:     } elsif ($which eq '64bit4') {
                   8007: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 8008:     } elsif ($which eq '64bit3') {
                   8009: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 8010:     } elsif ($which eq '64bit2') {
                   8011: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 8012:     } elsif ($which eq '64bit') {
                   8013: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   8014:     }
                   8015:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   8016: }
                   8017: 
                   8018: sub rndseed_32bit {
                   8019:     my ($symb,$courseid,$domain,$username)=@_;
                   8020:     {
                   8021: 	use integer;
                   8022: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   8023: 	my $symbseed=numval($symb) << 22;
                   8024: 	my $namechck=unpack("%32C*",$username) << 17;
                   8025: 	my $nameseed=numval($username) << 12;
                   8026: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   8027: 	my $courseseed=unpack("%32C*",$courseid);
                   8028: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 8029: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8030: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8031: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 8032: 	return $num;
                   8033:     }
                   8034: }
                   8035: 
                   8036: sub rndseed_64bit {
                   8037:     my ($symb,$courseid,$domain,$username)=@_;
                   8038:     {
                   8039: 	use integer;
                   8040: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   8041: 	my $symbseed=numval($symb) << 10;
                   8042: 	my $namechck=unpack("%32S*",$username);
                   8043: 	
                   8044: 	my $nameseed=numval($username) << 21;
                   8045: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   8046: 	my $courseseed=unpack("%32S*",$courseid);
                   8047: 	
                   8048: 	my $num1=$symbchck+$symbseed+$namechck;
                   8049: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8050: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8051: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8052: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 8053: 	return "$num1,$num2";
1.155     albertel 8054:     }
1.366     albertel 8055: }
                   8056: 
1.443     albertel 8057: sub rndseed_64bit2 {
                   8058:     my ($symb,$courseid,$domain,$username)=@_;
                   8059:     {
                   8060: 	use integer;
                   8061: 	# strings need to be an even # of cahracters long, it it is odd the
                   8062:         # last characters gets thrown away
                   8063: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8064: 	my $symbseed=numval($symb) << 10;
                   8065: 	my $namechck=unpack("%32S*",$username.' ');
                   8066: 	
                   8067: 	my $nameseed=numval($username) << 21;
1.501     albertel 8068: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8069: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8070: 	
                   8071: 	my $num1=$symbchck+$symbseed+$namechck;
                   8072: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8073: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8074: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 8075: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 8076: 	return "$num1,$num2";
                   8077:     }
                   8078: }
                   8079: 
                   8080: sub rndseed_64bit3 {
                   8081:     my ($symb,$courseid,$domain,$username)=@_;
                   8082:     {
                   8083: 	use integer;
                   8084: 	# strings need to be an even # of cahracters long, it it is odd the
                   8085:         # last characters gets thrown away
                   8086: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8087: 	my $symbseed=numval2($symb) << 10;
                   8088: 	my $namechck=unpack("%32S*",$username.' ');
                   8089: 	
                   8090: 	my $nameseed=numval2($username) << 21;
1.443     albertel 8091: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8092: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8093: 	
                   8094: 	my $num1=$symbchck+$symbseed+$namechck;
                   8095: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8096: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8097: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 8098: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8099: 	
1.503     albertel 8100: 	return "$num1:$num2";
1.443     albertel 8101:     }
                   8102: }
                   8103: 
1.575     albertel 8104: sub rndseed_64bit4 {
                   8105:     my ($symb,$courseid,$domain,$username)=@_;
                   8106:     {
                   8107: 	use integer;
                   8108: 	# strings need to be an even # of cahracters long, it it is odd the
                   8109:         # last characters gets thrown away
                   8110: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8111: 	my $symbseed=numval3($symb) << 10;
                   8112: 	my $namechck=unpack("%32S*",$username.' ');
                   8113: 	
                   8114: 	my $nameseed=numval3($username) << 21;
                   8115: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8116: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8117: 	
                   8118: 	my $num1=$symbchck+$symbseed+$namechck;
                   8119: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8120: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8121: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 8122: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8123: 	
                   8124: 	return "$num1:$num2";
                   8125:     }
                   8126: }
                   8127: 
1.675     albertel 8128: sub rndseed_64bit5 {
                   8129:     my ($symb,$courseid,$domain,$username)=@_;
                   8130:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   8131:     return "$num1:$num2";
                   8132: }
                   8133: 
1.366     albertel 8134: sub rndseed_CODE_64bit {
                   8135:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 8136:     {
1.366     albertel 8137: 	use integer;
1.443     albertel 8138: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 8139: 	my $symbseed=numval2($symb);
1.491     albertel 8140: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8141: 	my $CODEseed=numval(&getCODE());
1.443     albertel 8142: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 8143: 	my $num1=$symbseed+$CODEchck;
                   8144: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8145: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8146: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 8147: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8148: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 8149: 	return "$num1:$num2";
1.366     albertel 8150:     }
                   8151: }
                   8152: 
1.575     albertel 8153: sub rndseed_CODE_64bit4 {
                   8154:     my ($symb,$courseid,$domain,$username)=@_;
                   8155:     {
                   8156: 	use integer;
                   8157: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   8158: 	my $symbseed=numval3($symb);
                   8159: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8160: 	my $CODEseed=numval3(&getCODE());
                   8161: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8162: 	my $num1=$symbseed+$CODEchck;
                   8163: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8164: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8165: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 8166: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8167: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   8168: 	return "$num1:$num2";
                   8169:     }
                   8170: }
                   8171: 
1.675     albertel 8172: sub rndseed_CODE_64bit5 {
                   8173:     my ($symb,$courseid,$domain,$username)=@_;
                   8174:     my $code = &getCODE();
                   8175:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   8176:     return "$num1:$num2";
                   8177: }
                   8178: 
1.366     albertel 8179: sub setup_random_from_rndseed {
                   8180:     my ($rndseed)=@_;
1.503     albertel 8181:     if ($rndseed =~/([,:])/) {
                   8182: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 8183: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   8184:     } else {
                   8185: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 8186:     }
1.36      albertel 8187: }
                   8188: 
1.474     albertel 8189: sub latest_receipt_algorithm_id {
1.835     albertel 8190:     return 'receipt3';
1.474     albertel 8191: }
                   8192: 
1.480     www      8193: sub recunique {
                   8194:     my $fucourseid=shift;
                   8195:     my $unique;
1.835     albertel 8196:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   8197: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8198: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      8199:     } else {
                   8200: 	$unique=$perlvar{'lonReceipt'};
                   8201:     }
                   8202:     return unpack("%32C*",$unique);
                   8203: }
                   8204: 
                   8205: sub recprefix {
                   8206:     my $fucourseid=shift;
                   8207:     my $prefix;
1.835     albertel 8208:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   8209: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8210: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      8211:     } else {
                   8212: 	$prefix=$perlvar{'lonHostID'};
                   8213:     }
                   8214:     return unpack("%32C*",$prefix);
                   8215: }
                   8216: 
1.76      www      8217: sub ireceipt {
1.474     albertel 8218:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 8219: 
                   8220:     my $return =&recprefix($fucourseid).'-';
                   8221: 
                   8222:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   8223: 	$env{'request.state'} eq 'construct') {
                   8224: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   8225: 	return $return;
                   8226:     }
                   8227: 
1.76      www      8228:     my $cuname=unpack("%32C*",$funame);
                   8229:     my $cudom=unpack("%32C*",$fudom);
                   8230:     my $cucourseid=unpack("%32C*",$fucourseid);
                   8231:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      8232:     my $cunique=&recunique($fucourseid);
1.474     albertel 8233:     my $cpart=unpack("%32S*",$part);
1.835     albertel 8234:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   8235: 
1.790     albertel 8236: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 8237: 			       
                   8238: 	$return.= ($cunique%$cuname+
                   8239: 		   $cunique%$cudom+
                   8240: 		   $cusymb%$cuname+
                   8241: 		   $cusymb%$cudom+
                   8242: 		   $cucourseid%$cuname+
                   8243: 		   $cucourseid%$cudom+
                   8244: 		   $cpart%$cuname+
                   8245: 		   $cpart%$cudom);
                   8246:     } else {
                   8247: 	$return.= ($cunique%$cuname+
                   8248: 		   $cunique%$cudom+
                   8249: 		   $cusymb%$cuname+
                   8250: 		   $cusymb%$cudom+
                   8251: 		   $cucourseid%$cuname+
                   8252: 		   $cucourseid%$cudom);
                   8253:     }
                   8254:     return $return;
1.76      www      8255: }
                   8256: 
                   8257: sub receipt {
1.474     albertel 8258:     my ($part)=@_;
1.790     albertel 8259:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 8260:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      8261: }
1.260     ng       8262: 
1.790     albertel 8263: sub whichuser {
                   8264:     my ($passedsymb)=@_;
                   8265:     my ($symb,$courseid,$domain,$name,$publicuser);
                   8266:     if (defined($env{'form.grade_symb'})) {
                   8267: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   8268: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   8269: 	if (!$allowed &&
                   8270: 	    exists($env{'request.course.sec'}) &&
                   8271: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   8272: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   8273: 			      '/'.$env{'request.course.sec'});
                   8274: 	}
                   8275: 	if ($allowed) {
                   8276: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   8277: 	    $courseid=$tmp_courseid;
                   8278: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   8279: 	    ($name)=&get_env_multiple('form.grade_username');
                   8280: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   8281: 	}
                   8282:     }
                   8283:     if (!$passedsymb) {
                   8284: 	$symb=&symbread();
                   8285:     } else {
                   8286: 	$symb=$passedsymb;
                   8287:     }
                   8288:     $courseid=$env{'request.course.id'};
                   8289:     $domain=$env{'user.domain'};
                   8290:     $name=$env{'user.name'};
                   8291:     if ($name eq 'public' && $domain eq 'public') {
                   8292: 	if (!defined($env{'form.username'})) {
                   8293: 	    $env{'form.username'}.=time.rand(10000000);
                   8294: 	}
                   8295: 	$name.=$env{'form.username'};
                   8296:     }
                   8297:     return ($symb,$courseid,$domain,$name,$publicuser);
                   8298: 
                   8299: }
                   8300: 
1.36      albertel 8301: # ------------------------------------------------------------ Serves up a file
1.472     albertel 8302: # returns either the contents of the file or 
                   8303: # -1 if the file doesn't exist
1.481     raeburn  8304: #
                   8305: # if the target is a file that was uploaded via DOCS, 
                   8306: # a check will be made to see if a current copy exists on the local server,
                   8307: # if it does this will be served, otherwise a copy will be retrieved from
                   8308: # the home server for the course and stored in /home/httpd/html/userfiles on
                   8309: # the local server.   
1.472     albertel 8310: 
1.36      albertel 8311: sub getfile {
1.538     albertel 8312:     my ($file) = @_;
1.609     banghart 8313:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 8314:     &repcopy($file);
                   8315:     return &readfile($file);
                   8316: }
                   8317: 
                   8318: sub repcopy_userfile {
                   8319:     my ($file)=@_;
1.609     banghart 8320:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 8321:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 8322:     my ($cdom,$cnum,$filename) = 
1.811     albertel 8323: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 8324:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   8325:     if (-e "$file") {
1.828     www      8326: # we already have a local copy, check it out
1.538     albertel 8327: 	my @fileinfo = stat($file);
1.828     www      8328: 	my $rtncode;
                   8329: 	my $info;
1.538     albertel 8330: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 8331: 	if ($lwpresp ne 'ok') {
1.828     www      8332: # there is no such file anymore, even though we had a local copy
1.482     albertel 8333: 	    if ($rtncode eq '404') {
1.538     albertel 8334: 		unlink($file);
1.482     albertel 8335: 	    }
                   8336: 	    return -1;
                   8337: 	}
                   8338: 	if ($info < $fileinfo[9]) {
1.828     www      8339: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  8340: 	    return 'ok';
1.828     www      8341: 	} else {
                   8342: # the file is outdated, get rid of it
                   8343: 	    unlink($file);
1.482     albertel 8344: 	}
1.828     www      8345:     }
                   8346: # one way or the other, at this point, we don't have the file
                   8347: # construct the correct path for the file
                   8348:     my @parts = ($cdom,$cnum); 
                   8349:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   8350: 	push @parts, split(/\//,$1);
                   8351:     }
                   8352:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   8353:     foreach my $part (@parts) {
                   8354: 	$path .= '/'.$part;
                   8355: 	if (!-e $path) {
                   8356: 	    mkdir($path,0770);
1.482     albertel 8357: 	}
                   8358:     }
1.828     www      8359: # now the path exists for sure
                   8360: # get a user agent
                   8361:     my $ua=new LWP::UserAgent;
                   8362:     my $transferfile=$file.'.in.transfer';
                   8363: # FIXME: this should flock
                   8364:     if (-e $transferfile) { return 'ok'; }
                   8365:     my $request;
                   8366:     $uri=~s/^\///;
1.976.2.3  raeburn  8367:     my $homeserver = &homeserver($cnum,$cdom);
                   8368:     my $protocol = $protocol{$homeserver};
                   8369:     $protocol = 'http' if ($protocol ne 'https');
                   8370:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      8371:     my $response=$ua->request($request,$transferfile);
                   8372: # did it work?
                   8373:     if ($response->is_error()) {
                   8374: 	unlink($transferfile);
                   8375: 	&logthis("Userfile repcopy failed for $uri");
                   8376: 	return -1;
                   8377:     }
                   8378: # worked, rename the transfer file
                   8379:     rename($transferfile,$file);
1.607     raeburn  8380:     return 'ok';
1.481     raeburn  8381: }
                   8382: 
1.517     albertel 8383: sub tokenwrapper {
                   8384:     my $uri=shift;
1.976.2.3  raeburn  8385:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 8386:     $uri=~s|^/||;
1.620     albertel 8387:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8388:     my $token=$1;
1.552     albertel 8389:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8390:     if ($udom && $uname && $file) {
                   8391: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8392:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.976.2.3  raeburn  8393:         my $homeserver = &homeserver($uname,$udom);
                   8394:         my $protocol = $protocol{$homeserver};
                   8395:         $protocol = 'http' if ($protocol ne 'https');
                   8396:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 8397:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8398:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8399:     } else {
                   8400:         return '/adm/notfound.html';
                   8401:     }
                   8402: }
                   8403: 
1.828     www      8404: # call with reqtype HEAD: get last modification time
                   8405: # call with reqtype GET: get the file contents
                   8406: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8407: #
1.481     raeburn  8408: sub getuploaded {
                   8409:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8410:     $uri=~s/^\///;
1.976.2.3  raeburn  8411:     my $homeserver = &homeserver($cnum,$cdom);
                   8412:     my $protocol = $protocol{$homeserver};
                   8413:     $protocol = 'http' if ($protocol ne 'https');
                   8414:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  8415:     my $ua=new LWP::UserAgent;
                   8416:     my $request=new HTTP::Request($reqtype,$uri);
                   8417:     my $response=$ua->request($request);
                   8418:     $$rtncode = $response->code;
1.482     albertel 8419:     if (! $response->is_success()) {
                   8420: 	return 'failed';
                   8421:     }      
                   8422:     if ($reqtype eq 'HEAD') {
1.486     www      8423: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8424:     } elsif ($reqtype eq 'GET') {
                   8425: 	$$info = $response->content;
1.472     albertel 8426:     }
1.482     albertel 8427:     return 'ok';
1.36      albertel 8428: }
                   8429: 
1.481     raeburn  8430: sub readfile {
                   8431:     my $file = shift;
                   8432:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8433:     my $fh;
                   8434:     open($fh,"<$file");
                   8435:     my $a='';
1.800     albertel 8436:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8437:     return $a;
                   8438: }
                   8439: 
1.36      albertel 8440: sub filelocation {
1.590     banghart 8441:     my ($dir,$file) = @_;
                   8442:     my $location;
                   8443:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8444: 
                   8445:     if ($file =~ m-^/adm/-) {
                   8446: 	$file=~s-^/adm/wrapper/-/-;
                   8447: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8448:     }
1.882     albertel 8449: 
1.590     banghart 8450:     if ($file=~m:^/~:) { # is a contruction space reference
                   8451:         $location = $file;
                   8452:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8453:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8454: 	# is a correct contruction space reference
                   8455:         $location = $file;
1.956     raeburn  8456:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   8457:         $location = $file;
1.609     banghart 8458:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8459:         my ($udom,$uname,$filename)=
1.811     albertel 8460:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8461:         my $home=&homeserver($uname,$udom);
                   8462:         my $is_me=0;
                   8463:         my @ids=&current_machine_ids();
                   8464:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8465:         if ($is_me) {
1.955     raeburn  8466:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 8467:         } else {
                   8468:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8469:   	      $udom.'/'.$uname.'/'.$filename;
                   8470:         }
1.882     albertel 8471:     } elsif ($file =~ m-^/adm/-) {
                   8472: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8473:     } else {
                   8474:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8475:         $file=~s:^/res/:/:;
                   8476:         if ( !( $file =~ m:^/:) ) {
                   8477:             $location = $dir. '/'.$file;
                   8478:         } else {
                   8479:             $location = '/home/httpd/html/res'.$file;
                   8480:         }
1.59      albertel 8481:     }
1.590     banghart 8482:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8483:     while ($location=~m{/\.\./}) {
                   8484: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8485: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8486: 	} else {
                   8487: 	    $location=~ s{/\.\./}{/}g;
                   8488: 	}
                   8489:     } #remove dir/..
1.590     banghart 8490:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8491:     return $location;
1.46      www      8492: }
1.36      albertel 8493: 
1.46      www      8494: sub hreflocation {
                   8495:     my ($dir,$file)=@_;
1.976.2.3  raeburn  8496:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 8497: 	$file=filelocation($dir,$file);
1.700     albertel 8498:     } elsif ($file=~m-^/adm/-) {
                   8499: 	$file=~s-^/adm/wrapper/-/-;
                   8500: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8501:     }
                   8502:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8503: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8504:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8505: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8506:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8507: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8508: 	    -/uploaded/$1/$2/-x;
1.46      www      8509:     }
1.913     albertel 8510:     if ($file=~ m{^/userfiles/}) {
                   8511: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8512:     }
1.462     albertel 8513:     return $file;
1.465     albertel 8514: }
                   8515: 
                   8516: sub current_machine_domains {
1.853     albertel 8517:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8518: }
                   8519: 
                   8520: sub machine_domains {
                   8521:     my ($hostname) = @_;
1.465     albertel 8522:     my @domains;
1.838     albertel 8523:     my %hostname = &all_hostnames();
1.465     albertel 8524:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8525: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8526: 	if ($hostname eq $name) {
1.844     albertel 8527: 	    push(@domains,&host_domain($id));
1.465     albertel 8528: 	}
                   8529:     }
                   8530:     return @domains;
                   8531: }
                   8532: 
                   8533: sub current_machine_ids {
1.853     albertel 8534:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8535: }
                   8536: 
                   8537: sub machine_ids {
                   8538:     my ($hostname) = @_;
                   8539:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8540:     my @ids;
1.888     albertel 8541:     my %name_to_host = &all_names();
1.889     albertel 8542:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8543: 	return @{ $name_to_host{$hostname} };
                   8544:     }
                   8545:     return;
1.31      www      8546: }
                   8547: 
1.824     raeburn  8548: sub additional_machine_domains {
                   8549:     my @domains;
                   8550:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8551:     while( my $line = <$fh>) {
                   8552:         $line =~ s/\s//g;
                   8553:         push(@domains,$line);
                   8554:     }
                   8555:     return @domains;
                   8556: }
                   8557: 
                   8558: sub default_login_domain {
                   8559:     my $domain = $perlvar{'lonDefDomain'};
                   8560:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8561:     foreach my $posdom (&current_machine_domains(),
                   8562:                         &additional_machine_domains()) {
                   8563:         if (lc($posdom) eq lc($testdomain)) {
                   8564:             $domain=$posdom;
                   8565:             last;
                   8566:         }
                   8567:     }
                   8568:     return $domain;
                   8569: }
                   8570: 
1.31      www      8571: # ------------------------------------------------------------- Declutters URLs
                   8572: 
                   8573: sub declutter {
                   8574:     my $thisfn=shift;
1.569     albertel 8575:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8576:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8577:     $thisfn=~s/^\///;
1.697     albertel 8578:     $thisfn=~s|^adm/wrapper/||;
                   8579:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8580:     $thisfn=~s/^res\///;
1.235     www      8581:     $thisfn=~s/\?.+$//;
1.268     www      8582:     return $thisfn;
                   8583: }
                   8584: 
                   8585: # ------------------------------------------------------------- Clutter up URLs
                   8586: 
                   8587: sub clutter {
                   8588:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8589:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8590: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8591:        $thisfn='/res'.$thisfn; 
                   8592:     }
1.694     albertel 8593:     if ($thisfn !~m|/adm|) {
1.695     albertel 8594: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8595: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8596: 	} else {
                   8597: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8598: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8599: 	    if ($embstyle eq 'ssi'
                   8600: 		|| ($embstyle eq 'hdn')
                   8601: 		|| ($embstyle eq 'rat')
                   8602: 		|| ($embstyle eq 'prv')
                   8603: 		|| ($embstyle eq 'ign')) {
                   8604: 		#do nothing with these
                   8605: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8606: 		|| ($embstyle eq 'emb')
                   8607: 		|| ($embstyle eq 'wrp')) {
                   8608: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8609: 	    } elsif ($embstyle eq 'unk'
                   8610: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8611: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8612: 	    } else {
1.718     www      8613: #		&logthis("Got a blank emb style");
1.695     albertel 8614: 	    }
1.694     albertel 8615: 	}
                   8616:     }
1.31      www      8617:     return $thisfn;
1.12      www      8618: }
                   8619: 
1.787     albertel 8620: sub clutter_with_no_wrapper {
                   8621:     my $uri = &clutter(shift);
                   8622:     if ($uri =~ m-^/adm/-) {
                   8623: 	$uri =~ s-^/adm/wrapper/-/-;
                   8624: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8625:     }
                   8626:     return $uri;
                   8627: }
                   8628: 
1.557     albertel 8629: sub freeze_escape {
                   8630:     my ($value)=@_;
                   8631:     if (ref($value)) {
                   8632: 	$value=&nfreeze($value);
                   8633: 	return '__FROZEN__'.&escape($value);
                   8634:     }
                   8635:     return &escape($value);
                   8636: }
                   8637: 
1.11      www      8638: 
1.557     albertel 8639: sub thaw_unescape {
                   8640:     my ($value)=@_;
                   8641:     if ($value =~ /^__FROZEN__/) {
                   8642: 	substr($value,0,10,undef);
                   8643: 	$value=&unescape($value);
                   8644: 	return &thaw($value);
                   8645:     }
                   8646:     return &unescape($value);
                   8647: }
                   8648: 
1.436     albertel 8649: sub correct_line_ends {
                   8650:     my ($result)=@_;
                   8651:     $$result =~s/\r\n/\n/mg;
                   8652:     $$result =~s/\r/\n/mg;
1.415     albertel 8653: }
1.1       albertel 8654: # ================================================================ Main Program
                   8655: 
1.184     www      8656: sub goodbye {
1.204     albertel 8657:    &logthis("Starting Shut down");
1.443     albertel 8658: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8659:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8660: #converted
1.599     albertel 8661: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8662:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8663: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8664: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8665: #1.1 only
1.870     albertel 8666: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8667: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8668: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8669: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8670:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8671:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8672:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8673:    &flushcourselogs();
                   8674:    &logthis("Shutting down");
                   8675: }
                   8676: 
1.852     albertel 8677: sub get_dns {
1.869     albertel 8678:     my ($url,$func,$ignore_cache) = @_;
                   8679:     if (!$ignore_cache) {
                   8680: 	my ($content,$cached)=
                   8681: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8682: 	if ($cached) {
                   8683: 	    &$func($content);
                   8684: 	    return;
                   8685: 	}
                   8686:     }
                   8687: 
                   8688:     my %alldns;
1.852     albertel 8689:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8690:     foreach my $dns (<$config>) {
                   8691: 	next if ($dns !~ /^\^(\S*)/x);
1.976.2.2  raeburn  8692:         my $line = $1;
                   8693:         my ($host,$protocol) = split(/:/,$line);
                   8694:         if ($protocol ne 'https') {
                   8695:             $protocol = 'http';
                   8696:         }
                   8697: 	$alldns{$host} = $protocol;
1.869     albertel 8698:     }
                   8699:     while (%alldns) {
                   8700: 	my ($dns) = keys(%alldns);
1.852     albertel 8701: 	my $ua=new LWP::UserAgent;
1.976.2.2  raeburn  8702: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 8703: 	my $response=$ua->request($request);
1.976.2.2  raeburn  8704:         delete($alldns{$dns});
1.852     albertel 8705: 	next if ($response->is_error());
                   8706: 	my @content = split("\n",$response->content);
1.869     albertel 8707: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8708: 	&$func(\@content);
1.869     albertel 8709: 	return;
1.852     albertel 8710:     }
                   8711:     close($config);
1.871     albertel 8712:     my $which = (split('/',$url))[3];
                   8713:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8714:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8715:     my @content = <$config>;
                   8716:     &$func(\@content);
                   8717:     return;
1.852     albertel 8718: }
1.327     albertel 8719: # ------------------------------------------------------------ Read domain file
                   8720: {
1.852     albertel 8721:     my $loaded;
1.846     albertel 8722:     my %domain;
                   8723: 
1.852     albertel 8724:     sub parse_domain_tab {
                   8725: 	my ($lines) = @_;
                   8726: 	foreach my $line (@$lines) {
                   8727: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8728: 
1.846     albertel 8729: 	    chomp($line);
1.852     albertel 8730: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8731: 	    my %this_domain;
                   8732: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8733: 			       'lang_def', 'city', 'longi', 'lati',
                   8734: 			       'primary') {
                   8735: 		$this_domain{$field} = shift(@elements);
                   8736: 	    }
                   8737: 	    $domain{$name} = \%this_domain;
1.852     albertel 8738: 	}
                   8739:     }
1.864     albertel 8740: 
                   8741:     sub reset_domain_info {
                   8742: 	undef($loaded);
                   8743: 	undef(%domain);
                   8744:     }
                   8745: 
1.852     albertel 8746:     sub load_domain_tab {
1.869     albertel 8747: 	my ($ignore_cache) = @_;
                   8748: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8749: 	my $fh;
                   8750: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8751: 	    my @lines = <$fh>;
                   8752: 	    &parse_domain_tab(\@lines);
1.448     albertel 8753: 	}
1.852     albertel 8754: 	close($fh);
                   8755: 	$loaded = 1;
1.327     albertel 8756:     }
1.846     albertel 8757: 
                   8758:     sub domain {
1.852     albertel 8759: 	&load_domain_tab() if (!$loaded);
                   8760: 
1.846     albertel 8761: 	my ($name,$what) = @_;
                   8762: 	return if ( !exists($domain{$name}) );
                   8763: 
                   8764: 	if (!$what) {
                   8765: 	    return $domain{$name}{'description'};
                   8766: 	}
                   8767: 	return $domain{$name}{$what};
                   8768:     }
1.974     raeburn  8769: 
                   8770:     sub domain_info {
                   8771:         &load_domain_tab() if (!$loaded);
                   8772:         return %domain;
                   8773:     }
                   8774: 
1.327     albertel 8775: }
                   8776: 
                   8777: 
1.1       albertel 8778: # ------------------------------------------------------------- Read hosts file
                   8779: {
1.838     albertel 8780:     my %hostname;
1.844     albertel 8781:     my %hostdom;
1.845     albertel 8782:     my %libserv;
1.852     albertel 8783:     my $loaded;
1.888     albertel 8784:     my %name_to_host;
1.852     albertel 8785: 
                   8786:     sub parse_hosts_tab {
                   8787: 	my ($file) = @_;
                   8788: 	foreach my $configline (@$file) {
                   8789: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8790: 	    next if ($configline =~ /^\^/);
                   8791: 	    chomp($configline);
1.968     raeburn  8792: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852     albertel 8793: 	    $name=~s/\s//g;
                   8794: 	    if ($id && $domain && $role && $name) {
                   8795: 		$hostname{$id}=$name;
1.888     albertel 8796: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8797: 		$hostdom{$id}=$domain;
                   8798: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  8799:                 if (defined($protocol)) {
                   8800:                     if ($protocol eq 'https') {
                   8801:                         $protocol{$id} = $protocol;
                   8802:                     } else {
                   8803:                         $protocol{$id} = 'http'; 
                   8804:                     }
1.968     raeburn  8805:                 } else {
1.969     raeburn  8806:                     $protocol{$id} = 'http';
1.968     raeburn  8807:                 }
1.852     albertel 8808: 	    }
                   8809: 	}
                   8810:     }
1.864     albertel 8811:     
                   8812:     sub reset_hosts_info {
1.897     albertel 8813: 	&purge_remembered();
1.864     albertel 8814: 	&reset_domain_info();
                   8815: 	&reset_hosts_ip_info();
1.892     albertel 8816: 	undef(%name_to_host);
1.864     albertel 8817: 	undef(%hostname);
                   8818: 	undef(%hostdom);
                   8819: 	undef(%libserv);
                   8820: 	undef($loaded);
                   8821:     }
1.1       albertel 8822: 
1.852     albertel 8823:     sub load_hosts_tab {
1.869     albertel 8824: 	my ($ignore_cache) = @_;
                   8825: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8826: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8827: 	my @config = <$config>;
                   8828: 	&parse_hosts_tab(\@config);
                   8829: 	close($config);
                   8830: 	$loaded=1;
1.1       albertel 8831:     }
1.852     albertel 8832: 
1.838     albertel 8833:     sub hostname {
1.852     albertel 8834: 	&load_hosts_tab() if (!$loaded);
                   8835: 
1.838     albertel 8836: 	my ($lonid) = @_;
                   8837: 	return $hostname{$lonid};
                   8838:     }
1.845     albertel 8839: 
1.838     albertel 8840:     sub all_hostnames {
1.852     albertel 8841: 	&load_hosts_tab() if (!$loaded);
                   8842: 
1.838     albertel 8843: 	return %hostname;
                   8844:     }
1.845     albertel 8845: 
1.888     albertel 8846:     sub all_names {
                   8847: 	&load_hosts_tab() if (!$loaded);
                   8848: 
                   8849: 	return %name_to_host;
                   8850:     }
                   8851: 
1.974     raeburn  8852:     sub all_host_domain {
                   8853:         &load_hosts_tab() if (!$loaded);
                   8854:         return %hostdom;
                   8855:     }
                   8856: 
1.845     albertel 8857:     sub is_library {
1.852     albertel 8858: 	&load_hosts_tab() if (!$loaded);
                   8859: 
1.845     albertel 8860: 	return exists($libserv{$_[0]});
                   8861:     }
                   8862: 
                   8863:     sub all_library {
1.852     albertel 8864: 	&load_hosts_tab() if (!$loaded);
                   8865: 
1.845     albertel 8866: 	return %libserv;
                   8867:     }
                   8868: 
1.841     albertel 8869:     sub get_servers {
1.852     albertel 8870: 	&load_hosts_tab() if (!$loaded);
                   8871: 
1.841     albertel 8872: 	my ($domain,$type) = @_;
                   8873: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8874: 	                                          : %hostname;
                   8875: 	my %result;
1.842     albertel 8876: 	if (ref($domain) eq 'ARRAY') {
                   8877: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8878: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8879: 		    $result{$host} = $hostname;
                   8880: 		}
                   8881: 	    }
                   8882: 	} else {
                   8883: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8884: 		if ($hostdom{$host} eq $domain) {
                   8885: 		    $result{$host} = $hostname;
                   8886: 		}
1.841     albertel 8887: 	    }
                   8888: 	}
                   8889: 	return %result;
                   8890:     }
1.845     albertel 8891: 
1.844     albertel 8892:     sub host_domain {
1.852     albertel 8893: 	&load_hosts_tab() if (!$loaded);
                   8894: 
1.844     albertel 8895: 	my ($lonid) = @_;
                   8896: 	return $hostdom{$lonid};
                   8897:     }
                   8898: 
1.841     albertel 8899:     sub all_domains {
1.852     albertel 8900: 	&load_hosts_tab() if (!$loaded);
                   8901: 
1.841     albertel 8902: 	my %seen;
                   8903: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8904: 	return @uniq;
                   8905:     }
1.1       albertel 8906: }
                   8907: 
1.847     albertel 8908: { 
                   8909:     my %iphost;
1.856     albertel 8910:     my %name_to_ip;
                   8911:     my %lonid_to_ip;
1.869     albertel 8912: 
1.847     albertel 8913:     sub get_hosts_from_ip {
                   8914: 	my ($ip) = @_;
                   8915: 	my %iphosts = &get_iphost();
                   8916: 	if (ref($iphosts{$ip})) {
                   8917: 	    return @{$iphosts{$ip}};
                   8918: 	}
                   8919: 	return;
1.839     albertel 8920:     }
1.864     albertel 8921:     
                   8922:     sub reset_hosts_ip_info {
                   8923: 	undef(%iphost);
                   8924: 	undef(%name_to_ip);
                   8925: 	undef(%lonid_to_ip);
                   8926:     }
1.856     albertel 8927: 
                   8928:     sub get_host_ip {
                   8929: 	my ($lonid) = @_;
                   8930: 	if (exists($lonid_to_ip{$lonid})) {
                   8931: 	    return $lonid_to_ip{$lonid};
                   8932: 	}
                   8933: 	my $name=&hostname($lonid);
                   8934:    	my $ip = gethostbyname($name);
                   8935: 	return if (!$ip || length($ip) ne 4);
                   8936: 	$ip=inet_ntoa($ip);
                   8937: 	$name_to_ip{$name}   = $ip;
                   8938: 	$lonid_to_ip{$lonid} = $ip;
                   8939: 	return $ip;
                   8940:     }
1.847     albertel 8941:     
                   8942:     sub get_iphost {
1.869     albertel 8943: 	my ($ignore_cache) = @_;
1.894     albertel 8944: 
1.869     albertel 8945: 	if (!$ignore_cache) {
                   8946: 	    if (%iphost) {
                   8947: 		return %iphost;
                   8948: 	    }
                   8949: 	    my ($ip_info,$cached)=
                   8950: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8951: 	    if ($cached) {
                   8952: 		%iphost      = %{$ip_info->[0]};
                   8953: 		%name_to_ip  = %{$ip_info->[1]};
                   8954: 		%lonid_to_ip = %{$ip_info->[2]};
                   8955: 		return %iphost;
                   8956: 	    }
                   8957: 	}
1.894     albertel 8958: 
                   8959: 	# get yesterday's info for fallback
                   8960: 	my %old_name_to_ip;
                   8961: 	my ($ip_info,$cached)=
                   8962: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8963: 	if ($cached) {
                   8964: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8965: 	}
                   8966: 
1.888     albertel 8967: 	my %name_to_host = &all_names();
                   8968: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8969: 	    my $ip;
                   8970: 	    if (!exists($name_to_ip{$name})) {
                   8971: 		$ip = gethostbyname($name);
                   8972: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8973: 		    if (defined($old_name_to_ip{$name})) {
                   8974: 			$ip = $old_name_to_ip{$name};
                   8975: 			&logthis("Can't find $name defaulting to old $ip");
                   8976: 		    } else {
                   8977: 			&logthis("Name $name no IP found");
                   8978: 			next;
                   8979: 		    }
                   8980: 		} else {
                   8981: 		    $ip=inet_ntoa($ip);
1.847     albertel 8982: 		}
                   8983: 		$name_to_ip{$name} = $ip;
                   8984: 	    } else {
                   8985: 		$ip = $name_to_ip{$name};
1.653     albertel 8986: 	    }
1.888     albertel 8987: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8988: 		$lonid_to_ip{$id} = $ip;
                   8989: 	    }
                   8990: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8991: 	}
1.869     albertel 8992: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8993: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8994: 				      48*60*60);
1.869     albertel 8995: 
1.847     albertel 8996: 	return %iphost;
1.598     albertel 8997:     }
                   8998: }
                   8999: 
1.862     albertel 9000: BEGIN {
                   9001: 
                   9002: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   9003:     unless ($readit) {
                   9004: {
                   9005:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   9006:     %perlvar = (%perlvar,%{$configvars});
                   9007: }
                   9008: 
                   9009: 
1.1       albertel 9010: # ------------------------------------------------------ Read spare server file
                   9011: {
1.448     albertel 9012:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 9013: 
                   9014:     while (my $configline=<$config>) {
                   9015:        chomp($configline);
1.284     matthew  9016:        if ($configline) {
1.784     albertel 9017: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 9018: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 9019: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 9020:        }
                   9021:     }
1.448     albertel 9022:     close($config);
1.1       albertel 9023: }
1.11      www      9024: # ------------------------------------------------------------ Read permissions
                   9025: {
1.448     albertel 9026:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      9027: 
                   9028:     while (my $configline=<$config>) {
1.448     albertel 9029: 	chomp($configline);
                   9030: 	if ($configline) {
                   9031: 	    my ($role,$perm)=split(/ /,$configline);
                   9032: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   9033: 	}
1.11      www      9034:     }
1.448     albertel 9035:     close($config);
1.11      www      9036: }
                   9037: 
                   9038: # -------------------------------------------- Read plain texts for permissions
                   9039: {
1.448     albertel 9040:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      9041: 
                   9042:     while (my $configline=<$config>) {
1.448     albertel 9043: 	chomp($configline);
                   9044: 	if ($configline) {
1.742     raeburn  9045: 	    my ($short,@plain)=split(/:/,$configline);
                   9046:             %{$prp{$short}} = ();
                   9047: 	    if (@plain > 0) {
                   9048:                 $prp{$short}{'std'} = $plain[0];
                   9049:                 for (my $i=1; $i<@plain; $i++) {
                   9050:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   9051:                 }
                   9052:             }
1.448     albertel 9053: 	}
1.135     www      9054:     }
1.448     albertel 9055:     close($config);
1.135     www      9056: }
                   9057: 
                   9058: # ---------------------------------------------------------- Read package table
                   9059: {
1.448     albertel 9060:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      9061: 
                   9062:     while (my $configline=<$config>) {
1.483     albertel 9063: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 9064: 	chomp($configline);
                   9065: 	my ($short,$plain)=split(/:/,$configline);
                   9066: 	my ($pack,$name)=split(/\&/,$short);
                   9067: 	if ($plain ne '') {
                   9068: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   9069: 	    $packagetab{$short}=$plain; 
                   9070: 	}
1.11      www      9071:     }
1.448     albertel 9072:     close($config);
1.329     matthew  9073: }
                   9074: 
                   9075: # ------------- set up temporary directory
                   9076: {
                   9077:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   9078: 
1.11      www      9079: }
                   9080: 
1.794     albertel 9081: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   9082: 				'compress_threshold'=> 20_000,
                   9083:  			        });
1.185     www      9084: 
1.281     www      9085: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      9086: $dumpcount=0;
1.958     www      9087: $locknum=0;
1.22      www      9088: 
1.163     harris41 9089: &logtouch();
1.672     albertel 9090: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      9091: $readit=1;
1.564     albertel 9092:     {
                   9093: 	use integer;
                   9094: 	my $test=(2**32)+1;
1.568     albertel 9095: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 9096: 	&logthis(" Detected 64bit platform ($_64bit)");
                   9097:     }
1.195     www      9098: }
1.1       albertel 9099: }
1.179     www      9100: 
1.1       albertel 9101: 1;
1.191     harris41 9102: __END__
                   9103: 
1.243     albertel 9104: =pod
                   9105: 
1.191     harris41 9106: =head1 NAME
                   9107: 
1.243     albertel 9108: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 9109: 
                   9110: =head1 SYNOPSIS
                   9111: 
1.243     albertel 9112: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 9113: 
                   9114:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   9115: 
1.243     albertel 9116: Common parameters:
                   9117: 
                   9118: =over 4
                   9119: 
                   9120: =item *
                   9121: 
                   9122: $uname : an internal username (if $cname expecting a course Id specifically)
                   9123: 
                   9124: =item *
                   9125: 
                   9126: $udom : a domain (if $cdom expecting a course's domain specifically)
                   9127: 
                   9128: =item *
                   9129: 
                   9130: $symb : a resource instance identifier
                   9131: 
                   9132: =item *
                   9133: 
                   9134: $namespace : the name of a .db file that contains the data needed or
                   9135: being set.
                   9136: 
                   9137: =back
                   9138: 
1.394     bowersj2 9139: =head1 OVERVIEW
1.191     harris41 9140: 
1.394     bowersj2 9141: lonnet provides subroutines which interact with the
                   9142: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   9143: about classes, users, and resources.
1.243     albertel 9144: 
                   9145: For many of these objects you can also use this to store data about
                   9146: them or modify them in various ways.
1.191     harris41 9147: 
1.394     bowersj2 9148: =head2 Symbs
1.191     harris41 9149: 
1.394     bowersj2 9150: To identify a specific instance of a resource, LON-CAPA uses symbols
                   9151: or "symbs"X<symb>. These identifiers are built from the URL of the
                   9152: map, the resource number of the resource in the map, and the URL of
                   9153: the resource itself. The latter is somewhat redundant, but might help
                   9154: if maps change.
                   9155: 
                   9156: An example is
                   9157: 
                   9158:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   9159: 
                   9160: The respective map entry is
                   9161: 
                   9162:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   9163:   title="Problem 2">
                   9164:  </resource>
                   9165: 
                   9166: Symbs are used by the random number generator, as well as to store and
                   9167: restore data specific to a certain instance of for example a problem.
                   9168: 
                   9169: =head2 Storing And Retrieving Data
                   9170: 
                   9171: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   9172: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   9173: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   9174: is is the non-critical message twin of cstore. These functions are for
                   9175: handlers to store a perl hash to a user's permanent data space in an
                   9176: easy manner, and to retrieve it again on another call. It is expected
                   9177: that a handler would use this once at the beginning to retrieve data,
                   9178: and then again once at the end to send only the new data back.
                   9179: 
                   9180: The data is stored in the user's data directory on the user's
                   9181: homeserver under the ID of the course.
                   9182: 
                   9183: The hash that is returned by restore will have all of the previous
                   9184: value for all of the elements of the hash.
                   9185: 
                   9186: Example:
                   9187: 
                   9188:  #creating a hash
                   9189:  my %hash;
                   9190:  $hash{'foo'}='bar';
                   9191: 
                   9192:  #storing it
                   9193:  &Apache::lonnet::cstore(\%hash);
                   9194: 
                   9195:  #changing a value
                   9196:  $hash{'foo'}='notbar';
                   9197: 
                   9198:  #adding a new value
                   9199:  $hash{'bar'}='foo';
                   9200:  &Apache::lonnet::cstore(\%hash);
                   9201: 
                   9202:  #retrieving the hash
                   9203:  my %history=&Apache::lonnet::restore();
                   9204: 
                   9205:  #print the hash
                   9206:  foreach my $key (sort(keys(%history))) {
                   9207:    print("\%history{$key} = $history{$key}");
                   9208:  }
                   9209: 
                   9210: Will print out:
1.191     harris41 9211: 
1.394     bowersj2 9212:  %history{1:foo} = bar
                   9213:  %history{1:keys} = foo:timestamp
                   9214:  %history{1:timestamp} = 990455579
                   9215:  %history{2:bar} = foo
                   9216:  %history{2:foo} = notbar
                   9217:  %history{2:keys} = foo:bar:timestamp
                   9218:  %history{2:timestamp} = 990455580
                   9219:  %history{bar} = foo
                   9220:  %history{foo} = notbar
                   9221:  %history{timestamp} = 990455580
                   9222:  %history{version} = 2
                   9223: 
                   9224: Note that the special hash entries C<keys>, C<version> and
                   9225: C<timestamp> were added to the hash. C<version> will be equal to the
                   9226: total number of versions of the data that have been stored. The
                   9227: C<timestamp> attribute will be the UNIX time the hash was
                   9228: stored. C<keys> is available in every historical section to list which
                   9229: keys were added or changed at a specific historical revision of a
                   9230: hash.
                   9231: 
                   9232: B<Warning>: do not store the hash that restore returns directly. This
                   9233: will cause a mess since it will restore the historical keys as if the
                   9234: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 9235: 
1.394     bowersj2 9236: Calling convention:
1.191     harris41 9237: 
1.394     bowersj2 9238:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   9239:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 9240: 
1.394     bowersj2 9241: For more detailed information, see lonnet specific documentation.
1.191     harris41 9242: 
1.394     bowersj2 9243: =head1 RETURN MESSAGES
1.191     harris41 9244: 
1.394     bowersj2 9245: =over 4
1.191     harris41 9246: 
1.394     bowersj2 9247: =item * B<con_lost>: unable to contact remote host
1.191     harris41 9248: 
1.394     bowersj2 9249: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   9250: when the connection is brought back up
1.191     harris41 9251: 
1.394     bowersj2 9252: =item * B<con_failed>: unable to contact remote host and unable to save message
                   9253: for later delivery
1.191     harris41 9254: 
1.967     bisitz   9255: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 9256: 
1.394     bowersj2 9257: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 9258: that was requested
1.191     harris41 9259: 
1.243     albertel 9260: =back
1.191     harris41 9261: 
1.243     albertel 9262: =head1 PUBLIC SUBROUTINES
1.191     harris41 9263: 
1.243     albertel 9264: =head2 Session Environment Functions
1.191     harris41 9265: 
1.243     albertel 9266: =over 4
1.191     harris41 9267: 
1.394     bowersj2 9268: =item * 
                   9269: X<appenv()>
1.949     raeburn  9270: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 9271: the user envirnoment file, and will be restored for each access this
1.620     albertel 9272: user makes during this session, also modifies the %env for the current
1.949     raeburn  9273: process. Optional rolesarrayref - if defined contains a reference to an array
                   9274: of roles which are exempt from the restriction on modifying user.role entries 
                   9275: in the user's environment.db and in %env.    
1.191     harris41 9276: 
                   9277: =item *
1.394     bowersj2 9278: X<delenv()>
1.976.2.7  raeburn  9279: B<delenv($delthis,$regexp)>: removes all items from the session
                   9280: environment file that begin with $delthis. If the
                   9281: optional second arg - $regexp - is true, $delthis is treated as a
                   9282: regular expression, otherwise \Q$delthis\E is used.
                   9283: The values are also deleted from the current processes %env.
1.191     harris41 9284: 
1.795     albertel 9285: =item * get_env_multiple($name) 
                   9286: 
                   9287: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   9288: values may be defined and end up as an array ref.
                   9289: 
                   9290: returns an array of values
                   9291: 
1.243     albertel 9292: =back
                   9293: 
                   9294: =head2 User Information
1.191     harris41 9295: 
1.243     albertel 9296: =over 4
1.191     harris41 9297: 
                   9298: =item *
1.394     bowersj2 9299: X<queryauthenticate()>
                   9300: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 9301: authentication scheme
                   9302: 
                   9303: =item *
1.394     bowersj2 9304: X<authenticate()>
                   9305: B<authenticate($uname,$upass,$udom)>: try to
                   9306: authenticate user from domain's lib servers (first use the current
                   9307: one). C<$upass> should be the users password.
1.191     harris41 9308: 
                   9309: =item *
1.394     bowersj2 9310: X<homeserver()>
                   9311: B<homeserver($uname,$udom)>: find the server which has
                   9312: the user's directory and files (there must be only one), this caches
                   9313: the answer, and also caches if there is a borken connection.
1.191     harris41 9314: 
                   9315: =item *
1.394     bowersj2 9316: X<idget()>
                   9317: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   9318: (IDs are a unique resource in a domain, there must be only 1 ID per
                   9319: username, and only 1 username per ID in a specific domain) (returns
                   9320: hash: id=>name,id=>name)
1.191     harris41 9321: 
                   9322: =item *
1.394     bowersj2 9323: X<idrget()>
                   9324: B<idrget($udom,@unames)>: find the IDs behind a list of
                   9325: usernames (returns hash: name=>id,name=>id)
1.191     harris41 9326: 
                   9327: =item *
1.394     bowersj2 9328: X<idput()>
                   9329: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 9330: 
                   9331: =item *
1.394     bowersj2 9332: X<rolesinit()>
                   9333: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 9334: 
                   9335: =item *
1.551     albertel 9336: X<getsection()>
                   9337: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 9338: course $cname, return section name/number or '' for "not in course"
                   9339: and '-1' for "no section"
                   9340: 
                   9341: =item *
1.394     bowersj2 9342: X<userenvironment()>
                   9343: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 9344: passed in @what from the requested user's environment, returns a hash
                   9345: 
1.858     raeburn  9346: =item * 
                   9347: X<userlog_query()>
1.859     albertel 9348: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   9349: activity.log file. %filters defines filters applied when parsing the
                   9350: log file. These can be start or end timestamps, or the type of action
                   9351: - log to look for Login or Logout events, check for Checkin or
                   9352: Checkout, role for role selection. The response is in the form
                   9353: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   9354: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  9355: 
1.243     albertel 9356: =back
                   9357: 
                   9358: =head2 User Roles
                   9359: 
                   9360: =over 4
                   9361: 
                   9362: =item *
                   9363: 
1.810     raeburn  9364: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 9365:  F: full access
                   9366:  U,I,K: authentication modes (cxx only)
                   9367:  '': forbidden
                   9368:  1: user needs to choose course
                   9369:  2: browse allowed
1.766     albertel 9370:  A: passphrase authentication needed
1.243     albertel 9371: 
                   9372: =item *
                   9373: 
                   9374: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   9375: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   9376: and course level
                   9377: 
                   9378: =item *
                   9379: 
                   9380: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   9381: explanation of a user role term
                   9382: 
1.832     raeburn  9383: =item *
                   9384: 
1.935     raeburn  9385: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  9386: All arguments are optional. Returns a hash of a roles, either for
                   9387: co-author/assistant author roles for a user's Construction Space
1.906     albertel 9388: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  9389: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   9390: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   9391: For each key, value is set to colon-separated start and end times for
                   9392: the role.  If no username and domain are specified, will default to
1.934     raeburn  9393: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  9394: of role statuses (active, future or previous), roles 
                   9395: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   9396: to restrict the list of roles reported. If no array ref is 
                   9397: provided for types, will default to return only active roles.
1.834     albertel 9398: 
1.243     albertel 9399: =back
                   9400: 
                   9401: =head2 User Modification
                   9402: 
                   9403: =over 4
                   9404: 
                   9405: =item *
                   9406: 
1.957     raeburn  9407: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 9408: user for the level given by URL.  Optional start and end dates (leave empty
                   9409: string or zero for "no date")
1.191     harris41 9410: 
                   9411: =item *
                   9412: 
1.243     albertel 9413: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   9414: change a users, password, possible return values are: ok,
                   9415: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   9416: refused
1.191     harris41 9417: 
                   9418: =item *
                   9419: 
1.243     albertel 9420: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9421: 
                   9422: =item *
                   9423: 
1.963     raeburn  9424: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
                   9425:            $forceid,$desiredhome,$email,$inststatus) : 
1.243     albertel 9426: modify user
1.191     harris41 9427: 
                   9428: =item *
                   9429: 
1.286     matthew  9430: modifystudent
                   9431: 
1.957     raeburn  9432: modify a student's enrollment and identification information.
1.286     matthew  9433: The course id is resolved based on the current users environment.  
                   9434: This means the envoking user must be a course coordinator or otherwise
                   9435: associated with a course.
                   9436: 
1.297     matthew  9437: This call is essentially a wrapper for lonnet::modifyuser and
                   9438: lonnet::modify_student_enrollment
1.286     matthew  9439: 
                   9440: Inputs: 
                   9441: 
                   9442: =over 4
                   9443: 
1.957     raeburn  9444: =item B<$udom> Student's loncapa domain
1.286     matthew  9445: 
1.957     raeburn  9446: =item B<$uname> Student's loncapa login name
1.286     matthew  9447: 
1.964     bisitz   9448: =item B<$uid> Student/Employee ID
1.286     matthew  9449: 
1.957     raeburn  9450: =item B<$umode> Student's authentication mode
1.286     matthew  9451: 
1.957     raeburn  9452: =item B<$upass> Student's password
1.286     matthew  9453: 
1.957     raeburn  9454: =item B<$first> Student's first name
1.286     matthew  9455: 
1.957     raeburn  9456: =item B<$middle> Student's middle name
1.286     matthew  9457: 
1.957     raeburn  9458: =item B<$last> Student's last name
1.286     matthew  9459: 
1.957     raeburn  9460: =item B<$gene> Student's generation
1.286     matthew  9461: 
1.957     raeburn  9462: =item B<$usec> Student's section in course
1.286     matthew  9463: 
                   9464: =item B<$end> Unix time of the roles expiration
                   9465: 
                   9466: =item B<$start> Unix time of the roles start date
                   9467: 
                   9468: =item B<$forceid> If defined, allow $uid to be changed
                   9469: 
                   9470: =item B<$desiredhome> server to use as home server for student
                   9471: 
1.957     raeburn  9472: =item B<$email> Student's permanent e-mail address
                   9473: 
                   9474: =item B<$type> Type of enrollment (auto or manual)
                   9475: 
1.963     raeburn  9476: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   9477: 
                   9478: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  9479: 
1.963     raeburn  9480: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  9481: 
1.963     raeburn  9482: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  9483: 
1.963     raeburn  9484: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  9485: 
1.286     matthew  9486: =back
1.297     matthew  9487: 
                   9488: =item *
                   9489: 
                   9490: modify_student_enrollment
                   9491: 
                   9492: Change a students enrollment status in a class.  The environment variable
                   9493: 'role.request.course' must be defined for this function to proceed.
                   9494: 
                   9495: Inputs:
                   9496: 
                   9497: =over 4
                   9498: 
                   9499: =item $udom, students domain
                   9500: 
                   9501: =item $uname, students name
                   9502: 
                   9503: =item $uid, students user id
                   9504: 
                   9505: =item $first, students first name
                   9506: 
                   9507: =item $middle
                   9508: 
                   9509: =item $last
                   9510: 
                   9511: =item $gene
                   9512: 
                   9513: =item $usec
                   9514: 
                   9515: =item $end
                   9516: 
                   9517: =item $start
                   9518: 
1.957     raeburn  9519: =item $type
                   9520: 
                   9521: =item $locktype
                   9522: 
                   9523: =item $cid
                   9524: 
                   9525: =item $selfenroll
                   9526: 
                   9527: =item $context
                   9528: 
1.297     matthew  9529: =back
                   9530: 
1.191     harris41 9531: 
                   9532: =item *
                   9533: 
1.243     albertel 9534: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9535: custom role; give a custom role to a user for the level given by URL.  Specify
                   9536: name and domain of role author, and role name
1.191     harris41 9537: 
                   9538: =item *
                   9539: 
1.243     albertel 9540: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9541: 
                   9542: =item *
                   9543: 
1.243     albertel 9544: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9545: 
                   9546: =back
                   9547: 
                   9548: =head2 Course Infomation
                   9549: 
                   9550: =over 4
1.191     harris41 9551: 
                   9552: =item *
                   9553: 
1.631     albertel 9554: coursedescription($courseid) : returns a hash of information about the
                   9555: specified course id, including all environment settings for the
                   9556: course, the description of the course will be in the hash under the
                   9557: key 'description'
1.191     harris41 9558: 
                   9559: =item *
                   9560: 
1.624     albertel 9561: resdata($name,$domain,$type,@which) : request for current parameter
                   9562: setting for a specific $type, where $type is either 'course' or 'user',
                   9563: @what should be a list of parameters to ask about. This routine caches
                   9564: answers for 5 minutes.
1.243     albertel 9565: 
1.877     foxr     9566: =item *
                   9567: 
                   9568: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9569: data base, returning a hash that is keyed by the resource name and has
                   9570: values that are the resource value.  I believe that the timestamps and
                   9571: versions are also returned.
                   9572: 
                   9573: 
1.243     albertel 9574: =back
                   9575: 
                   9576: =head2 Course Modification
                   9577: 
                   9578: =over 4
1.191     harris41 9579: 
                   9580: =item *
                   9581: 
1.243     albertel 9582: writecoursepref($courseid,%prefs) : write preferences (environment
                   9583: database) for a course
1.191     harris41 9584: 
                   9585: =item *
                   9586: 
1.243     albertel 9587: createcourse($udom,$description,$url) : make/modify course
                   9588: 
                   9589: =back
                   9590: 
                   9591: =head2 Resource Subroutines
                   9592: 
                   9593: =over 4
1.191     harris41 9594: 
                   9595: =item *
                   9596: 
1.243     albertel 9597: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9598: 
                   9599: =item *
                   9600: 
1.243     albertel 9601: repcopy($filename) : subscribes to the requested file, and attempts to
                   9602: replicate from the owning library server, Might return
1.607     raeburn  9603: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9604: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9605: resource. Expects the local filesystem pathname
                   9606: (/home/httpd/html/res/....)
                   9607: 
                   9608: =back
                   9609: 
                   9610: =head2 Resource Information
                   9611: 
                   9612: =over 4
1.191     harris41 9613: 
                   9614: =item *
                   9615: 
1.243     albertel 9616: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9617: a vairety of different possible values, $varname should be a request
                   9618: string, and the other parameters can be used to specify who and what
                   9619: one is asking about.
                   9620: 
                   9621: Possible values for $varname are environment.lastname (or other item
                   9622: from the envirnment hash), user.name (or someother aspect about the
                   9623: user), resource.0.maxtries (or some other part and parameter of a
                   9624: resource)
1.204     albertel 9625: 
                   9626: =item *
                   9627: 
1.243     albertel 9628: directcondval($number) : get current value of a condition; reads from a state
                   9629: string
1.204     albertel 9630: 
                   9631: =item *
                   9632: 
1.243     albertel 9633: condval($condidx) : value of condition index based on state
1.204     albertel 9634: 
                   9635: =item *
                   9636: 
1.243     albertel 9637: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9638: resource's metadata, $what should be either a specific key, or either
                   9639: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9640: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9641: 
                   9642: this function automatically caches all requests
1.191     harris41 9643: 
                   9644: =item *
                   9645: 
1.243     albertel 9646: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9647: network of library servers; returns file handle of where SQL and regex results
                   9648: will be stored for query
1.191     harris41 9649: 
                   9650: =item *
                   9651: 
1.243     albertel 9652: symbread($filename) : return symbolic list entry (filename argument optional);
                   9653: returns the data handle
1.191     harris41 9654: 
                   9655: =item *
                   9656: 
1.243     albertel 9657: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9658: a possible symb for the URL in $thisfn, and if is an encryypted
                   9659: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9660: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9661: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9662: 
1.191     harris41 9663: 
                   9664: =item *
                   9665: 
1.243     albertel 9666: symbclean($symb) : removes versions numbers from a symb, returns the
                   9667: cleaned symb
1.191     harris41 9668: 
                   9669: =item *
                   9670: 
1.243     albertel 9671: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9672: course map, user must be in a course for it to work.
1.191     harris41 9673: 
                   9674: =item *
                   9675: 
1.243     albertel 9676: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9677: 
                   9678: =item *
                   9679: 
1.243     albertel 9680: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9681: a random seed, all arguments are optional, if they aren't sent it uses the
                   9682: environment to derive them. Note: if symb isn't sent and it can't get one
                   9683: from &symbread it will use the current time as its return value
1.191     harris41 9684: 
                   9685: =item *
                   9686: 
1.243     albertel 9687: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9688: unfakeable, receipt
1.191     harris41 9689: 
                   9690: =item *
                   9691: 
1.620     albertel 9692: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9693: 
                   9694: =item *
                   9695: 
1.243     albertel 9696: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9697: 
                   9698: =item *
                   9699: 
1.243     albertel 9700: 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 9701: 
                   9702: =item *
                   9703: 
1.243     albertel 9704: 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 9705: 
                   9706: =item *
                   9707: 
1.243     albertel 9708: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9709: 
                   9710: =item *
                   9711: 
1.243     albertel 9712: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9713: forcing spreadsheet to reevaluate the resource scores next time.
                   9714: 
                   9715: =back
                   9716: 
                   9717: =head2 Storing/Retreiving Data
                   9718: 
                   9719: =over 4
1.191     harris41 9720: 
                   9721: =item *
                   9722: 
1.243     albertel 9723: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9724: for this url; hashref needs to be given and should be a \%hashname; the
                   9725: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9726: be derived from the env
1.191     harris41 9727: 
                   9728: =item *
                   9729: 
1.243     albertel 9730: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9731: uses critical subroutine
1.191     harris41 9732: 
                   9733: =item *
                   9734: 
1.243     albertel 9735: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9736: all args are optional
1.191     harris41 9737: 
                   9738: =item *
                   9739: 
1.717     albertel 9740: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9741: dumps the complete (or key matching regexp) namespace into a hash
                   9742: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9743: normally &store()ed into
                   9744: 
                   9745: $range should be either an integer '100' (give me the first 100
                   9746:                                            matching records)
                   9747:               or be  two integers sperated by a - with no spaces
                   9748:                  '30-50' (give me the 30th through the 50th matching
                   9749:                           records)
                   9750: 
                   9751: 
                   9752: =item *
                   9753: 
                   9754: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9755: replaces a &store() version of data with a replacement set of data
                   9756: for a particular resource in a namespace passed in the $storehash hash 
                   9757: reference
                   9758: 
                   9759: =item *
                   9760: 
1.243     albertel 9761: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9762: works very similar to store/cstore, but all data is stored in a
                   9763: temporary location and can be reset using tmpreset, $storehash should
                   9764: be a hash reference, returns nothing on success
1.191     harris41 9765: 
                   9766: =item *
                   9767: 
1.243     albertel 9768: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9769: similar to restore, but all data is stored in a temporary location and
                   9770: can be reset using tmpreset. Returns a hash of values on success,
                   9771: error string otherwise.
1.191     harris41 9772: 
                   9773: =item *
                   9774: 
1.243     albertel 9775: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9776: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9777: 
                   9778: =item *
                   9779: 
1.243     albertel 9780: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9781: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9782: 
                   9783: =item *
                   9784: 
1.243     albertel 9785: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9786: namesp ($udom and $uname are optional)
1.191     harris41 9787: 
                   9788: =item *
                   9789: 
1.702     albertel 9790: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9791: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9792: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9793: 
1.702     albertel 9794: $range should be either an integer '100' (give me the first 100
                   9795:                                            matching records)
                   9796:               or be  two integers sperated by a - with no spaces
                   9797:                  '30-50' (give me the 30th through the 50th matching
                   9798:                           records)
1.449     matthew  9799: =item *
                   9800: 
                   9801: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9802: $store can be a scalar, an array reference, or if the amount to be 
                   9803: incremented is > 1, a hash reference.
                   9804: 
                   9805: ($udom and $uname are optional)
1.191     harris41 9806: 
                   9807: =item *
                   9808: 
1.243     albertel 9809: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9810: ($udom and $uname are optional)
1.191     harris41 9811: 
                   9812: =item *
                   9813: 
1.243     albertel 9814: cput($namespace,$storehash,$udom,$uname) : critical put
                   9815: ($udom and $uname are optional)
1.191     harris41 9816: 
                   9817: =item *
                   9818: 
1.748     albertel 9819: newput($namespace,$storehash,$udom,$uname) :
                   9820: 
                   9821: Attempts to store the items in the $storehash, but only if they don't
                   9822: currently exist, if this succeeds you can be certain that you have 
                   9823: successfully created a new key value pair in the $namespace db.
                   9824: 
                   9825: 
                   9826: Args:
                   9827:  $namespace: name of database to store values to
                   9828:  $storehash: hashref to store to the db
                   9829:  $udom: (optional) domain of user containing the db
                   9830:  $uname: (optional) name of user caontaining the db
                   9831: 
                   9832: Returns:
                   9833:  'ok' -> succeeded in storing all keys of $storehash
                   9834:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9835:                         least <key> already existed in the db (other
                   9836:                         requested keys may also already exist)
1.967     bisitz   9837:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 9838:  'con_lost' -> unable to contact request server
                   9839:  'refused' -> action was not allowed by remote machine
                   9840: 
                   9841: 
                   9842: =item *
                   9843: 
1.243     albertel 9844: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9845: reference filled in from namesp (encrypts the return communication)
                   9846: ($udom and $uname are optional)
1.191     harris41 9847: 
                   9848: =item *
                   9849: 
1.243     albertel 9850: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9851: critical subroutine
                   9852: 
1.806     raeburn  9853: =item *
                   9854: 
1.860     raeburn  9855: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9856: array reference filled in from namespace found in domain level on either
                   9857: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9858: 
                   9859: =item *
                   9860: 
1.860     raeburn  9861: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9862: domain level either on specified domain server ($uhome) or primary domain 
                   9863: server ($udom and $uhome are optional)
1.806     raeburn  9864: 
1.943     raeburn  9865: =item * 
                   9866: 
                   9867: get_domain_defaults($target_domain) : returns hash with defaults for
                   9868: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   9869: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   9870: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   9871: Values are retrieved from cache (if current), or from domain's configuration.db
                   9872: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   9873: or lonTabs/domain.tab. 
                   9874: 
                   9875: %domdefaults = &get_auth_defaults($target_domain);
                   9876: 
1.243     albertel 9877: =back
                   9878: 
                   9879: =head2 Network Status Functions
                   9880: 
                   9881: =over 4
1.191     harris41 9882: 
                   9883: =item *
                   9884: 
                   9885: dirlist($uri) : return directory list based on URI
                   9886: 
                   9887: =item *
                   9888: 
1.243     albertel 9889: spareserver() : find server with least workload from spare.tab
                   9890: 
                   9891: =back
                   9892: 
                   9893: =head2 Apache Request
                   9894: 
                   9895: =over 4
1.191     harris41 9896: 
                   9897: =item *
                   9898: 
1.243     albertel 9899: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9900: localhost, posts hash
                   9901: 
                   9902: =back
                   9903: 
                   9904: =head2 Data to String to Data
                   9905: 
                   9906: =over 4
1.191     harris41 9907: 
                   9908: =item *
                   9909: 
1.243     albertel 9910: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9911: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9912: 
                   9913: =item *
                   9914: 
1.243     albertel 9915: hashref2str($hashref) : convert a hashref into a string complete with
                   9916: escaping and '=' and '&' separators, supports elements that are
                   9917: arrayrefs and hashrefs
1.191     harris41 9918: 
                   9919: =item *
                   9920: 
1.243     albertel 9921: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9922: with escaping and '&' separators, supports elements that are arrayrefs
                   9923: and hashrefs
1.191     harris41 9924: 
                   9925: =item *
                   9926: 
1.243     albertel 9927: str2hash($string) : convert string to hash using unescaping and
                   9928: splitting on '=' and '&', supports elements that are arrayrefs and
                   9929: hashrefs
1.191     harris41 9930: 
                   9931: =item *
                   9932: 
1.243     albertel 9933: str2array($string) : convert string to hash using unescaping and
                   9934: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9935: 
                   9936: =back
                   9937: 
                   9938: =head2 Logging Routines
                   9939: 
                   9940: =over 4
                   9941: 
                   9942: These routines allow one to make log messages in the lonnet.log and
                   9943: lonnet.perm logfiles.
1.191     harris41 9944: 
                   9945: =item *
                   9946: 
1.243     albertel 9947: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9948: 
                   9949: =item *
                   9950: 
1.243     albertel 9951: logthis() : append message to the normal lonnet.log file, it gets
                   9952: preiodically rolled over and deleted.
1.191     harris41 9953: 
                   9954: =item *
                   9955: 
1.243     albertel 9956: logperm() : append a permanent message to lonnet.perm.log, this log
                   9957: file never gets deleted by any automated portion of the system, only
                   9958: messages of critical importance should go in here.
                   9959: 
                   9960: =back
                   9961: 
                   9962: =head2 General File Helper Routines
                   9963: 
                   9964: =over 4
1.191     harris41 9965: 
                   9966: =item *
                   9967: 
1.481     raeburn  9968: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9969: (a) files in /uploaded
                   9970:   (i) If a local copy of the file exists - 
                   9971:       compares modification date of local copy with last-modified date for 
                   9972:       definitive version stored on home server for course. If local copy is 
                   9973:       stale, requests a new version from the home server and stores it. 
                   9974:       If the original has been removed from the home server, then local copy 
                   9975:       is unlinked.
                   9976:   (ii) If local copy does not exist -
                   9977:       requests the file from the home server and stores it. 
                   9978:   
                   9979:   If $caller is 'uploadrep':  
                   9980:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9981:     for request for files originally uploaded via DOCS. 
                   9982:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9983:   
                   9984:   Otherwise:
                   9985:      This indicates a call from the content generation phase of the request.
                   9986:      -  returns the entire contents of the file or -1.
                   9987:      
                   9988: (b) files in /res
                   9989:    - returns the entire contents of a file or -1; 
                   9990:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9991: 
1.712     albertel 9992: 
                   9993: =item *
                   9994: 
                   9995: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9996:                   reference
                   9997: 
                   9998: returns either a stat() list of data about the file or an empty list
                   9999: if the file doesn't exist or couldn't find out about it (connection
                   10000: problems or user unknown)
                   10001: 
1.191     harris41 10002: =item *
                   10003: 
1.243     albertel 10004: filelocation($dir,$file) : returns file system location of a file
                   10005: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   10006: directory that relative $file lookups are to looked in ($dir of /a/dir
                   10007: and a file of ../bob will become /a/bob)
1.191     harris41 10008: 
                   10009: =item *
                   10010: 
                   10011: hreflocation($dir,$file) : returns file system location or a URL; same as
                   10012: filelocation except for hrefs
                   10013: 
                   10014: =item *
                   10015: 
                   10016: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   10017: 
1.243     albertel 10018: =back
                   10019: 
1.608     albertel 10020: =head2 Usererfile file routines (/uploaded*)
                   10021: 
                   10022: =over 4
                   10023: 
                   10024: =item *
                   10025: 
                   10026: userfileupload(): main rotine for putting a file in a user or course's
                   10027:                   filespace, arguments are,
                   10028: 
1.620     albertel 10029:  formname - required - this is the name of the element in $env where the
1.608     albertel 10030:            filename, and the contents of the file to create/modifed exist
1.620     albertel 10031:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   10032:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 10033:  coursedoc - if true, store the file in the course of the active role
                   10034:              of the current user
                   10035:  subdir - required - subdirectory to put the file in under ../userfiles/
                   10036:          if undefined, it will be placed in "unknown"
                   10037: 
                   10038:  (This routine calls clean_filename() to remove any dangerous
                   10039:  characters from the filename, and then calls finuserfileupload() to
                   10040:  complete the transaction)
                   10041: 
                   10042:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10043:  and /adm/notfound.html if unsuccessful
                   10044: 
                   10045: =item *
                   10046: 
                   10047: clean_filename(): routine for cleaing a filename up for storage in
                   10048:                  userfile space, argument is:
                   10049: 
                   10050:  filename - proposed filename
                   10051: 
                   10052: returns: the new clean filename
                   10053: 
                   10054: =item *
                   10055: 
                   10056: finishuserfileupload(): routine that creaes and sends the file to
                   10057: userspace, probably shouldn't be called directly
                   10058: 
                   10059:   docuname: username or courseid of destination for the file
                   10060:   docudom: domain of user/course of destination for the file
                   10061:   formname: same as for userfileupload()
                   10062:   fname: filename (inculding subdirectories) for the file
                   10063: 
                   10064:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10065:  and /adm/notfound.html if unsuccessful
                   10066: 
                   10067: =item *
                   10068: 
                   10069: renameuserfile(): renames an existing userfile to a new name
                   10070: 
                   10071:   Args:
                   10072:    docuname: username or courseid of destination for the file
                   10073:    docudom: domain of user/course of destination for the file
                   10074:    old: current file name (including any subdirs under userfiles)
                   10075:    new: desired file name (including any subdirs under userfiles)
                   10076: 
                   10077: =item *
                   10078: 
                   10079: mkdiruserfile(): creates a directory is a userfiles dir
                   10080: 
                   10081:   Args:
                   10082:    docuname: username or courseid of destination for the file
                   10083:    docudom: domain of user/course of destination for the file
                   10084:    dir: dir to create (including any subdirs under userfiles)
                   10085: 
                   10086: =item *
                   10087: 
                   10088: removeuserfile(): removes a file that exists in userfiles
                   10089: 
                   10090:   Args:
                   10091:    docuname: username or courseid of destination for the file
                   10092:    docudom: domain of user/course of destination for the file
                   10093:    fname: filname to delete (including any subdirs under userfiles)
                   10094: 
                   10095: =item *
                   10096: 
                   10097: removeuploadedurl(): convience function for removeuserfile()
                   10098: 
                   10099:   Args:
                   10100:    url:  a full /uploaded/... url to delete
                   10101: 
1.747     albertel 10102: =item * 
                   10103: 
                   10104: get_portfile_permissions():
                   10105:   Args:
                   10106:     domain: domain of user or course contain the portfolio files
                   10107:     user: name of user or num of course contain the portfolio files
                   10108:   Returns:
                   10109:     hashref of a dump of the proper file_permissions.db
                   10110:    
                   10111: 
                   10112: =item * 
                   10113: 
                   10114: get_access_controls():
                   10115: 
                   10116: Args:
                   10117:   current_permissions: the hash ref returned from get_portfile_permissions()
                   10118:   group: (optional) the group you want the files associated with
                   10119:   file: (optional) the file you want access info on
                   10120: 
                   10121: Returns:
1.749     raeburn  10122:     a hash (keys are file names) of hashes containing
                   10123:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   10124:         values are XML containing access control settings (see below) 
1.747     albertel 10125: 
                   10126: Internal notes:
                   10127: 
1.749     raeburn  10128:  access controls are stored in file_permissions.db as key=value pairs.
                   10129:     key -> path to file/file_name\0uniqueID:scope_end_start
                   10130:         where scope -> public,guest,course,group,domains or users.
                   10131:               end -> UNIX time for end of access (0 -> no end date)
                   10132:               start -> UNIX time for start of access
                   10133: 
                   10134:     value -> XML description of access control
                   10135:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   10136:             <start></start>
                   10137:             <end></end>
                   10138: 
                   10139:             <password></password>  for scope type = guest
                   10140: 
                   10141:             <domain></domain>     for scope type = course or group
                   10142:             <number></number>
                   10143:             <roles id="">
                   10144:              <role></role>
                   10145:              <access></access>
                   10146:              <section></section>
                   10147:              <group></group>
                   10148:             </roles>
                   10149: 
                   10150:             <dom></dom>         for scope type = domains
                   10151: 
                   10152:             <users>             for scope type = users
                   10153:              <user>
                   10154:               <uname></uname>
                   10155:               <udom></udom>
                   10156:              </user>
                   10157:             </users>
                   10158:            </scope> 
                   10159:               
                   10160:  Access data is also aggregated for each file in an additional key=value pair:
                   10161:  key -> path to file/file_name\0accesscontrol 
                   10162:  value -> reference to hash
                   10163:           hash contains key = value pairs
                   10164:           where key = uniqueID:scope_end_start
                   10165:                 value = UNIX time record was last updated
                   10166: 
                   10167:           Used to improve speed of look-ups of access controls for each file.  
                   10168:  
                   10169:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   10170: 
                   10171: modify_access_controls():
                   10172: 
                   10173: Modifies access controls for a portfolio file
                   10174: Args
                   10175: 1. file name
                   10176: 2. reference to hash of required changes,
                   10177: 3. domain
                   10178: 4. username
                   10179:   where domain,username are the domain of the portfolio owner 
                   10180:   (either a user or a course) 
                   10181: 
                   10182: Returns:
                   10183: 1. result of additions or updates ('ok' or 'error', with error message). 
                   10184: 2. result of deletions ('ok' or 'error', with error message).
                   10185: 3. reference to hash of any new or updated access controls.
                   10186: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   10187:    key = integer (inbound ID)
                   10188:    value = uniqueID  
1.747     albertel 10189: 
1.608     albertel 10190: =back
                   10191: 
1.243     albertel 10192: =head2 HTTP Helper Routines
                   10193: 
                   10194: =over 4
                   10195: 
1.191     harris41 10196: =item *
                   10197: 
                   10198: escape() : unpack non-word characters into CGI-compatible hex codes
                   10199: 
                   10200: =item *
                   10201: 
                   10202: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   10203: 
1.243     albertel 10204: =back
                   10205: 
                   10206: =head1 PRIVATE SUBROUTINES
                   10207: 
                   10208: =head2 Underlying communication routines (Shouldn't call)
                   10209: 
                   10210: =over 4
                   10211: 
                   10212: =item *
                   10213: 
                   10214: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   10215: 
                   10216: =item *
                   10217: 
                   10218: reply() : uses subreply to send a message to remote machine, logs all failures
                   10219: 
                   10220: =item *
                   10221: 
                   10222: critical() : passes a critical message to another server; if cannot
                   10223: get through then place message in connection buffer directory and
                   10224: returns con_delayed, if incapable of saving message, returns
                   10225: con_failed
                   10226: 
                   10227: =item *
                   10228: 
                   10229: reconlonc() : tries to reconnect lonc client processes.
                   10230: 
                   10231: =back
                   10232: 
                   10233: =head2 Resource Access Logging
                   10234: 
                   10235: =over 4
                   10236: 
                   10237: =item *
                   10238: 
                   10239: flushcourselogs() : flush (save) buffer logs and access logs
                   10240: 
                   10241: =item *
                   10242: 
                   10243: courselog($what) : save message for course in hash
                   10244: 
                   10245: =item *
                   10246: 
                   10247: courseacclog($what) : save message for course using &courselog().  Perform
                   10248: special processing for specific resource types (problems, exams, quizzes, etc).
                   10249: 
1.191     harris41 10250: =item *
                   10251: 
                   10252: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   10253: as a PerlChildExitHandler
1.243     albertel 10254: 
                   10255: =back
                   10256: 
                   10257: =head2 Other
                   10258: 
                   10259: =over 4
                   10260: 
                   10261: =item *
                   10262: 
                   10263: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 10264: 
                   10265: =back
                   10266: 
                   10267: =cut
1.877     foxr     10268: 

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