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

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

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