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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.976.2.6! raeburn     4: # $Id: lonnet.pm,v 1.976.2.5 2009/01/05 16:28:11 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 {
                    525:     my $delthis=shift;
                    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.4  raeburn   538: 	    if ($key=~/^\Q$delthis\E/) { 
1.915     albertel  539: 		delete($env{$key});
                    540: 		delete($disk_env{$key});
                    541: 	    }
1.448     albertel  542: 	}
1.783     albertel  543: 	untie(%disk_env);
1.5       www       544:     }
                    545:     return 'ok';
1.369     albertel  546: }
                    547: 
1.790     albertel  548: sub get_env_multiple {
                    549:     my ($name) = @_;
                    550:     my @values;
                    551:     if (defined($env{$name})) {
                    552:         # exists is it an array
                    553:         if (ref($env{$name})) {
                    554:             @values=@{ $env{$name} };
                    555:         } else {
                    556:             $values[0]=$env{$name};
                    557:         }
                    558:     }
                    559:     return(@values);
                    560: }
                    561: 
1.958     www       562: # ------------------------------------------------------------------- Locking
                    563: 
                    564: sub set_lock {
                    565:     my ($text)=@_;
                    566:     $locknum++;
                    567:     my $id=$$.'-'.$locknum;
                    568:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    569:              'session.lock.'.$id => $text});
                    570:     return $id;
                    571: }
                    572: 
                    573: sub get_locks {
                    574:     my $num=0;
                    575:     my %texts=();
                    576:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    577:        if ($lock=~/\w/) {
                    578:           $num++;
                    579:           $texts{$lock}=$env{'session.lock.'.$lock};
                    580:        }
                    581:    }
                    582:    return ($num,%texts);
                    583: }
                    584: 
                    585: sub remove_lock {
                    586:     my ($id)=@_;
                    587:     my $newlocks='';
                    588:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    589:        if (($lock=~/\w/) && ($lock ne $id)) {
                    590:           $newlocks.=','.$lock;
                    591:        }
                    592:     }
                    593:     &appenv({'session.locks' => $newlocks});
                    594:     &delenv('session.lock.'.$id);
                    595: }
                    596: 
                    597: sub remove_all_locks {
                    598:     my $activelocks=$env{'session.locks'};
                    599:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    600:        if ($lock=~/\w/) {
                    601:           &remove_lock($lock);
                    602:        }
                    603:     }
                    604: }
                    605: 
                    606: 
1.369     albertel  607: # ------------------------------------------ Find out current server userload
                    608: sub userload {
                    609:     my $numusers=0;
                    610:     {
                    611: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    612: 	my $filename;
                    613: 	my $curtime=time;
                    614: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  615: 	    next if ($filename eq '.' || $filename eq '..');
                    616: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  617: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  618: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  619: 	}
                    620: 	closedir(LONIDS);
                    621:     }
                    622:     my $userloadpercent=0;
                    623:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    624:     if ($maxuserload) {
1.371     albertel  625: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  626:     }
1.372     albertel  627:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  628:     return $userloadpercent;
1.283     www       629: }
                    630: 
                    631: # ------------------------------------------ Fight off request when overloaded
                    632: 
                    633: sub overloaderror {
                    634:     my ($r,$checkserver)=@_;
                    635:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    636:     my $loadavg;
                    637:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  638:        open(my $loadfile,'/proc/loadavg');
1.283     www       639:        $loadavg=<$loadfile>;
                    640:        $loadavg =~ s/\s.*//g;
1.285     matthew   641:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  642:        close($loadfile);
1.283     www       643:     } else {
                    644:        $loadavg=&reply('load',$checkserver);
                    645:     }
1.285     matthew   646:     my $overload=$loadavg-100;
1.283     www       647:     if ($overload>0) {
1.285     matthew   648: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       649:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       650:         return 413;
1.283     www       651:     }    
                    652:     return '';
1.5       www       653: }
1.1       albertel  654: 
                    655: # ------------------------------ Find server with least workload from spare.tab
1.11      www       656: 
1.1       albertel  657: sub spareserver {
1.670     albertel  658:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  659:     my $spare_server;
1.370     albertel  660:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  661:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    662:                                                      :  $userloadpercent;
                    663:     
                    664:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    665: 	($spare_server, $lowest_load) =
                    666: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    667:     }
                    668: 
                    669:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    670: 
                    671:     if (!$found_server) {
                    672: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    673: 	    ($spare_server, $lowest_load) =
                    674: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    675: 	}
                    676:     }
                    677: 
                    678:     if (!$want_server_name) {
1.968     raeburn   679:         my $protocol = 'http';
                    680:         if ($protocol{$spare_server} eq 'https') {
                    681:             $protocol = $protocol{$spare_server};
                    682:         }
                    683: 	$spare_server = $protocol.'://'.&hostname($spare_server);
1.784     albertel  684:     }
                    685:     return $spare_server;
                    686: }
                    687: 
                    688: sub compare_server_load {
                    689:     my ($try_server, $spare_server, $lowest_load) = @_;
                    690: 
                    691:     my $loadans     = &reply('load',    $try_server);
                    692:     my $userloadans = &reply('userload',$try_server);
                    693: 
                    694:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    695: 	next; #didn't get a number from the server
                    696:     }
                    697: 
                    698:     my $load;
                    699:     if ($loadans =~ /\d/) {
                    700: 	if ($userloadans =~ /\d/) {
                    701: 	    #both are numbers, pick the bigger one
                    702: 	    $load = ($loadans > $userloadans) ? $loadans 
                    703: 		                              : $userloadans;
1.411     albertel  704: 	} else {
1.784     albertel  705: 	    $load = $loadans;
1.411     albertel  706: 	}
1.784     albertel  707:     } else {
                    708: 	$load = $userloadans;
                    709:     }
                    710: 
                    711:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    712: 	$spare_server = $try_server;
                    713: 	$lowest_load  = $load;
1.370     albertel  714:     }
1.784     albertel  715:     return ($spare_server,$lowest_load);
1.202     matthew   716: }
1.914     albertel  717: 
                    718: # --------------------------- ask offload servers if user already has a session
                    719: sub find_existing_session {
                    720:     my ($udom,$uname) = @_;
                    721:     foreach my $try_server (@{ $spareid{'primary'} },
                    722: 			    @{ $spareid{'default'} }) {
                    723: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    724:     }
                    725:     return;
                    726: }
                    727: 
                    728: # -------------------------------- ask if server already has a session for user
                    729: sub has_user_session {
                    730:     my ($lonid,$udom,$uname) = @_;
                    731:     my $result = &reply(join(':','userhassession',
                    732: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    733:     return 1 if ($result eq 'ok');
                    734: 
                    735:     return 0;
                    736: }
                    737: 
1.202     matthew   738: # --------------------------------------------- Try to change a user's password
                    739: 
                    740: sub changepass {
1.799     raeburn   741:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   742:     $currentpass = &escape($currentpass);
                    743:     $newpass     = &escape($newpass);
1.799     raeburn   744:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   745: 		       $server);
                    746:     if (! $answer) {
                    747: 	&logthis("No reply on password change request to $server ".
                    748: 		 "by $uname in domain $udom.");
                    749:     } elsif ($answer =~ "^ok") {
                    750:         &logthis("$uname in $udom successfully changed their password ".
                    751: 		 "on $server.");
                    752:     } elsif ($answer =~ "^pwchange_failure") {
                    753: 	&logthis("$uname in $udom was unable to change their password ".
                    754: 		 "on $server.  The action was blocked by either lcpasswd ".
                    755: 		 "or pwchange");
                    756:     } elsif ($answer =~ "^non_authorized") {
                    757:         &logthis("$uname in $udom did not get their password correct when ".
                    758: 		 "attempting to change it on $server.");
                    759:     } elsif ($answer =~ "^auth_mode_error") {
                    760:         &logthis("$uname in $udom attempted to change their password despite ".
                    761: 		 "not being locally or internally authenticated on $server.");
                    762:     } elsif ($answer =~ "^unknown_user") {
                    763:         &logthis("$uname in $udom attempted to change their password ".
                    764: 		 "on $server but were unable to because $server is not ".
                    765: 		 "their home server.");
                    766:     } elsif ($answer =~ "^refused") {
                    767: 	&logthis("$server refused to change $uname in $udom password because ".
                    768: 		 "it was sent an unencrypted request to change the password.");
                    769:     }
                    770:     return $answer;
1.1       albertel  771: }
                    772: 
1.169     harris41  773: # ----------------------- Try to determine user's current authentication scheme
                    774: 
                    775: sub queryauthenticate {
                    776:     my ($uname,$udom)=@_;
1.456     albertel  777:     my $uhome=&homeserver($uname,$udom);
                    778:     if (!$uhome) {
                    779: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    780: 	return 'no_host';
                    781:     }
                    782:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    783:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    784: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  785:     }
1.456     albertel  786:     return $answer;
1.169     harris41  787: }
                    788: 
1.1       albertel  789: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       790: 
1.1       albertel  791: sub authenticate {
1.952     raeburn   792:     my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807     albertel  793:     $upass=&escape($upass);
                    794:     $uname= &LONCAPA::clean_username($uname);
1.836     www       795:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   796:     my $newhome;
1.836     www       797:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    798: # Maybe the machine was offline and only re-appeared again recently?
                    799:         &reconlonc();
                    800: # One more
1.952     raeburn   801: 	$uhome=&homeserver($uname,$udom,1);
                    802:         if (($uhome eq 'no_host') && $checkdefauth) {
                    803:             if (defined(&domain($udom,'primary'))) {
                    804:                 $newhome=&domain($udom,'primary');
                    805:             }
                    806:             if ($newhome ne '') {
                    807:                 $uhome = $newhome;
                    808:             }
                    809:         }
1.836     www       810: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    811: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   812: 	    return 'no_host';
                    813:         }
1.1       albertel  814:     }
1.952     raeburn   815:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471     albertel  816:     if ($answer eq 'authorized') {
1.952     raeburn   817:         if ($newhome) {
                    818:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    819:             return 'no_account_on_host'; 
                    820:         } else {
                    821:             &logthis("User $uname at $udom authorized by $uhome");
                    822:             return $uhome;
                    823:         }
1.471     albertel  824:     }
                    825:     if ($answer eq 'non_authorized') {
                    826: 	&logthis("User $uname at $udom rejected by $uhome");
                    827: 	return 'no_host'; 
1.9       www       828:     }
1.471     albertel  829:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  830:     return 'no_host';
                    831: }
                    832: 
                    833: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       834: 
1.599     albertel  835: my %homecache;
1.1       albertel  836: sub homeserver {
1.230     stredwic  837:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  838:     my $index="$uname:$udom";
1.426     albertel  839: 
1.599     albertel  840:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  841: 
                    842:     my %servers = &get_servers($udom,'library');
                    843:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  844:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  845: 		 exists($badServerCache{$tryserver}));
1.841     albertel  846: 
                    847: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    848: 	if ($answer eq 'found') {
                    849: 	    delete($badServerCache{$tryserver}); 
                    850: 	    return $homecache{$index}=$tryserver;
                    851: 	} elsif ($answer eq 'no_host') {
                    852: 	    $badServerCache{$tryserver}=1;
                    853: 	}
1.1       albertel  854:     }    
                    855:     return 'no_host';
1.70      www       856: }
                    857: 
                    858: # ------------------------------------- Find the usernames behind a list of IDs
                    859: 
                    860: sub idget {
                    861:     my ($udom,@ids)=@_;
                    862:     my %returnhash=();
                    863:     
1.841     albertel  864:     my %servers = &get_servers($udom,'library');
                    865:     foreach my $tryserver (keys(%servers)) {
                    866: 	my $idlist=join('&',@ids);
                    867: 	$idlist=~tr/A-Z/a-z/; 
                    868: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    869: 	my @answer=();
                    870: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    871: 	    @answer=split(/\&/,$reply);
                    872: 	}                    ;
                    873: 	my $i;
                    874: 	for ($i=0;$i<=$#ids;$i++) {
                    875: 	    if ($answer[$i]) {
                    876: 		$returnhash{$ids[$i]}=$answer[$i];
                    877: 	    } 
                    878: 	}
                    879:     } 
1.70      www       880:     return %returnhash;
                    881: }
                    882: 
                    883: # ------------------------------------- Find the IDs behind a list of usernames
                    884: 
                    885: sub idrget {
                    886:     my ($udom,@unames)=@_;
                    887:     my %returnhash=();
1.800     albertel  888:     foreach my $uname (@unames) {
                    889:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  890:     }
1.70      www       891:     return %returnhash;
                    892: }
                    893: 
                    894: # ------------------------------- Store away a list of names and associated IDs
                    895: 
                    896: sub idput {
                    897:     my ($udom,%ids)=@_;
                    898:     my %servers=();
1.800     albertel  899:     foreach my $uname (keys(%ids)) {
                    900: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    901:         my $uhom=&homeserver($uname,$udom);
1.70      www       902:         if ($uhom ne 'no_host') {
1.800     albertel  903:             my $id=&escape($ids{$uname});
1.70      www       904:             $id=~tr/A-Z/a-z/;
1.800     albertel  905:             my $esc_unam=&escape($uname);
1.70      www       906: 	    if ($servers{$uhom}) {
1.800     albertel  907: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       908:             } else {
1.800     albertel  909:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       910:             }
                    911:         }
1.191     harris41  912:     }
1.800     albertel  913:     foreach my $server (keys(%servers)) {
                    914:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  915:     }
1.344     www       916: }
                    917: 
1.806     raeburn   918: # ------------------------------------------- get items from domain db files   
                    919: 
                    920: sub get_dom {
1.860     raeburn   921:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   922:     my $items='';
                    923:     foreach my $item (@$storearr) {
                    924:         $items.=&escape($item).'&';
                    925:     }
                    926:     $items=~s/\&$//;
1.860     raeburn   927:     if (!$udom) {
                    928:         $udom=$env{'user.domain'};
                    929:         if (defined(&domain($udom,'primary'))) {
                    930:             $uhome=&domain($udom,'primary');
                    931:         } else {
1.874     albertel  932:             undef($uhome);
1.860     raeburn   933:         }
                    934:     } else {
                    935:         if (!$uhome) {
                    936:             if (defined(&domain($udom,'primary'))) {
                    937:                 $uhome=&domain($udom,'primary');
                    938:             }
                    939:         }
                    940:     }
                    941:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   942:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn   943:         my %returnhash;
1.875     albertel  944:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn   945:             return %returnhash;
                    946:         }
1.806     raeburn   947:         my @pairs=split(/\&/,$rep);
                    948:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    949:             return @pairs;
                    950:         }
                    951:         my $i=0;
                    952:         foreach my $item (@$storearr) {
                    953:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    954:             $i++;
                    955:         }
                    956:         return %returnhash;
                    957:     } else {
1.880     banghart  958:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn   959:     }
                    960: }
                    961: 
                    962: # -------------------------------------------- put items in domain db files 
                    963: 
                    964: sub put_dom {
1.860     raeburn   965:     my ($namespace,$storehash,$udom,$uhome)=@_;
                    966:     if (!$udom) {
                    967:         $udom=$env{'user.domain'};
                    968:         if (defined(&domain($udom,'primary'))) {
                    969:             $uhome=&domain($udom,'primary');
                    970:         } else {
1.874     albertel  971:             undef($uhome);
1.860     raeburn   972:         }
                    973:     } else {
                    974:         if (!$uhome) {
                    975:             if (defined(&domain($udom,'primary'))) {
                    976:                 $uhome=&domain($udom,'primary');
                    977:             }
                    978:         }
                    979:     } 
                    980:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   981:         my $items='';
                    982:         foreach my $item (keys(%$storehash)) {
                    983:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    984:         }
                    985:         $items=~s/\&$//;
                    986:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    987:     } else {
1.860     raeburn   988:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn   989:     }
                    990: }
                    991: 
1.837     raeburn   992: sub retrieve_inst_usertypes {
                    993:     my ($udom) = @_;
                    994:     my (%returnhash,@order);
1.846     albertel  995:     if (defined(&domain($udom,'primary'))) {
                    996:         my $uhome=&domain($udom,'primary');
1.837     raeburn   997:         my $rep=&reply("inst_usertypes:$udom",$uhome);
1.960     raeburn   998:         if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                    999:             &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1000:             return (\%returnhash,\@order);
                   1001:         }
1.837     raeburn  1002:         my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1003:         my @pairs=split(/\&/,$hashitems);
                   1004:         foreach my $item (@pairs) {
                   1005:             my ($key,$value)=split(/=/,$item,2);
                   1006:             $key = &unescape($key);
                   1007:             next if ($key =~ /^error: 2 /);
                   1008:             $returnhash{$key}=&thaw_unescape($value);
                   1009:         }
                   1010:         my @esc_order = split(/\&/,$orderitems);
                   1011:         foreach my $item (@esc_order) {
                   1012:             push(@order,&unescape($item));
                   1013:         }
                   1014:     } else {
                   1015:         &logthis("get_dom failed - no primary domain server for $udom");
                   1016:     }
                   1017:     return (\%returnhash,\@order);
                   1018: }
                   1019: 
1.868     raeburn  1020: sub is_domainimage {
                   1021:     my ($url) = @_;
                   1022:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1023:         if (&domain($1) ne '') {
                   1024:             return '1';
                   1025:         }
                   1026:     }
                   1027:     return;
                   1028: }
                   1029: 
1.899     raeburn  1030: sub inst_directory_query {
                   1031:     my ($srch) = @_;
                   1032:     my $udom = $srch->{'srchdomain'};
                   1033:     my %results;
                   1034:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1035:     my $outcome;
1.899     raeburn  1036:     if ($homeserver ne '') {
1.904     albertel 1037: 	my $queryid=&reply("querysend:instdirsearch:".
                   1038: 			   &escape($srch->{'srchby'}).':'.
                   1039: 			   &escape($srch->{'srchterm'}).':'.
                   1040: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1041: 	my $host=&hostname($homeserver);
                   1042: 	if ($queryid !~/^\Q$host\E\_/) {
                   1043: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1044: 	    return;
                   1045: 	}
                   1046: 	my $response = &get_query_reply($queryid);
                   1047: 	my $maxtries = 5;
                   1048: 	my $tries = 1;
                   1049: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1050: 	    $response = &get_query_reply($queryid);
                   1051: 	    $tries ++;
                   1052: 	}
                   1053: 
                   1054:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1055:             if ($response eq 'unavailable') {
                   1056:                 $outcome = $response;
                   1057:             } else {
                   1058:                 $outcome = 'ok';
                   1059:                 my @matches = split(/\n/,$response);
                   1060:                 foreach my $match (@matches) {
                   1061:                     my ($key,$value) = split(/=/,$match);
                   1062:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1063:                 }
1.899     raeburn  1064:             }
                   1065:         }
                   1066:     }
1.909     raeburn  1067:     return ($outcome,%results);
1.899     raeburn  1068: }
                   1069: 
                   1070: sub usersearch {
                   1071:     my ($srch) = @_;
                   1072:     my $dom = $srch->{'srchdomain'};
                   1073:     my %results;
                   1074:     my %libserv = &all_library();
                   1075:     my $query = 'usersearch';
                   1076:     foreach my $tryserver (keys(%libserv)) {
                   1077:         if (&host_domain($tryserver) eq $dom) {
                   1078:             my $host=&hostname($tryserver);
                   1079:             my $queryid=
1.911     raeburn  1080:                 &reply("querysend:".&escape($query).':'.
                   1081:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1082:                        &escape($srch->{'srchtype'}).':'.
                   1083:                        &escape($srch->{'srchterm'}),$tryserver);
                   1084:             if ($queryid !~/^\Q$host\E\_/) {
                   1085:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1086:                 next;
1.899     raeburn  1087:             }
                   1088:             my $reply = &get_query_reply($queryid);
                   1089:             my $maxtries = 1;
                   1090:             my $tries = 1;
                   1091:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1092:                 $reply = &get_query_reply($queryid);
                   1093:                 $tries ++;
                   1094:             }
                   1095:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1096:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1097:             } else {
1.911     raeburn  1098:                 my @matches;
                   1099:                 if ($reply =~ /\n/) {
                   1100:                     @matches = split(/\n/,$reply);
                   1101:                 } else {
                   1102:                     @matches = split(/\&/,$reply);
                   1103:                 }
1.899     raeburn  1104:                 foreach my $match (@matches) {
                   1105:                     my ($uname,$udom,%userhash);
1.911     raeburn  1106:                     foreach my $entry (split(/:/,$match)) {
                   1107:                         my ($key,$value) =
                   1108:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1109:                         $userhash{$key} = $value;
                   1110:                         if ($key eq 'username') {
                   1111:                             $uname = $value;
                   1112:                         } elsif ($key eq 'domain') {
                   1113:                             $udom = $value;
1.911     raeburn  1114:                         }
1.899     raeburn  1115:                     }
                   1116:                     $results{$uname.':'.$udom} = \%userhash;
                   1117:                 }
                   1118:             }
                   1119:         }
                   1120:     }
                   1121:     return %results;
                   1122: }
                   1123: 
1.912     raeburn  1124: sub get_instuser {
                   1125:     my ($udom,$uname,$id) = @_;
                   1126:     my $homeserver = &domain($udom,'primary');
                   1127:     my ($outcome,%results);
                   1128:     if ($homeserver ne '') {
                   1129:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1130:                            &escape($id).':'.&escape($udom),$homeserver);
                   1131:         my $host=&hostname($homeserver);
                   1132:         if ($queryid !~/^\Q$host\E\_/) {
                   1133:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1134:             return;
                   1135:         }
                   1136:         my $response = &get_query_reply($queryid);
                   1137:         my $maxtries = 5;
                   1138:         my $tries = 1;
                   1139:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1140:             $response = &get_query_reply($queryid);
                   1141:             $tries ++;
                   1142:         }
                   1143:         if (!&error($response) && $response ne 'refused') {
                   1144:             if ($response eq 'unavailable') {
                   1145:                 $outcome = $response;
                   1146:             } else {
                   1147:                 $outcome = 'ok';
                   1148:                 my @matches = split(/\n/,$response);
                   1149:                 foreach my $match (@matches) {
                   1150:                     my ($key,$value) = split(/=/,$match);
                   1151:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1152:                 }
                   1153:             }
                   1154:         }
                   1155:     }
                   1156:     my %userinfo;
                   1157:     if (ref($results{$uname}) eq 'HASH') {
                   1158:         %userinfo = %{$results{$uname}};
                   1159:     } 
                   1160:     return ($outcome,%userinfo);
                   1161: }
                   1162: 
                   1163: sub inst_rulecheck {
1.923     raeburn  1164:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1165:     my %returnhash;
                   1166:     if ($udom ne '') {
                   1167:         if (ref($rules) eq 'ARRAY') {
                   1168:             @{$rules} = map {&escape($_);} (@{$rules});
                   1169:             my $rulestr = join(':',@{$rules});
                   1170:             my $homeserver=&domain($udom,'primary');
                   1171:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1172:                 my $response;
                   1173:                 if ($item eq 'username') {                
                   1174:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1175:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1176:                                               $homeserver));
1.923     raeburn  1177:                 } elsif ($item eq 'id') {
                   1178:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1179:                                               ':'.&escape($id).':'.$rulestr,
                   1180:                                               $homeserver));
1.945     raeburn  1181:                 } elsif ($item eq 'selfcreate') {
                   1182:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1183:                                                &escape($udom).':'.&escape($uname).
                   1184:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1185:                 }
1.912     raeburn  1186:                 if ($response ne 'refused') {
                   1187:                     my @pairs=split(/\&/,$response);
                   1188:                     foreach my $item (@pairs) {
                   1189:                         my ($key,$value)=split(/=/,$item,2);
                   1190:                         $key = &unescape($key);
                   1191:                         next if ($key =~ /^error: 2 /);
                   1192:                         $returnhash{$key}=&thaw_unescape($value);
                   1193:                     }
                   1194:                 }
                   1195:             }
                   1196:         }
                   1197:     }
                   1198:     return %returnhash;
                   1199: }
                   1200: 
                   1201: sub inst_userrules {
1.923     raeburn  1202:     my ($udom,$check) = @_;
1.912     raeburn  1203:     my (%ruleshash,@ruleorder);
                   1204:     if ($udom ne '') {
                   1205:         my $homeserver=&domain($udom,'primary');
                   1206:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1207:             my $response;
                   1208:             if ($check eq 'id') {
                   1209:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1210:                                  $homeserver);
1.943     raeburn  1211:             } elsif ($check eq 'email') {
                   1212:                 $response=&reply('instemailrules:'.&escape($udom),
                   1213:                                  $homeserver);
1.923     raeburn  1214:             } else {
                   1215:                 $response=&reply('instuserrules:'.&escape($udom),
                   1216:                                  $homeserver);
                   1217:             }
1.912     raeburn  1218:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1219:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1220:                 ($response ne 'no_such_host')) {
                   1221:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1222:                 my @pairs=split(/\&/,$hashitems);
                   1223:                 foreach my $item (@pairs) {
                   1224:                     my ($key,$value)=split(/=/,$item,2);
                   1225:                     $key = &unescape($key);
                   1226:                     next if ($key =~ /^error: 2 /);
                   1227:                     $ruleshash{$key}=&thaw_unescape($value);
                   1228:                 }
                   1229:                 my @esc_order = split(/\&/,$orderitems);
                   1230:                 foreach my $item (@esc_order) {
                   1231:                     push(@ruleorder,&unescape($item));
                   1232:                 }
                   1233:             }
                   1234:         }
                   1235:     }
                   1236:     return (\%ruleshash,\@ruleorder);
                   1237: }
                   1238: 
1.976     raeburn  1239: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1240: 
                   1241: sub get_domain_defaults {
                   1242:     my ($domain) = @_;
                   1243:     my $cachetime = 60*60*24;
                   1244:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1245:     if (defined($cached)) {
                   1246:         if (ref($result) eq 'HASH') {
                   1247:             return %{$result};
                   1248:         }
                   1249:     }
                   1250:     my %domdefaults;
                   1251:     my %domconfig =
1.976     raeburn  1252:          &Apache::lonnet::get_dom('configuration',['defaults','quotas'],$domain);
1.943     raeburn  1253:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1254:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1255:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1256:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.976.2.5  raeburn  1257:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
                   1258:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1259:     } else {
                   1260:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1261:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1262:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1263:     }
1.976     raeburn  1264:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1265:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1266:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1267:         } else {
                   1268:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1269:         } 
                   1270:         my @usertools = ('aboutme','blog','portfolio');
                   1271:         foreach my $item (@usertools) {
                   1272:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1273:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1274:             }
                   1275:         }
                   1276:     }
1.943     raeburn  1277:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1278:                                   $cachetime);
                   1279:     return %domdefaults;
                   1280: }
                   1281: 
1.344     www      1282: # --------------------------------------------------- Assign a key to a student
                   1283: 
                   1284: sub assign_access_key {
1.364     www      1285: #
                   1286: # a valid key looks like uname:udom#comments
                   1287: # comments are being appended
                   1288: #
1.498     www      1289:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1290:     $kdom=
1.620     albertel 1291:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1292:     $knum=
1.620     albertel 1293:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1294:     $cdom=
1.620     albertel 1295:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1296:     $cnum=
1.620     albertel 1297:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1298:     $udom=$env{'user.name'} unless (defined($udom));
                   1299:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1300:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1301:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1302:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1303:                                                   # assigned to this person
                   1304:                                                   # - this should not happen,
1.345     www      1305:                                                   # unless something went wrong
                   1306:                                                   # the first time around
                   1307: # ready to assign
1.364     www      1308:         $logentry=$1.'; '.$logentry;
1.496     www      1309:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1310:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1311: # key now belongs to user
1.346     www      1312: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1313:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1314:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1315:                 return 'ok';
                   1316:             } else {
                   1317:                 return 
                   1318:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1319: 	    }
                   1320:         } else {
                   1321:             return 'error: Could not assign key, try again later.';
                   1322:         }
1.364     www      1323:     } elsif (!$existing{$ckey}) {
1.345     www      1324: # the key does not exist
                   1325: 	return 'error: The key does not exist';
                   1326:     } else {
                   1327: # the key is somebody else's
                   1328: 	return 'error: The key is already in use';
                   1329:     }
1.344     www      1330: }
                   1331: 
1.364     www      1332: # ------------------------------------------ put an additional comment on a key
                   1333: 
                   1334: sub comment_access_key {
                   1335: #
                   1336: # a valid key looks like uname:udom#comments
                   1337: # comments are being appended
                   1338: #
                   1339:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1340:     $cdom=
1.620     albertel 1341:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1342:     $cnum=
1.620     albertel 1343:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1344:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1345:     if ($existing{$ckey}) {
                   1346:         $existing{$ckey}.='; '.$logentry;
                   1347: # ready to assign
1.367     www      1348:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1349:                                                  $cdom,$cnum) eq 'ok') {
                   1350: 	    return 'ok';
                   1351:         } else {
                   1352: 	    return 'error: Count not store comment.';
                   1353:         }
                   1354:     } else {
                   1355: # the key does not exist
                   1356: 	return 'error: The key does not exist';
                   1357:     }
                   1358: }
                   1359: 
1.344     www      1360: # ------------------------------------------------------ Generate a set of keys
                   1361: 
                   1362: sub generate_access_keys {
1.364     www      1363:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1364:     $cdom=
1.620     albertel 1365:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1366:     $cnum=
1.620     albertel 1367:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1368:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1369:     unless (($cdom) && ($cnum)) { return 0; }
                   1370:     if ($number>10000) { return 0; }
                   1371:     sleep(2); # make sure don't get same seed twice
                   1372:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1373:     my $total=0;
                   1374:     for (my $i=1;$i<=$number;$i++) {
                   1375:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1376:                   sprintf("%lx",int(100000*rand)).'-'.
                   1377:                   sprintf("%lx",int(100000*rand));
                   1378:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1379:        $newkey=~s/0/h/g; # and also 0 and O
                   1380:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1381:        if ($existing{$newkey}) {
                   1382:            $i--;
                   1383:        } else {
1.364     www      1384: 	  if (&put('accesskeys',
                   1385:               { $newkey => '# generated '.localtime().
1.620     albertel 1386:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1387:                            '; '.$logentry },
                   1388: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1389:               $total++;
                   1390: 	  }
                   1391:        }
                   1392:     }
1.620     albertel 1393:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1394:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1395:     return $total;
                   1396: }
                   1397: 
                   1398: # ------------------------------------------------------- Validate an accesskey
                   1399: 
                   1400: sub validate_access_key {
                   1401:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1402:     $cdom=
1.620     albertel 1403:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1404:     $cnum=
1.620     albertel 1405:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1406:     $udom=$env{'user.domain'} unless (defined($udom));
                   1407:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1408:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1409:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1410: }
                   1411: 
                   1412: # ------------------------------------- Find the section of student in a course
1.652     albertel 1413: sub devalidate_getsection_cache {
                   1414:     my ($udom,$unam,$courseid)=@_;
                   1415:     my $hashid="$udom:$unam:$courseid";
                   1416:     &devalidate_cache_new('getsection',$hashid);
                   1417: }
1.298     matthew  1418: 
1.815     albertel 1419: sub courseid_to_courseurl {
                   1420:     my ($courseid) = @_;
                   1421:     #already url style courseid
                   1422:     return $courseid if ($courseid =~ m{^/});
                   1423: 
                   1424:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1425: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1426: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1427: 	return "/$cdom/$cnum";
                   1428:     }
                   1429: 
                   1430:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1431:     if (exists($courseinfo{'num'})) {
                   1432: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1433:     }
                   1434: 
                   1435:     return undef;
                   1436: }
                   1437: 
1.298     matthew  1438: sub getsection {
                   1439:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1440:     my $cachetime=1800;
1.551     albertel 1441: 
                   1442:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1443:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1444:     if (defined($cached)) { return $result; }
                   1445: 
1.298     matthew  1446:     my %Pending; 
                   1447:     my %Expired;
                   1448:     #
                   1449:     # Each role can either have not started yet (pending), be active, 
                   1450:     #    or have expired.
                   1451:     #
                   1452:     # If there is an active role, we are done.
                   1453:     #
                   1454:     # If there is more than one role which has not started yet, 
                   1455:     #     choose the one which will start sooner
                   1456:     # If there is one role which has not started yet, return it.
                   1457:     #
                   1458:     # If there is more than one expired role, choose the one which ended last.
                   1459:     # If there is a role which has expired, return it.
                   1460:     #
1.815     albertel 1461:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1462:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1463:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1464:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1465:         my $section=$1;
                   1466:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1467:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1468:         my $now=time;
1.548     albertel 1469:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1470:             $Expired{$end}=$section;
                   1471:             next;
                   1472:         }
1.548     albertel 1473:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1474:             $Pending{$start}=$section;
                   1475:             next;
                   1476:         }
1.599     albertel 1477:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1478:     }
                   1479:     #
                   1480:     # Presumedly there will be few matching roles from the above
                   1481:     # loop and the sorting time will be negligible.
                   1482:     if (scalar(keys(%Pending))) {
                   1483:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1484:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1485:     } 
                   1486:     if (scalar(keys(%Expired))) {
                   1487:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1488:         my $time = pop(@sorted);
1.599     albertel 1489:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1490:     }
1.599     albertel 1491:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1492: }
1.70      www      1493: 
1.599     albertel 1494: sub save_cache {
                   1495:     &purge_remembered();
1.722     albertel 1496:     #&Apache::loncommon::validate_page();
1.620     albertel 1497:     undef(%env);
1.780     albertel 1498:     undef($env_loaded);
1.599     albertel 1499: }
1.452     albertel 1500: 
1.599     albertel 1501: my $to_remember=-1;
                   1502: my %remembered;
                   1503: my %accessed;
                   1504: my $kicks=0;
                   1505: my $hits=0;
1.849     albertel 1506: sub make_key {
                   1507:     my ($name,$id) = @_;
1.872     albertel 1508:     if (length($id) > 65 
                   1509: 	&& length(&escape($id)) > 200) {
                   1510: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1511:     }
1.849     albertel 1512:     return &escape($name.':'.$id);
                   1513: }
                   1514: 
1.599     albertel 1515: sub devalidate_cache_new {
                   1516:     my ($name,$id,$debug) = @_;
                   1517:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1518:     $id=&make_key($name,$id);
1.599     albertel 1519:     $memcache->delete($id);
                   1520:     delete($remembered{$id});
                   1521:     delete($accessed{$id});
                   1522: }
                   1523: 
                   1524: sub is_cached_new {
                   1525:     my ($name,$id,$debug) = @_;
1.849     albertel 1526:     $id=&make_key($name,$id);
1.599     albertel 1527:     if (exists($remembered{$id})) {
                   1528: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1529: 	$accessed{$id}=[&gettimeofday()];
                   1530: 	$hits++;
                   1531: 	return ($remembered{$id},1);
                   1532:     }
                   1533:     my $value = $memcache->get($id);
                   1534:     if (!(defined($value))) {
                   1535: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1536: 	return (undef,undef);
1.416     albertel 1537:     }
1.599     albertel 1538:     if ($value eq '__undef__') {
                   1539: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1540: 	$value=undef;
                   1541:     }
                   1542:     &make_room($id,$value,$debug);
                   1543:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1544:     return ($value,1);
                   1545: }
                   1546: 
                   1547: sub do_cache_new {
                   1548:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1549:     $id=&make_key($name,$id);
1.599     albertel 1550:     my $setvalue=$value;
                   1551:     if (!defined($setvalue)) {
                   1552: 	$setvalue='__undef__';
                   1553:     }
1.623     albertel 1554:     if (!defined($time) ) {
                   1555: 	$time=600;
                   1556:     }
1.599     albertel 1557:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1558:     my $result = $memcache->set($id,$setvalue,$time);
                   1559:     if (! $result) {
1.872     albertel 1560: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1561: 	$memcache->disconnect_all();
1.872     albertel 1562:     }
1.600     albertel 1563:     # need to make a copy of $value
1.919     albertel 1564:     &make_room($id,$value,$debug);
1.599     albertel 1565:     return $value;
                   1566: }
                   1567: 
                   1568: sub make_room {
                   1569:     my ($id,$value,$debug)=@_;
1.919     albertel 1570: 
                   1571:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1572:                                     : $value;
1.599     albertel 1573:     if ($to_remember<0) { return; }
                   1574:     $accessed{$id}=[&gettimeofday()];
                   1575:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1576:     my $to_kick;
                   1577:     my $max_time=0;
                   1578:     foreach my $other (keys(%accessed)) {
                   1579: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1580: 	    $to_kick=$other;
                   1581: 	    $max_time=&tv_interval($accessed{$other});
                   1582: 	}
                   1583:     }
                   1584:     delete($remembered{$to_kick});
                   1585:     delete($accessed{$to_kick});
                   1586:     $kicks++;
                   1587:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1588:     return;
                   1589: }
                   1590: 
1.599     albertel 1591: sub purge_remembered {
1.604     albertel 1592:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1593:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1594:     undef(%remembered);
                   1595:     undef(%accessed);
1.428     albertel 1596: }
1.70      www      1597: # ------------------------------------- Read an entry from a user's environment
                   1598: 
                   1599: sub userenvironment {
                   1600:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1601:     my $items;
                   1602:     foreach my $item (@what) {
                   1603:         $items.=&escape($item).'&';
                   1604:     }
                   1605:     $items=~s/\&$//;
1.70      www      1606:     my %returnhash=();
                   1607:     my @answer=split(/\&/,
1.976     raeburn  1608:                 &reply('get:'.$udom.':'.$unam.':environment:'.$items,
1.70      www      1609:                       &homeserver($unam,$udom)));
                   1610:     my $i;
                   1611:     for ($i=0;$i<=$#what;$i++) {
                   1612: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1613:     }
                   1614:     return %returnhash;
1.1       albertel 1615: }
                   1616: 
1.617     albertel 1617: # ---------------------------------------------------------- Get a studentphoto
                   1618: sub studentphoto {
                   1619:     my ($udom,$unam,$ext) = @_;
                   1620:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1621:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1622:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1623:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1624:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1625:             } else {
                   1626:                 my ($result,$perm_reqd)=
1.707     albertel 1627: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1628:                 if ($result eq 'ok') {
                   1629:                     if (!($perm_reqd eq 'yes')) {
                   1630:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1631:                     }
                   1632:                 }
                   1633:             }
                   1634:         }
                   1635:     } else {
                   1636:         my ($result,$perm_reqd) = 
1.707     albertel 1637: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1638:         if ($result eq 'ok') {
                   1639:             if (!($perm_reqd eq 'yes')) {
                   1640:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1641:             }
                   1642:         }
                   1643:     }
                   1644:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1645: }
                   1646: 
                   1647: sub retrievestudentphoto {
                   1648:     my ($udom,$unam,$ext,$type) = @_;
                   1649:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1650:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1651:     if ($ret eq 'ok') {
                   1652:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1653:         if ($type eq 'thumbnail') {
                   1654:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1655:         }
                   1656:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1657:         return $tokenurl;
                   1658:     } else {
                   1659:         if ($type eq 'thumbnail') {
                   1660:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1661:         } else { 
                   1662:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1663:         }
1.617     albertel 1664:     }
                   1665: }
                   1666: 
1.263     www      1667: # -------------------------------------------------------------------- New chat
                   1668: 
                   1669: sub chatsend {
1.724     raeburn  1670:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1671:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1672:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1673:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1674:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1675: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1676: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1677: }
                   1678: 
                   1679: # ------------------------------------------ Find current version of a resource
                   1680: 
                   1681: sub getversion {
                   1682:     my $fname=&clutter(shift);
                   1683:     unless ($fname=~/^\/res\//) { return -1; }
                   1684:     return &currentversion(&filelocation('',$fname));
                   1685: }
                   1686: 
                   1687: sub currentversion {
                   1688:     my $fname=shift;
1.599     albertel 1689:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1690:     if (defined($cached)) { return $result; }
1.292     www      1691:     my $author=$fname;
                   1692:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1693:     my ($udom,$uname)=split(/\//,$author);
                   1694:     my $home=homeserver($uname,$udom);
                   1695:     if ($home eq 'no_host') { 
                   1696:         return -1; 
                   1697:     }
                   1698:     my $answer=reply("currentversion:$fname",$home);
                   1699:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1700: 	return -1;
                   1701:     }
1.599     albertel 1702:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1703: }
                   1704: 
1.1       albertel 1705: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1706: 
1.1       albertel 1707: sub subscribe {
                   1708:     my $fname=shift;
1.761     raeburn  1709:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1710:     $fname=~s/[\n\r]//g;
1.1       albertel 1711:     my $author=$fname;
                   1712:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1713:     my ($udom,$uname)=split(/\//,$author);
                   1714:     my $home=homeserver($uname,$udom);
1.335     albertel 1715:     if ($home eq 'no_host') {
                   1716:         return 'not_found';
1.1       albertel 1717:     }
                   1718:     my $answer=reply("sub:$fname",$home);
1.64      www      1719:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1720: 	$answer.=' by '.$home;
                   1721:     }
1.1       albertel 1722:     return $answer;
                   1723: }
                   1724:     
1.8       www      1725: # -------------------------------------------------------------- Replicate file
                   1726: 
                   1727: sub repcopy {
                   1728:     my $filename=shift;
1.23      www      1729:     $filename=~s/\/+/\//g;
1.607     raeburn  1730:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1731:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1732:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1733: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1734: 	return &repcopy_userfile($filename);
                   1735:     }
1.532     albertel 1736:     $filename=~s/[\n\r]//g;
1.8       www      1737:     my $transname="$filename.in.transfer";
1.828     www      1738: # FIXME: this should flock
1.607     raeburn  1739:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1740:     my $remoteurl=subscribe($filename);
1.64      www      1741:     if ($remoteurl =~ /^con_lost by/) {
                   1742: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1743:            return 'unavailable';
1.8       www      1744:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1745: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1746: 	   return 'not_found';
1.64      www      1747:     } elsif ($remoteurl =~ /^rejected by/) {
                   1748: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1749:            return 'forbidden';
1.20      www      1750:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1751:            return 'ok';
1.8       www      1752:     } else {
1.290     www      1753:         my $author=$filename;
                   1754:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1755:         my ($udom,$uname)=split(/\//,$author);
                   1756:         my $home=homeserver($uname,$udom);
                   1757:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1758:            my @parts=split(/\//,$filename);
                   1759:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1760:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1761:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1762: 	       return 'bad_request';
1.8       www      1763:            }
                   1764:            my $count;
                   1765:            for ($count=5;$count<$#parts;$count++) {
                   1766:                $path.="/$parts[$count]";
                   1767:                if ((-e $path)!=1) {
                   1768: 		   mkdir($path,0777);
                   1769:                }
                   1770:            }
                   1771:            my $ua=new LWP::UserAgent;
                   1772:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1773:            my $response=$ua->request($request,$transname);
                   1774:            if ($response->is_error()) {
                   1775: 	       unlink($transname);
                   1776:                my $message=$response->status_line;
1.672     albertel 1777:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1778:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1779:                return 'unavailable';
1.8       www      1780:            } else {
1.16      www      1781: 	       if ($remoteurl!~/\.meta$/) {
                   1782:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1783:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1784:                   if ($mresponse->is_error()) {
                   1785: 		      unlink($filename.'.meta');
                   1786:                       &logthis(
1.672     albertel 1787:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1788:                   }
                   1789: 	       }
1.8       www      1790:                rename($transname,$filename);
1.607     raeburn  1791:                return 'ok';
1.8       www      1792:            }
1.290     www      1793:        }
1.8       www      1794:     }
1.330     www      1795: }
                   1796: 
                   1797: # ------------------------------------------------ Get server side include body
                   1798: sub ssi_body {
1.381     albertel 1799:     my ($filelink,%form)=@_;
1.606     matthew  1800:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1801:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1802:     }
1.953     www      1803:     my $output='';
                   1804:     my $response;
1.976.2.3  raeburn  1805:     if ($filelink=~/^https?\:/) {
1.954     raeburn  1806:        ($output,$response)=&externalssi($filelink);
1.953     www      1807:     } else {
                   1808:        ($output,$response)=&ssi($filelink,%form);
                   1809:     }
1.778     albertel 1810:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1811:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 1812:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      1813:     if (wantarray) {
                   1814:         return ($output, $response);
                   1815:     } else {
                   1816:         return $output;
                   1817:     }
1.8       www      1818: }
                   1819: 
1.15      www      1820: # --------------------------------------------------------- Server Side Include
                   1821: 
1.782     albertel 1822: sub absolute_url {
                   1823:     my ($host_name) = @_;
                   1824:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1825:     if ($host_name eq '') {
                   1826: 	$host_name = $ENV{'SERVER_NAME'};
                   1827:     }
                   1828:     return $protocol.$host_name;
                   1829: }
                   1830: 
1.942     foxr     1831: #
                   1832: #   Server side include.
                   1833: # Parameters:
                   1834: #  fn     Possibly encrypted resource name/id.
                   1835: #  form   Hash that describes how the rendering should be done
                   1836: #         and other things.
1.944     foxr     1837: # Returns:
1.950     raeburn  1838: #   Scalar context: The content of the response.
                   1839: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     1840: #     
1.15      www      1841: sub ssi {
                   1842: 
1.944     foxr     1843:     my ($fn,%form)=@_;
1.15      www      1844:     my $ua=new LWP::UserAgent;
1.23      www      1845:     my $request;
1.711     albertel 1846: 
                   1847:     $form{'no_update_last_known'}=1;
1.895     albertel 1848:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1849:     if (%form) {
1.782     albertel 1850:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1851:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1852:     } else {
1.782     albertel 1853:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1854:     }
                   1855: 
1.15      www      1856:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1857:     my $response=$ua->request($request);
                   1858: 
1.944     foxr     1859:     if (wantarray) {
                   1860: 	return ($response->content, $response);
                   1861:     } else {
                   1862: 	return $response->content;
1.942     foxr     1863:     }
1.324     www      1864: }
                   1865: 
                   1866: sub externalssi {
                   1867:     my ($url)=@_;
                   1868:     my $ua=new LWP::UserAgent;
                   1869:     my $request=new HTTP::Request('GET',$url);
                   1870:     my $response=$ua->request($request);
1.954     raeburn  1871:     if (wantarray) {
                   1872:         return ($response->content, $response);
                   1873:     } else {
                   1874:         return $response->content;
                   1875:     }
1.15      www      1876: }
1.254     www      1877: 
1.492     albertel 1878: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1879: 
                   1880: sub allowuploaded {
                   1881:     my ($srcurl,$url)=@_;
                   1882:     $url=&clutter(&declutter($url));
                   1883:     my $dir=$url;
                   1884:     $dir=~s/\/[^\/]+$//;
                   1885:     my %httpref=();
                   1886:     my $httpurl=&hreflocation('',$url);
                   1887:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  1888:     &Apache::lonnet::appenv(\%httpref);
1.254     www      1889: }
1.477     raeburn  1890: 
1.478     albertel 1891: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1892: # input: action, courseID, current domain, intended
1.637     raeburn  1893: #        path to file, source of file, instruction to parse file for objects,
                   1894: #        ref to hash for embedded objects,
                   1895: #        ref to hash for codebase of java objects.
                   1896: #
1.485     raeburn  1897: # output: url to file (if action was uploaddoc), 
                   1898: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1899: #
1.478     albertel 1900: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1901: # course.
1.477     raeburn  1902: #
1.478     albertel 1903: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1904: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1905: #          course's home server.
1.477     raeburn  1906: #
1.478     albertel 1907: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1908: #          be copied from $source (current location) to 
                   1909: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1910: #         and will then be copied to
                   1911: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1912: #         course's home server.
1.485     raeburn  1913: #
1.481     raeburn  1914: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1915: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1916: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1917: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1918: #         in course's home server.
1.637     raeburn  1919: #
1.477     raeburn  1920: 
                   1921: sub process_coursefile {
1.638     albertel 1922:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1923:     my $fetchresult;
1.638     albertel 1924:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1925:     if ($action eq 'propagate') {
1.638     albertel 1926:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1927: 			     $home);
1.481     raeburn  1928:     } else {
1.477     raeburn  1929:         my $fpath = '';
                   1930:         my $fname = $file;
1.478     albertel 1931:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1932:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1933:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1934:         if ($action eq 'copy') {
                   1935:             if ($source eq '') {
                   1936:                 $fetchresult = 'no source file';
                   1937:                 return $fetchresult;
                   1938:             } else {
                   1939:                 my $destination = $filepath.'/'.$fname;
                   1940:                 rename($source,$destination);
                   1941:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1942:                                  $home);
1.481     raeburn  1943:             }
                   1944:         } elsif ($action eq 'uploaddoc') {
                   1945:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1946:             print $fh $env{'form.'.$source};
1.481     raeburn  1947:             close($fh);
1.637     raeburn  1948:             if ($parser eq 'parse') {
1.961     raeburn  1949:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
1.637     raeburn  1950:                 unless ($parse_result eq 'ok') {
                   1951:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1952:                 }
                   1953:             }
1.477     raeburn  1954:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1955:                                  $home);
1.481     raeburn  1956:             if ($fetchresult eq 'ok') {
                   1957:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1958:             } else {
                   1959:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1960:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1961:                 return '/adm/notfound.html';
                   1962:             }
1.477     raeburn  1963:         }
                   1964:     }
1.485     raeburn  1965:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1966:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1967:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1968:     }
                   1969:     return $fetchresult;
                   1970: }
                   1971: 
1.637     raeburn  1972: sub build_filepath {
                   1973:     my ($fpath) = @_;
                   1974:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1975:     unless ($fpath eq '') {
                   1976:         my @parts=split('/',$fpath);
                   1977:         foreach my $part (@parts) {
                   1978:             $filepath.= '/'.$part;
                   1979:             if ((-e $filepath)!=1) {
                   1980:                 mkdir($filepath,0777);
                   1981:             }
                   1982:         }
                   1983:     }
                   1984:     return $filepath;
                   1985: }
                   1986: 
                   1987: sub store_edited_file {
1.638     albertel 1988:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1989:     my $file = $primary_url;
                   1990:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1991:     my $fpath = '';
                   1992:     my $fname = $file;
                   1993:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1994:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1995:     my $filepath = &build_filepath($fpath);
                   1996:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1997:     print $fh $content;
                   1998:     close($fh);
1.638     albertel 1999:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2000:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2001: 			  $home);
1.637     raeburn  2002:     if ($$fetchresult eq 'ok') {
                   2003:         return '/uploaded/'.$fpath.'/'.$fname;
                   2004:     } else {
1.638     albertel 2005:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2006: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2007:         return '/adm/notfound.html';
                   2008:     }
                   2009: }
                   2010: 
1.531     albertel 2011: sub clean_filename {
1.831     albertel 2012:     my ($fname,$args)=@_;
1.315     www      2013: # Replace Windows backslashes by forward slashes
1.257     www      2014:     $fname=~s/\\/\//g;
1.831     albertel 2015:     if (!$args->{'keep_path'}) {
                   2016:         # Get rid of everything but the actual filename
                   2017: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2018:     }
1.315     www      2019: # Replace spaces by underscores
                   2020:     $fname=~s/\s+/\_/g;
                   2021: # Replace all other weird characters by nothing
1.831     albertel 2022:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2023: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2024: # numbers
                   2025:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2026:     return $fname;
                   2027: }
                   2028: 
1.608     albertel 2029: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2030: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 2031: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 2032: #        $coursedoc - if true up to the current course
                   2033: #                     if false
                   2034: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2035: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2036: #        $allfiles - reference to hash for embedded objects
                   2037: #        $codebase - reference to hash for codebase of java objects
                   2038: #        $desuname - username for permanent storage of uploaded file
                   2039: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2040: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2041: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  2042: # 
1.686     albertel 2043: # output: url of file in userspace, or error: <message> 
                   2044: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2045: 
                   2046: 
1.531     albertel 2047: sub userfileupload {
1.860     raeburn  2048:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   2049:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 2050:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2051:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2052:     $fname=&clean_filename($fname);
1.315     www      2053: # See if there is anything left
1.257     www      2054:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2055:     chop($env{'form.'.$formname});
1.523     raeburn  2056:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2057:         my $now = time;
                   2058:         my $filepath = 'tmp/helprequests/'.$now;
                   2059:         my @parts=split(/\//,$filepath);
                   2060:         my $fullpath = $perlvar{'lonDaemons'};
                   2061:         for (my $i=0;$i<@parts;$i++) {
                   2062:             $fullpath .= '/'.$parts[$i];
                   2063:             if ((-e $fullpath)!=1) {
                   2064:                 mkdir($fullpath,0777);
                   2065:             }
                   2066:         }
                   2067:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2068:         print $fh $env{'form.'.$formname};
1.523     raeburn  2069:         close($fh);
1.741     raeburn  2070:         return $fullpath.'/'.$fname;
                   2071:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2072:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2073:                        '_'.$env{'user.domain'}.'/pending';
                   2074:         my @parts=split(/\//,$filepath);
                   2075:         my $fullpath = $perlvar{'lonDaemons'};
                   2076:         for (my $i=0;$i<@parts;$i++) {
                   2077:             $fullpath .= '/'.$parts[$i];
                   2078:             if ((-e $fullpath)!=1) {
                   2079:                 mkdir($fullpath,0777);
                   2080:             }
                   2081:         }
                   2082:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2083:         print $fh $env{'form.'.$formname};
                   2084:         close($fh);
                   2085:         return $fullpath.'/'.$fname;
1.523     raeburn  2086:     }
1.719     banghart 2087:     
1.258     www      2088: # Create the directory if not present
1.493     albertel 2089:     $fname="$subdir/$fname";
1.259     www      2090:     if ($coursedoc) {
1.638     albertel 2091: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2092: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2093:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2094:             return &finishuserfileupload($docuname,$docudom,
                   2095: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  2096: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  2097:         } else {
1.620     albertel 2098:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2099:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2100: 				       $fname,$formname,$parser,
                   2101: 				       $allfiles,$codebase);
1.481     raeburn  2102:         }
1.719     banghart 2103:     } elsif (defined($destuname)) {
                   2104:         my $docuname=$destuname;
                   2105:         my $docudom=$destudom;
1.860     raeburn  2106: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2107: 				     $parser,$allfiles,$codebase,
                   2108:                                      $thumbwidth,$thumbheight);
1.719     banghart 2109:         
1.259     www      2110:     } else {
1.638     albertel 2111:         my $docuname=$env{'user.name'};
                   2112:         my $docudom=$env{'user.domain'};
1.714     raeburn  2113:         if (exists($env{'form.group'})) {
                   2114:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2115:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2116:         }
1.860     raeburn  2117: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2118: 				     $parser,$allfiles,$codebase,
                   2119:                                      $thumbwidth,$thumbheight);
1.259     www      2120:     }
1.271     www      2121: }
                   2122: 
                   2123: sub finishuserfileupload {
1.860     raeburn  2124:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   2125:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  2126:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2127:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  2128:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2129:     $file=$fname;
                   2130:     if ($fname=~m|/|) {
                   2131:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2132: 	$path.=$fnamepath.'/';
                   2133:     }
1.259     www      2134:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2135:     my $count;
                   2136:     for ($count=4;$count<=$#parts;$count++) {
                   2137:         $filepath.="/$parts[$count]";
                   2138:         if ((-e $filepath)!=1) {
                   2139: 	    mkdir($filepath,0777);
                   2140:         }
                   2141:     }
                   2142: # Save the file
                   2143:     {
1.701     albertel 2144: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2145: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2146: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2147: 	    return '/adm/notfound.html';
                   2148: 	}
                   2149: 	if (!print FH ($env{'form.'.$formname})) {
                   2150: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2151: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2152: 	    return '/adm/notfound.html';
                   2153: 	}
1.570     albertel 2154: 	close(FH);
1.258     www      2155:     }
1.637     raeburn  2156:     if ($parser eq 'parse') {
1.961     raeburn  2157:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
1.638     albertel 2158: 						   $codebase);
1.637     raeburn  2159:         unless ($parse_result eq 'ok') {
1.638     albertel 2160:             &logthis('Failed to parse '.$filepath.$file.
                   2161: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  2162:         }
                   2163:     }
1.860     raeburn  2164:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2165:         my $input = $filepath.'/'.$file;
                   2166:         my $output = $filepath.'/'.'tn-'.$file;
                   2167:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2168:         system("convert -sample $thumbsize $input $output");
                   2169:         if (-e $filepath.'/'.'tn-'.$file) {
                   2170:             $fetchthumb  = 1; 
                   2171:         }
                   2172:     }
1.858     raeburn  2173:  
1.259     www      2174: # Notify homeserver to grep it
                   2175: #
1.638     albertel 2176:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 2177:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2178:     if ($fetchresult eq 'ok') {
1.860     raeburn  2179:         if ($fetchthumb) {
                   2180:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2181:             if ($thumbresult ne 'ok') {
                   2182:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2183:                          $docuhome.': '.$thumbresult);
                   2184:             }
                   2185:         }
1.259     www      2186: #
1.258     www      2187: # Return the URL to it
1.494     albertel 2188:         return '/uploaded/'.$path.$file;
1.263     www      2189:     } else {
1.494     albertel 2190:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2191: 		 ': '.$fetchresult);
1.263     www      2192:         return '/adm/notfound.html';
1.858     raeburn  2193:     }
1.493     albertel 2194: }
                   2195: 
1.637     raeburn  2196: sub extract_embedded_items {
1.961     raeburn  2197:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2198:     my @state = ();
                   2199:     my %javafiles = (
                   2200:                       codebase => '',
                   2201:                       code => '',
                   2202:                       archive => ''
                   2203:                     );
                   2204:     my %mediafiles = (
                   2205:                       src => '',
                   2206:                       movie => '',
                   2207:                      );
1.648     raeburn  2208:     my $p;
                   2209:     if ($content) {
                   2210:         $p = HTML::LCParser->new($content);
                   2211:     } else {
1.961     raeburn  2212:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2213:     }
1.641     albertel 2214:     while (my $t=$p->get_token()) {
1.640     albertel 2215: 	if ($t->[0] eq 'S') {
                   2216: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2217: 	    push(@state, $tagname);
1.648     raeburn  2218:             if (lc($tagname) eq 'allow') {
                   2219:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2220:             }
1.640     albertel 2221: 	    if (lc($tagname) eq 'img') {
                   2222: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2223: 	    }
1.886     albertel 2224: 	    if (lc($tagname) eq 'a') {
                   2225: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2226: 	    }
1.645     raeburn  2227:             if (lc($tagname) eq 'script') {
                   2228:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2229:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2230:                 } else {
                   2231:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2232:                 }
                   2233:             }
                   2234:             if (lc($tagname) eq 'link') {
                   2235:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2236:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2237:                 }
                   2238:             }
1.640     albertel 2239: 	    if (lc($tagname) eq 'object' ||
                   2240: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2241: 		foreach my $item (keys(%javafiles)) {
                   2242: 		    $javafiles{$item} = '';
                   2243: 		}
                   2244: 	    }
                   2245: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2246: 		my $name = lc($attr->{'name'});
                   2247: 		foreach my $item (keys(%javafiles)) {
                   2248: 		    if ($name eq $item) {
                   2249: 			$javafiles{$item} = $attr->{'value'};
                   2250: 			last;
                   2251: 		    }
                   2252: 		}
                   2253: 		foreach my $item (keys(%mediafiles)) {
                   2254: 		    if ($name eq $item) {
                   2255: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2256: 			last;
                   2257: 		    }
                   2258: 		}
                   2259: 	    }
                   2260: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2261: 		foreach my $item (keys(%javafiles)) {
                   2262: 		    if ($attr->{$item}) {
                   2263: 			$javafiles{$item} = $attr->{$item};
                   2264: 			last;
                   2265: 		    }
                   2266: 		}
                   2267: 		foreach my $item (keys(%mediafiles)) {
                   2268: 		    if ($attr->{$item}) {
                   2269: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2270: 			last;
                   2271: 		    }
                   2272: 		}
                   2273: 	    }
                   2274: 	} elsif ($t->[0] eq 'E') {
                   2275: 	    my ($tagname) = ($t->[1]);
                   2276: 	    if ($javafiles{'codebase'} ne '') {
                   2277: 		$javafiles{'codebase'} .= '/';
                   2278: 	    }  
                   2279: 	    if (lc($tagname) eq 'applet' ||
                   2280: 		lc($tagname) eq 'object' ||
                   2281: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2282: 		) {
                   2283: 		foreach my $item (keys(%javafiles)) {
                   2284: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2285: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2286: 			&add_filetype($allfiles,$file,$item);
                   2287: 		    }
                   2288: 		}
                   2289: 	    } 
                   2290: 	    pop @state;
                   2291: 	}
                   2292:     }
1.637     raeburn  2293:     return 'ok';
                   2294: }
                   2295: 
1.639     albertel 2296: sub add_filetype {
                   2297:     my ($allfiles,$file,$type)=@_;
                   2298:     if (exists($allfiles->{$file})) {
                   2299: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2300: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2301: 	}
                   2302:     } else {
                   2303: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2304:     }
                   2305: }
                   2306: 
1.493     albertel 2307: sub removeuploadedurl {
                   2308:     my ($url)=@_;
                   2309:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 2310:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2311: }
                   2312: 
                   2313: sub removeuserfile {
                   2314:     my ($docuname,$docudom,$fname)=@_;
                   2315:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2316:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   2317:     if ($result eq 'ok') {
                   2318:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2319:             my $metafile = $fname.'.meta';
                   2320:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2321: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   2322:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2323:             my $sqlresult = 
1.823     albertel 2324:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2325:                                         'portfolio_metadata',$group,
                   2326:                                         'delete');
1.798     raeburn  2327:         }
                   2328:     }
                   2329:     return $result;
1.257     www      2330: }
1.15      www      2331: 
1.530     albertel 2332: sub mkdiruserfile {
                   2333:     my ($docuname,$docudom,$dir)=@_;
                   2334:     my $home=&homeserver($docuname,$docudom);
                   2335:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2336: }
                   2337: 
1.531     albertel 2338: sub renameuserfile {
                   2339:     my ($docuname,$docudom,$old,$new)=@_;
                   2340:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2341:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2342:                         &escape("$old").':'.&escape("$new"),$home);
                   2343:     if ($result eq 'ok') {
                   2344:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2345:             my $oldmeta = $old.'.meta';
                   2346:             my $newmeta = $new.'.meta';
                   2347:             my $metaresult = 
                   2348:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2349: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2350:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2351:             my $sqlresult = 
1.823     albertel 2352:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2353:                                         'portfolio_metadata',$group,
                   2354:                                         'delete');
1.798     raeburn  2355:         }
                   2356:     }
                   2357:     return $result;
1.531     albertel 2358: }
                   2359: 
1.14      www      2360: # ------------------------------------------------------------------------- Log
                   2361: 
                   2362: sub log {
                   2363:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2364:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2365: }
                   2366: 
                   2367: # ------------------------------------------------------------------ Course Log
1.352     www      2368: #
                   2369: # This routine flushes several buffers of non-mission-critical nature
                   2370: #
1.157     www      2371: 
                   2372: sub flushcourselogs {
1.352     www      2373:     &logthis('Flushing log buffers');
                   2374: #
                   2375: # course logs
                   2376: # This is a log of all transactions in a course, which can be used
                   2377: # for data mining purposes
                   2378: #
                   2379: # It also collects the courseid database, which lists last transaction
                   2380: # times and course titles for all courseids
                   2381: #
                   2382:     my %courseidbuffer=();
1.921     raeburn  2383:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2384:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2385: 		          &escape($courselogs{$crsid}),
                   2386: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2387: 	    delete $courselogs{$crsid};
                   2388:         } else {
                   2389:             &logthis('Failed to flush log buffer for '.$crsid);
                   2390:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2391:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2392:                         " exceeded maximum size, deleting.</font>");
                   2393:                delete $courselogs{$crsid};
                   2394:             }
1.352     www      2395:         }
1.920     raeburn  2396:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2397:             'description' => $coursedescrbuf{$crsid},
                   2398:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2399:             'type'        => $coursetypebuf{$crsid},
                   2400:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2401:         };
1.191     harris41 2402:     }
1.352     www      2403: #
                   2404: # Write course id database (reverse lookup) to homeserver of courses 
                   2405: # Is used in pickcourse
                   2406: #
1.840     albertel 2407:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2408:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2409:                                     $courseidbuffer{$crs_home},
                   2410:                                     $crs_home,'timeonly');
1.352     www      2411:     }
                   2412: #
                   2413: # File accesses
                   2414: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2415: #
1.449     matthew  2416:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2417:         if ($entry =~ /___count$/) {
                   2418:             my ($dom,$name);
1.807     albertel 2419:             ($dom,$name,undef)=
1.811     albertel 2420: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2421:             if (! defined($dom) || $dom eq '' || 
                   2422:                 ! defined($name) || $name eq '') {
1.620     albertel 2423:                 my $cid = $env{'request.course.id'};
                   2424:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2425:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2426:             }
1.450     matthew  2427:             my $value = $accesshash{$entry};
                   2428:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2429:             my %temphash=($url => $value);
1.449     matthew  2430:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2431:             if ($result eq 'ok') {
                   2432:                 delete $accesshash{$entry};
                   2433:             } elsif ($result eq 'unknown_cmd') {
                   2434:                 # Target server has old code running on it.
1.450     matthew  2435:                 my %temphash=($entry => $value);
1.449     matthew  2436:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2437:                     delete $accesshash{$entry};
                   2438:                 }
                   2439:             }
                   2440:         } else {
1.811     albertel 2441:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2442:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2443:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2444:                 delete $accesshash{$entry};
                   2445:             }
1.185     www      2446:         }
1.191     harris41 2447:     }
1.352     www      2448: #
                   2449: # Roles
                   2450: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2451: #
1.800     albertel 2452:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2453:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2454: 	    split(/\:/,$entry);
                   2455:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2456:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2457:                 $rudom,$runame) eq 'ok') {
                   2458: 	    delete $userrolehash{$entry};
                   2459:         }
                   2460:     }
1.662     raeburn  2461: #
                   2462: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2463: #
                   2464:     my %domrolebuffer = ();
                   2465:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2466:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2467:         if ($domrolebuffer{$rudom}) {
                   2468:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2469:                       '='.&escape($domainrolehash{$entry});
                   2470:         } else {
                   2471:             $domrolebuffer{$rudom}.=&escape($entry).
                   2472:                       '='.&escape($domainrolehash{$entry});
                   2473:         }
                   2474:         delete $domainrolehash{$entry};
                   2475:     }
                   2476:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2477: 	my %servers = &get_servers($dom,'library');
                   2478: 	foreach my $tryserver (keys(%servers)) {
                   2479: 	    unless (&reply('domroleput:'.$dom.':'.
                   2480: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2481: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2482: 	    }
1.662     raeburn  2483:         }
                   2484:     }
1.186     www      2485:     $dumpcount++;
1.157     www      2486: }
                   2487: 
                   2488: sub courselog {
                   2489:     my $what=shift;
1.158     www      2490:     $what=time.':'.$what;
1.620     albertel 2491:     unless ($env{'request.course.id'}) { return ''; }
                   2492:     $coursedombuf{$env{'request.course.id'}}=
                   2493:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2494:     $coursenumbuf{$env{'request.course.id'}}=
                   2495:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2496:     $coursehombuf{$env{'request.course.id'}}=
                   2497:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2498:     $coursedescrbuf{$env{'request.course.id'}}=
                   2499:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2500:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2501:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2502:     $courseownerbuf{$env{'request.course.id'}}=
                   2503:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2504:     $coursetypebuf{$env{'request.course.id'}}=
                   2505:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2506:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2507: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2508:     } else {
1.620     albertel 2509: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2510:     }
1.620     albertel 2511:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2512: 	&flushcourselogs();
                   2513:     }
1.158     www      2514: }
                   2515: 
                   2516: sub courseacclog {
                   2517:     my $fnsymb=shift;
1.620     albertel 2518:     unless ($env{'request.course.id'}) { return ''; }
                   2519:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2520:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2521:         $what.=':POST';
1.583     matthew  2522:         # FIXME: Probably ought to escape things....
1.800     albertel 2523: 	foreach my $key (keys(%env)) {
                   2524:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2525:                 my $formitem = $1;
                   2526:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2527:                     $what.=':'.$formitem.'='.$env{$key};
                   2528:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2529:                     $what.=':'.$formitem.'='.$env{$key};
                   2530:                 }
1.158     www      2531:             }
1.191     harris41 2532:         }
1.583     matthew  2533:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2534:         # FIXME: We should not be depending on a form parameter that someone
                   2535:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2536:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2537:             $what.= ':POST';
                   2538:             # FIXME: Probably ought to escape things....
                   2539:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2540:                                  'crsdiscuss') {
1.620     albertel 2541:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2542:             }
                   2543:         }
1.158     www      2544:     }
                   2545:     &courselog($what);
1.149     www      2546: }
                   2547: 
1.185     www      2548: sub countacc {
                   2549:     my $url=&declutter(shift);
1.458     matthew  2550:     return if (! defined($url) || $url eq '');
1.620     albertel 2551:     unless ($env{'request.course.id'}) { return ''; }
                   2552:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2553:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2554:     $accesshash{$key}++;
1.185     www      2555: }
1.349     www      2556: 
1.361     www      2557: sub linklog {
                   2558:     my ($from,$to)=@_;
                   2559:     $from=&declutter($from);
                   2560:     $to=&declutter($to);
                   2561:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2562:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2563: }
                   2564:   
1.349     www      2565: sub userrolelog {
                   2566:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2567:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2568:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2569:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2570:         ($trole=~/^ta/)) {
1.350     www      2571:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2572:        $userrolehash
                   2573:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2574:                     =$tend.':'.$tstart;
1.662     raeburn  2575:     }
1.898     albertel 2576:     if (($env{'request.role'} =~ /dc\./) &&
                   2577: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2578: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2579: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2580:        $userrolehash
                   2581:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2582:                     =$tend.':'.$tstart;
                   2583:     }
1.662     raeburn  2584:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2585:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2586:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2587:         ($trole=~/^sc/)) {
                   2588:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2589:        $domainrolehash
                   2590:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2591:                     = $tend.':'.$tstart;
                   2592:     }
1.351     www      2593: }
                   2594: 
1.957     raeburn  2595: sub courserolelog {
                   2596:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2597:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2598:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2599:         ($trole eq 'ta') || ($trole eq 'st') ||
                   2600:         ($trole=~/^cr/) || ($trole eq 'gr')) {
                   2601:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2602:             my $cdom = $1;
                   2603:             my $cnum = $2;
                   2604:             my $sec = $3;
                   2605:             my $namespace = 'rolelog';
                   2606:             my %storehash = (
                   2607:                                role    => $trole,
                   2608:                                start   => $tstart,
                   2609:                                end     => $tend,
                   2610:                                selfenroll => $selfenroll,
                   2611:                                context    => $context,
                   2612:                             );
                   2613:             if ($trole eq 'gr') {
                   2614:                 $namespace = 'groupslog';
                   2615:                 $storehash{'group'} = $sec;
                   2616:             } else {
                   2617:                 $storehash{'section'} = $sec;
                   2618:             }
                   2619:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
                   2620:         }
                   2621:     }
                   2622:     return;
                   2623: }
                   2624: 
1.351     www      2625: sub get_course_adv_roles {
1.948     raeburn  2626:     my ($cid,$codes) = @_;
1.620     albertel 2627:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2628:     my %coursehash=&coursedescription($cid);
1.470     www      2629:     my %nothide=();
1.800     albertel 2630:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2631:         if ($user !~ /:/) {
                   2632: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2633:         } else {
                   2634:             $nothide{$user}=1;
                   2635:         }
1.470     www      2636:     }
1.351     www      2637:     my %returnhash=();
                   2638:     my %dumphash=
                   2639:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2640:     my $now=time;
1.800     albertel 2641:     foreach my $entry (keys %dumphash) {
                   2642: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2643:         if (($tstart) && ($tstart<0)) { next; }
                   2644:         if (($tend) && ($tend<$now)) { next; }
                   2645:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2646:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2647: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2648: 	if ((&privileged($username,$domain)) && 
                   2649: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2650: 	if ($role eq 'cr') { next; }
1.948     raeburn  2651:         if ($codes) {
                   2652:             if ($section) { $role .= ':'.$section; }
                   2653:             if ($returnhash{$role}) {
                   2654:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2655:             } else {
                   2656:                 $returnhash{$role}=$username.':'.$domain;
                   2657:             }
1.351     www      2658:         } else {
1.948     raeburn  2659:             my $key=&plaintext($role);
1.973     bisitz   2660:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  2661:             if ($returnhash{$key}) {
                   2662: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2663:             } else {
                   2664:                 $returnhash{$key}=$username.':'.$domain;
                   2665:             }
1.351     www      2666:         }
1.948     raeburn  2667:     }
1.400     www      2668:     return %returnhash;
                   2669: }
                   2670: 
                   2671: sub get_my_roles {
1.937     raeburn  2672:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2673:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2674:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2675:     my (%dumphash,%nothide);
1.858     raeburn  2676:     if ($context eq 'userroles') { 
                   2677:         %dumphash = &dump('roles',$udom,$uname);
                   2678:     } else {
                   2679:         %dumphash=
1.400     www      2680:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2681:         if ($hidepriv) {
                   2682:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2683:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2684:                 if ($user !~ /:/) {
                   2685:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2686:                 } else {
                   2687:                     $nothide{$user} = 1;
                   2688:                 }
                   2689:             }
                   2690:         }
1.858     raeburn  2691:     }
1.400     www      2692:     my %returnhash=();
                   2693:     my $now=time;
1.800     albertel 2694:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2695:         my ($role,$tend,$tstart);
                   2696:         if ($context eq 'userroles') {
                   2697: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2698:         } else {
                   2699:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2700:         }
1.400     www      2701:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2702:         my $status = 'active';
1.939     raeburn  2703:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2704:             $status = 'previous';
                   2705:         } 
                   2706:         if (($tstart) && ($now<$tstart)) {
                   2707:             $status = 'future';
                   2708:         }
                   2709:         if (ref($types) eq 'ARRAY') {
                   2710:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2711:                 next;
                   2712:             } 
                   2713:         } else {
                   2714:             if ($status ne 'active') {
                   2715:                 next;
                   2716:             }
                   2717:         }
1.867     raeburn  2718:         my ($rolecode,$username,$domain,$section,$area);
                   2719:         if ($context eq 'userroles') {
                   2720:             ($area,$rolecode) = split(/_/,$entry);
                   2721:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2722:         } else {
                   2723:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2724:         }
1.832     raeburn  2725:         if (ref($roledoms) eq 'ARRAY') {
                   2726:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2727:                 next;
                   2728:             }
                   2729:         }
                   2730:         if (ref($roles) eq 'ARRAY') {
                   2731:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2732:                 if ($role =~ /^cr\//) {
                   2733:                     if (!grep(/^cr$/,@{$roles})) {
                   2734:                         next;
                   2735:                     }
                   2736:                 } else {
                   2737:                     next;
                   2738:                 }
1.832     raeburn  2739:             }
1.867     raeburn  2740:         }
1.937     raeburn  2741:         if ($hidepriv) {
                   2742:             if ((&privileged($username,$domain)) &&
                   2743:                 (!$nothide{$username.':'.$domain})) { 
                   2744:                 next;
                   2745:             }
                   2746:         }
1.933     raeburn  2747:         if ($withsec) {
                   2748:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2749:                 $tstart.':'.$tend;
                   2750:         } else {
                   2751:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2752:         }
1.832     raeburn  2753:     }
1.373     www      2754:     return %returnhash;
1.399     www      2755: }
                   2756: 
                   2757: # ----------------------------------------------------- Frontpage Announcements
                   2758: #
                   2759: #
                   2760: 
                   2761: sub postannounce {
                   2762:     my ($server,$text)=@_;
1.844     albertel 2763:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2764:     unless ($text=~/\w/) { $text=''; }
                   2765:     return &reply('setannounce:'.&escape($text),$server);
                   2766: }
                   2767: 
                   2768: sub getannounce {
1.448     albertel 2769: 
                   2770:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2771: 	my $announcement='';
1.800     albertel 2772: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2773: 	close($fh);
1.399     www      2774: 	if ($announcement=~/\w/) { 
                   2775: 	    return 
                   2776:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2777:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2778: 	} else {
                   2779: 	    return '';
                   2780: 	}
                   2781:     } else {
                   2782: 	return '';
                   2783:     }
1.351     www      2784: }
1.353     www      2785: 
                   2786: # ---------------------------------------------------------- Course ID routines
                   2787: # Deal with domain's nohist_courseid.db files
                   2788: #
                   2789: 
                   2790: sub courseidput {
1.921     raeburn  2791:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2792:     my $outcome;
                   2793:     if ($caller eq 'timeonly') {
                   2794:         my $cids = '';
                   2795:         foreach my $item (keys(%$storehash)) {
                   2796:             $cids.=&escape($item).'&';
                   2797:         }
                   2798:         $cids=~s/\&$//;
                   2799:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2800:                           $coursehome);       
                   2801:     } else {
                   2802:         my $items = '';
                   2803:         foreach my $item (keys(%$storehash)) {
                   2804:             $items.= &escape($item).'='.
                   2805:                      &freeze_escape($$storehash{$item}).'&';
                   2806:         }
                   2807:         $items=~s/\&$//;
                   2808:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2809:                           $coursehome);
1.918     raeburn  2810:     }
                   2811:     if ($outcome eq 'unknown_cmd') {
                   2812:         my $what;
                   2813:         foreach my $cid (keys(%$storehash)) {
                   2814:             $what .= &escape($cid).'=';
1.921     raeburn  2815:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2816:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2817:             }
                   2818:             $what =~ s/\:$/&/;
                   2819:         }
                   2820:         $what =~ s/\&$//;  
                   2821:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2822:     } else {
                   2823:         return $outcome;
                   2824:     }
1.353     www      2825: }
                   2826: 
                   2827: sub courseiddump {
1.921     raeburn  2828:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  2829:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.962     raeburn  2830:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
1.918     raeburn  2831:     my $as_hash = 1;
                   2832:     my %returnhash;
                   2833:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2834:     my %libserv = &all_library();
                   2835:     foreach my $tryserver (keys(%libserv)) {
                   2836:         if ( (  $hostidflag == 1 
                   2837: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2838: 	     || (!defined($hostidflag)) ) {
                   2839: 
1.918     raeburn  2840: 	    if (($domfilter eq '') ||
                   2841: 		(&host_domain($tryserver) eq $domfilter)) {
                   2842:                 my $rep = 
                   2843:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2844:                          $sincefilter.':'.&escape($descfilter).':'.
                   2845:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2846:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  2847:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  2848:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   2849:                          $showhidden.':'.$caller,$tryserver);
1.918     raeburn  2850:                 my @pairs=split(/\&/,$rep);
                   2851:                 foreach my $item (@pairs) {
                   2852:                     my ($key,$value)=split(/\=/,$item,2);
                   2853:                     $key = &unescape($key);
                   2854:                     next if ($key =~ /^error: 2 /);
                   2855:                     my $result = &thaw_unescape($value);
                   2856:                     if (ref($result) eq 'HASH') {
                   2857:                         $returnhash{$key}=$result;
                   2858:                     } else {
1.921     raeburn  2859:                         my @responses = split(/:/,$value);
                   2860:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  2861:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  2862:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  2863:                         }
                   2864:                     } 
1.353     www      2865:                 }
                   2866:             }
                   2867:         }
                   2868:     }
                   2869:     return %returnhash;
                   2870: }
                   2871: 
1.658     raeburn  2872: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2873: 
                   2874: sub dcmailput {
1.685     raeburn  2875:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2876:     my $status = &Apache::lonnet::critical(
1.740     www      2877:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2878:        &escape($message),$server);
1.662     raeburn  2879:     return $status;
                   2880: }
                   2881: 
1.658     raeburn  2882: sub dcmaildump {
                   2883:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2884:     my %returnhash=();
1.846     albertel 2885: 
                   2886:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2887:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2888:                                                          &escape($enddate).':';
                   2889: 	my @esc_senders=map { &escape($_)} @$senders;
                   2890: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2891: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2892:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2893:             if (($key) && ($value)) {
                   2894:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2895:             }
                   2896:         }
                   2897:     }
                   2898:     return %returnhash;
                   2899: }
1.662     raeburn  2900: # ---------------------------------------------------------- Domain roles
                   2901: 
                   2902: sub get_domain_roles {
                   2903:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2904:     if (undef($startdate) || $startdate eq '') {
                   2905:         $startdate = '.';
                   2906:     }
                   2907:     if (undef($enddate) || $enddate eq '') {
                   2908:         $enddate = '.';
                   2909:     }
1.922     raeburn  2910:     my $rolelist;
                   2911:     if (ref($roles) eq 'ARRAY') {
                   2912:         $rolelist = join(':',@{$roles});
                   2913:     }
1.662     raeburn  2914:     my %personnel = ();
1.841     albertel 2915: 
                   2916:     my %servers = &get_servers($dom,'library');
                   2917:     foreach my $tryserver (keys(%servers)) {
                   2918: 	%{$personnel{$tryserver}}=();
                   2919: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2920: 					    &escape($startdate).':'.
                   2921: 					    &escape($enddate).':'.
                   2922: 					    &escape($rolelist), $tryserver))) {
                   2923: 	    my ($key,$value) = split(/\=/,$line,2);
                   2924: 	    if (($key) && ($value)) {
                   2925: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2926: 	    }
                   2927: 	}
1.662     raeburn  2928:     }
                   2929:     return %personnel;
                   2930: }
1.658     raeburn  2931: 
1.149     www      2932: # ----------------------------------------------------------- Check out an item
                   2933: 
1.504     albertel 2934: sub get_first_access {
                   2935:     my ($type,$argsymb)=@_;
1.790     albertel 2936:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2937:     if ($argsymb) { $symb=$argsymb; }
                   2938:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 2939:     if ($type eq 'course') {
                   2940: 	$res='course';
                   2941:     } elsif ($type eq 'map') {
1.588     albertel 2942: 	$res=&symbread($map);
                   2943:     } else {
                   2944: 	$res=$symb;
                   2945:     }
                   2946:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2947:     return $times{"$courseid\0$res"};
1.504     albertel 2948: }
                   2949: 
                   2950: sub set_first_access {
                   2951:     my ($type)=@_;
1.790     albertel 2952:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2953:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 2954:     if ($type eq 'course') {
                   2955: 	$res='course';
                   2956:     } elsif ($type eq 'map') {
1.588     albertel 2957: 	$res=&symbread($map);
                   2958:     } else {
                   2959: 	$res=$symb;
                   2960:     }
                   2961:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2962:     if (!$firstaccess) {
1.588     albertel 2963: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2964:     }
                   2965:     return 'already_set';
1.504     albertel 2966: }
                   2967: 
1.149     www      2968: sub checkout {
                   2969:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2970:     my $now=time;
                   2971:     my $lonhost=$perlvar{'lonHostID'};
                   2972:     my $infostr=&escape(
1.234     www      2973:                  'CHECKOUTTOKEN&'.
1.149     www      2974:                  $tuname.'&'.
                   2975:                  $tudom.'&'.
                   2976:                  $tcrsid.'&'.
                   2977:                  $symb.'&'.
                   2978: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2979:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2980:     if ($token=~/^error\:/) { 
1.672     albertel 2981:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2982:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2983:                  "</font>");
                   2984:         return ''; 
                   2985:     }
                   2986: 
1.149     www      2987:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2988:     $token=~tr/a-z/A-Z/;
                   2989: 
1.153     www      2990:     my %infohash=('resource.0.outtoken' => $token,
                   2991:                   'resource.0.checkouttime' => $now,
                   2992:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2993: 
                   2994:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2995:        return '';
1.151     www      2996:     } else {
1.672     albertel 2997:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2998:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2999:                  "</font>");
1.149     www      3000:     }    
                   3001: 
                   3002:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3003:                          &escape('Checkout '.$infostr.' - '.
                   3004:                                                  $token)) ne 'ok') {
                   3005: 	return '';
1.151     www      3006:     } else {
1.672     albertel 3007:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3008:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3009:                  "</font>");
1.149     www      3010:     }
1.151     www      3011:     return $token;
1.149     www      3012: }
                   3013: 
                   3014: # ------------------------------------------------------------ Check in an item
                   3015: 
                   3016: sub checkin {
                   3017:     my $token=shift;
1.150     www      3018:     my $now=time;
                   3019:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3020:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3021:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3022:     $dtoken=~s/\W/\_/g;
1.234     www      3023:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3024:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3025: 
1.154     www      3026:     unless (($tuname) && ($tudom)) {
                   3027:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3028:         return '';
                   3029:     }
                   3030:     
                   3031:     unless (&allowed('mgr',$tcrsid)) {
                   3032:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3033:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3034:         return '';
                   3035:     }
                   3036: 
1.153     www      3037:     my %infohash=('resource.0.intoken' => $token,
                   3038:                   'resource.0.checkintime' => $now,
                   3039:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3040: 
                   3041:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3042:        return '';
                   3043:     }    
                   3044: 
                   3045:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3046:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3047: 	return '';
                   3048:     }
                   3049: 
                   3050:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3051: }
                   3052: 
                   3053: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3054: 
                   3055: sub expirespread {
                   3056:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3057:     my $cid=$env{'request.course.id'}; 
1.110     www      3058:     if ($cid) {
                   3059:        my $now=time;
                   3060:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3061:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3062:                             $env{'course.'.$cid.'.num'}.
1.110     www      3063: 	        	    ':nohist_expirationdates:'.
                   3064:                             &escape($key).'='.$now,
1.620     albertel 3065:                             $env{'course.'.$cid.'.home'})
1.110     www      3066:     }
                   3067:     return 'ok';
1.14      www      3068: }
                   3069: 
1.109     www      3070: # ----------------------------------------------------- Devalidate Spreadsheets
                   3071: 
                   3072: sub devalidate {
1.325     www      3073:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3074:     my $cid=$env{'request.course.id'}; 
1.109     www      3075:     if ($cid) {
1.391     matthew  3076:         # delete the stored spreadsheets for
                   3077:         # - the student level sheet of this user in course's homespace
                   3078:         # - the assessment level sheet for this resource 
                   3079:         #   for this user in user's homespace
1.553     albertel 3080: 	# - current conditional state info
1.325     www      3081: 	my $key=$uname.':'.$udom.':';
1.109     www      3082:         my $status=
1.299     matthew  3083: 	    &del('nohist_calculatedsheets',
1.391     matthew  3084: 		 [$key.'studentcalc:'],
1.620     albertel 3085: 		 $env{'course.'.$cid.'.domain'},
                   3086: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3087: 		.' '.
                   3088: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3089: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3090:         unless ($status eq 'ok ok') {
                   3091:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3092:                     $uname.' at '.$udom.' for '.
1.109     www      3093: 		    $symb.': '.$status);
1.133     albertel 3094:         }
1.553     albertel 3095: 	&delenv('user.state.'.$cid);
1.109     www      3096:     }
                   3097: }
                   3098: 
1.265     albertel 3099: sub get_scalar {
                   3100:     my ($string,$end) = @_;
                   3101:     my $value;
                   3102:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3103: 	$value = $1;
                   3104:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3105: 	$value = $1;
                   3106:     }
                   3107:     return &unescape($value);
                   3108: }
                   3109: 
                   3110: sub array2str {
                   3111:   my (@array) = @_;
                   3112:   my $result=&arrayref2str(\@array);
                   3113:   $result=~s/^__ARRAY_REF__//;
                   3114:   $result=~s/__END_ARRAY_REF__$//;
                   3115:   return $result;
                   3116: }
                   3117: 
1.204     albertel 3118: sub arrayref2str {
                   3119:   my ($arrayref) = @_;
1.265     albertel 3120:   my $result='__ARRAY_REF__';
1.204     albertel 3121:   foreach my $elem (@$arrayref) {
1.265     albertel 3122:     if(ref($elem) eq 'ARRAY') {
                   3123:       $result.=&arrayref2str($elem).'&';
                   3124:     } elsif(ref($elem) eq 'HASH') {
                   3125:       $result.=&hashref2str($elem).'&';
                   3126:     } elsif(ref($elem)) {
                   3127:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3128:     } else {
                   3129:       $result.=&escape($elem).'&';
                   3130:     }
                   3131:   }
                   3132:   $result=~s/\&$//;
1.265     albertel 3133:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3134:   return $result;
                   3135: }
                   3136: 
1.168     albertel 3137: sub hash2str {
1.204     albertel 3138:   my (%hash) = @_;
                   3139:   my $result=&hashref2str(\%hash);
1.265     albertel 3140:   $result=~s/^__HASH_REF__//;
                   3141:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3142:   return $result;
                   3143: }
                   3144: 
                   3145: sub hashref2str {
                   3146:   my ($hashref)=@_;
1.265     albertel 3147:   my $result='__HASH_REF__';
1.800     albertel 3148:   foreach my $key (sort(keys(%$hashref))) {
                   3149:     if (ref($key) eq 'ARRAY') {
                   3150:       $result.=&arrayref2str($key).'=';
                   3151:     } elsif (ref($key) eq 'HASH') {
                   3152:       $result.=&hashref2str($key).'=';
                   3153:     } elsif (ref($key)) {
1.265     albertel 3154:       $result.='=';
1.800     albertel 3155:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3156:     } else {
1.800     albertel 3157: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3158:     }
                   3159: 
1.800     albertel 3160:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3161:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3162:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3163:       $result.=&hashref2str($hashref->{$key}).'&';
                   3164:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3165:        $result.='&';
1.800     albertel 3166:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3167:     } else {
1.800     albertel 3168:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3169:     }
                   3170:   }
1.168     albertel 3171:   $result=~s/\&$//;
1.265     albertel 3172:   $result .= '__END_HASH_REF__';
1.168     albertel 3173:   return $result;
                   3174: }
                   3175: 
                   3176: sub str2hash {
1.265     albertel 3177:     my ($string)=@_;
                   3178:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3179:     return %$hash;
                   3180: }
                   3181: 
                   3182: sub str2hashref {
1.168     albertel 3183:   my ($string) = @_;
1.265     albertel 3184: 
                   3185:   my %hash;
                   3186: 
                   3187:   if($string !~ /^__HASH_REF__/) {
                   3188:       if (! ($string eq '' || !defined($string))) {
                   3189: 	  $hash{'error'}='Not hash reference';
                   3190:       }
                   3191:       return (\%hash, $string);
                   3192:   }
                   3193: 
                   3194:   $string =~ s/^__HASH_REF__//;
                   3195: 
                   3196:   while($string !~ /^__END_HASH_REF__/) {
                   3197:       #key
                   3198:       my $key='';
                   3199:       if($string =~ /^__HASH_REF__/) {
                   3200:           ($key, $string)=&str2hashref($string);
                   3201:           if(defined($key->{'error'})) {
                   3202:               $hash{'error'}='Bad data';
                   3203:               return (\%hash, $string);
                   3204:           }
                   3205:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3206:           ($key, $string)=&str2arrayref($string);
                   3207:           if($key->[0] eq 'Array reference error') {
                   3208:               $hash{'error'}='Bad data';
                   3209:               return (\%hash, $string);
                   3210:           }
                   3211:       } else {
                   3212:           $string =~ s/^(.*?)=//;
1.267     albertel 3213: 	  $key=&unescape($1);
1.265     albertel 3214:       }
                   3215:       $string =~ s/^=//;
                   3216: 
                   3217:       #value
                   3218:       my $value='';
                   3219:       if($string =~ /^__HASH_REF__/) {
                   3220:           ($value, $string)=&str2hashref($string);
                   3221:           if(defined($value->{'error'})) {
                   3222:               $hash{'error'}='Bad data';
                   3223:               return (\%hash, $string);
                   3224:           }
                   3225:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3226:           ($value, $string)=&str2arrayref($string);
                   3227:           if($value->[0] eq 'Array reference error') {
                   3228:               $hash{'error'}='Bad data';
                   3229:               return (\%hash, $string);
                   3230:           }
                   3231:       } else {
                   3232: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3233:       }
                   3234:       $string =~ s/^&//;
                   3235: 
                   3236:       $hash{$key}=$value;
1.204     albertel 3237:   }
1.265     albertel 3238: 
                   3239:   $string =~ s/^__END_HASH_REF__//;
                   3240: 
                   3241:   return (\%hash, $string);
1.204     albertel 3242: }
                   3243: 
                   3244: sub str2array {
1.265     albertel 3245:     my ($string)=@_;
                   3246:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3247:     return @$array;
                   3248: }
                   3249: 
                   3250: sub str2arrayref {
1.204     albertel 3251:   my ($string) = @_;
1.265     albertel 3252:   my @array;
                   3253: 
                   3254:   if($string !~ /^__ARRAY_REF__/) {
                   3255:       if (! ($string eq '' || !defined($string))) {
                   3256: 	  $array[0]='Array reference error';
                   3257:       }
                   3258:       return (\@array, $string);
                   3259:   }
                   3260: 
                   3261:   $string =~ s/^__ARRAY_REF__//;
                   3262: 
                   3263:   while($string !~ /^__END_ARRAY_REF__/) {
                   3264:       my $value='';
                   3265:       if($string =~ /^__HASH_REF__/) {
                   3266:           ($value, $string)=&str2hashref($string);
                   3267:           if(defined($value->{'error'})) {
                   3268:               $array[0] ='Array reference error';
                   3269:               return (\@array, $string);
                   3270:           }
                   3271:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3272:           ($value, $string)=&str2arrayref($string);
                   3273:           if($value->[0] eq 'Array reference error') {
                   3274:               $array[0] ='Array reference error';
                   3275:               return (\@array, $string);
                   3276:           }
                   3277:       } else {
                   3278: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3279:       }
                   3280:       $string =~ s/^&//;
                   3281: 
                   3282:       push(@array, $value);
1.191     harris41 3283:   }
1.265     albertel 3284: 
                   3285:   $string =~ s/^__END_ARRAY_REF__//;
                   3286: 
                   3287:   return (\@array, $string);
1.168     albertel 3288: }
                   3289: 
1.167     albertel 3290: # -------------------------------------------------------------------Temp Store
                   3291: 
1.168     albertel 3292: sub tmpreset {
                   3293:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3294:   if (!$symb) {
                   3295:     $symb=&symbread();
1.620     albertel 3296:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3297:   }
                   3298:   $symb=escape($symb);
                   3299: 
1.620     albertel 3300:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3301:   $namespace=~s/\//\_/g;
                   3302:   $namespace=~s/\W//g;
                   3303: 
1.620     albertel 3304:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3305:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3306:   if ($domain eq 'public' && $stuname eq 'public') {
                   3307:       $stuname=$ENV{'REMOTE_ADDR'};
                   3308:   }
1.168     albertel 3309:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3310:   my %hash;
                   3311:   if (tie(%hash,'GDBM_File',
                   3312: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3313: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3314:     foreach my $key (keys %hash) {
1.180     albertel 3315:       if ($key=~ /:$symb/) {
1.168     albertel 3316: 	delete($hash{$key});
                   3317:       }
                   3318:     }
                   3319:   }
                   3320: }
                   3321: 
1.167     albertel 3322: sub tmpstore {
1.168     albertel 3323:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3324: 
                   3325:   if (!$symb) {
                   3326:     $symb=&symbread();
1.620     albertel 3327:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3328:   }
                   3329:   $symb=escape($symb);
                   3330: 
                   3331:   if (!$namespace) {
                   3332:     # I don't think we would ever want to store this for a course.
                   3333:     # it seems this will only be used if we don't have a course.
1.620     albertel 3334:     #$namespace=$env{'request.course.id'};
1.168     albertel 3335:     #if (!$namespace) {
1.620     albertel 3336:       $namespace=$env{'request.state'};
1.168     albertel 3337:     #}
                   3338:   }
                   3339:   $namespace=~s/\//\_/g;
                   3340:   $namespace=~s/\W//g;
1.620     albertel 3341:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3342:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3343:   if ($domain eq 'public' && $stuname eq 'public') {
                   3344:       $stuname=$ENV{'REMOTE_ADDR'};
                   3345:   }
1.168     albertel 3346:   my $now=time;
                   3347:   my %hash;
                   3348:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3349:   if (tie(%hash,'GDBM_File',
                   3350: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3351: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3352:     $hash{"version:$symb"}++;
                   3353:     my $version=$hash{"version:$symb"};
                   3354:     my $allkeys=''; 
                   3355:     foreach my $key (keys(%$storehash)) {
                   3356:       $allkeys.=$key.':';
1.591     albertel 3357:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3358:     }
                   3359:     $hash{"$version:$symb:timestamp"}=$now;
                   3360:     $allkeys.='timestamp';
                   3361:     $hash{"$version:keys:$symb"}=$allkeys;
                   3362:     if (untie(%hash)) {
                   3363:       return 'ok';
                   3364:     } else {
                   3365:       return "error:$!";
                   3366:     }
                   3367:   } else {
                   3368:     return "error:$!";
                   3369:   }
                   3370: }
1.167     albertel 3371: 
1.168     albertel 3372: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3373: 
1.168     albertel 3374: sub tmprestore {
                   3375:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3376: 
1.168     albertel 3377:   if (!$symb) {
                   3378:     $symb=&symbread();
1.620     albertel 3379:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3380:   }
                   3381:   $symb=escape($symb);
                   3382: 
1.620     albertel 3383:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3384: 
1.620     albertel 3385:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3386:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3387:   if ($domain eq 'public' && $stuname eq 'public') {
                   3388:       $stuname=$ENV{'REMOTE_ADDR'};
                   3389:   }
1.168     albertel 3390:   my %returnhash;
                   3391:   $namespace=~s/\//\_/g;
                   3392:   $namespace=~s/\W//g;
                   3393:   my %hash;
                   3394:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3395:   if (tie(%hash,'GDBM_File',
                   3396: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3397: 	  &GDBM_READER(),0640)) {
1.168     albertel 3398:     my $version=$hash{"version:$symb"};
                   3399:     $returnhash{'version'}=$version;
                   3400:     my $scope;
                   3401:     for ($scope=1;$scope<=$version;$scope++) {
                   3402:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3403:       my @keys=split(/:/,$vkeys);
                   3404:       my $key;
                   3405:       $returnhash{"$scope:keys"}=$vkeys;
                   3406:       foreach $key (@keys) {
1.591     albertel 3407: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3408: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3409:       }
                   3410:     }
1.168     albertel 3411:     if (!(untie(%hash))) {
                   3412:       return "error:$!";
                   3413:     }
                   3414:   } else {
                   3415:     return "error:$!";
                   3416:   }
                   3417:   return %returnhash;
1.167     albertel 3418: }
                   3419: 
1.9       www      3420: # ----------------------------------------------------------------------- Store
                   3421: 
                   3422: sub store {
1.124     www      3423:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3424:     my $home='';
                   3425: 
1.168     albertel 3426:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3427: 
1.213     www      3428:     $symb=&symbclean($symb);
1.122     albertel 3429:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3430: 
1.620     albertel 3431:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3432:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3433: 
                   3434:     &devalidate($symb,$stuname,$domain);
1.109     www      3435: 
                   3436:     $symb=escape($symb);
1.187     www      3437:     if (!$namespace) { 
1.620     albertel 3438:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3439:           return ''; 
                   3440:        } 
                   3441:     }
1.620     albertel 3442:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3443: 
                   3444:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3445:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3446: 
1.12      www      3447:     my $namevalue='';
1.800     albertel 3448:     foreach my $key (keys(%$storehash)) {
                   3449:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3450:     }
1.12      www      3451:     $namevalue=~s/\&$//;
1.187     www      3452:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3453:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3454: }
                   3455: 
1.47      www      3456: # -------------------------------------------------------------- Critical Store
                   3457: 
                   3458: sub cstore {
1.124     www      3459:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3460:     my $home='';
                   3461: 
1.168     albertel 3462:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3463: 
1.213     www      3464:     $symb=&symbclean($symb);
1.122     albertel 3465:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3466: 
1.620     albertel 3467:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3468:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3469: 
                   3470:     &devalidate($symb,$stuname,$domain);
1.109     www      3471: 
                   3472:     $symb=escape($symb);
1.187     www      3473:     if (!$namespace) { 
1.620     albertel 3474:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3475:           return ''; 
                   3476:        } 
                   3477:     }
1.620     albertel 3478:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3479: 
                   3480:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3481:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3482: 
1.47      www      3483:     my $namevalue='';
1.800     albertel 3484:     foreach my $key (keys(%$storehash)) {
                   3485:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3486:     }
1.47      www      3487:     $namevalue=~s/\&$//;
1.187     www      3488:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3489:     return critical
                   3490:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3491: }
                   3492: 
1.9       www      3493: # --------------------------------------------------------------------- Restore
                   3494: 
                   3495: sub restore {
1.124     www      3496:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3497:     my $home='';
                   3498: 
1.168     albertel 3499:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3500: 
1.122     albertel 3501:     if (!$symb) {
                   3502:       unless ($symb=escape(&symbread())) { return ''; }
                   3503:     } else {
1.213     www      3504:       $symb=&escape(&symbclean($symb));
1.122     albertel 3505:     }
1.188     www      3506:     if (!$namespace) { 
1.620     albertel 3507:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3508:           return ''; 
                   3509:        } 
                   3510:     }
1.620     albertel 3511:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3512:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3513:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3514:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3515: 
1.12      www      3516:     my %returnhash=();
1.800     albertel 3517:     foreach my $line (split(/\&/,$answer)) {
                   3518: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3519:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3520:     }
1.75      www      3521:     my $version;
                   3522:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3523:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3524:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3525:        }
1.75      www      3526:     }
1.13      www      3527:     return %returnhash;
1.34      www      3528: }
                   3529: 
                   3530: # ---------------------------------------------------------- Course Description
                   3531: 
                   3532: sub coursedescription {
1.731     albertel 3533:     my ($courseid,$args)=@_;
1.34      www      3534:     $courseid=~s/^\///;
1.49      www      3535:     $courseid=~s/\_/\//g;
1.34      www      3536:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3537:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3538:     my $normalid=$cdomain.'_'.$cnum;
                   3539:     # need to always cache even if we get errors otherwise we keep 
                   3540:     # trying and trying and trying to get the course description.
                   3541:     my %envhash=();
                   3542:     my %returnhash=();
1.731     albertel 3543:     
                   3544:     my $expiretime=600;
                   3545:     if ($env{'request.course.id'} eq $normalid) {
                   3546: 	$expiretime=120;
                   3547:     }
                   3548: 
                   3549:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3550:     if (!$args->{'freshen_cache'}
                   3551: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3552: 	foreach my $key (keys(%env)) {
                   3553: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3554: 	    my ($setting) = $1;
                   3555: 	    $returnhash{$setting} = $env{$key};
                   3556: 	}
                   3557: 	return %returnhash;
                   3558:     }
                   3559: 
                   3560:     # get the data agin
                   3561:     if (!$args->{'one_time'}) {
                   3562: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3563:     }
1.811     albertel 3564: 
1.34      www      3565:     if ($chome ne 'no_host') {
1.302     albertel 3566:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3567:        if (!exists($returnhash{'con_lost'})) {
                   3568:            $returnhash{'home'}= $chome;
                   3569: 	   $returnhash{'domain'} = $cdomain;
                   3570: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3571:            if (!defined($returnhash{'type'})) {
                   3572:                $returnhash{'type'} = 'Course';
                   3573:            }
1.130     albertel 3574:            while (my ($name,$value) = each %returnhash) {
1.53      www      3575:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3576:            }
1.270     www      3577:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3578:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3579: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3580:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3581:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3582:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3583:        }
                   3584:     }
1.731     albertel 3585:     if (!$args->{'one_time'}) {
1.949     raeburn  3586: 	&appenv(\%envhash);
1.731     albertel 3587:     }
1.302     albertel 3588:     return %returnhash;
1.461     www      3589: }
                   3590: 
                   3591: # -------------------------------------------------See if a user is privileged
                   3592: 
                   3593: sub privileged {
                   3594:     my ($username,$domain)=@_;
                   3595:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3596: 			&homeserver($username,$domain));
                   3597:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3598:     my $now=time;
                   3599:     if ($rolesdump ne '') {
1.800     albertel 3600:         foreach my $entry (split(/&/,$rolesdump)) {
                   3601: 	    if ($entry!~/^rolesdef_/) {
                   3602: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3603: 		$area=~s/\_\w\w$//;
                   3604: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3605: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3606: 		    my $active=1;
                   3607: 		    if ($tend) {
                   3608: 			if ($tend<$now) { $active=0; }
                   3609: 		    }
                   3610: 		    if ($tstart) {
                   3611: 			if ($tstart>$now) { $active=0; }
                   3612: 		    }
                   3613: 		    if ($active) { return 1; }
                   3614: 		}
                   3615: 	    }
                   3616: 	}
                   3617:     }
                   3618:     return 0;
1.9       www      3619: }
1.1       albertel 3620: 
1.103     harris41 3621: # -------------------------------------------------------- Get user privileges
1.11      www      3622: 
                   3623: sub rolesinit {
                   3624:     my ($domain,$username,$authhost)=@_;
1.966     raeburn  3625:     my %userroles;
1.11      www      3626:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.966     raeburn  3627:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
1.11      www      3628:     my %allroles=();
1.678     raeburn  3629:     my %allgroups=();   
1.11      www      3630:     my $now=time;
1.966     raeburn  3631:     %userroles = ('user.login.time' => $now);
1.678     raeburn  3632:     my $group_privs;
1.11      www      3633: 
                   3634:     if ($rolesdump ne '') {
1.800     albertel 3635:         foreach my $entry (split(/&/,$rolesdump)) {
                   3636: 	  if ($entry!~/^rolesdef_/) {
                   3637:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3638: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3639:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3640: 	    if ($role=~/^cr/) { 
1.807     albertel 3641: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3642: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3643: 		    ($tend,$tstart)=split('_',$trest);
                   3644: 		} else {
                   3645: 		    $trole=$role;
                   3646: 		}
1.678     raeburn  3647:             } elsif ($role =~ m|^gr/|) {
                   3648:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3649:                 ($trole,$group_privs) = split(/\//,$trole);
                   3650:                 $group_privs = &unescape($group_privs);
1.587     albertel 3651: 	    } else {
                   3652: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3653: 	    }
1.743     albertel 3654: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3655: 					 $username);
                   3656: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3657:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3658:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3659:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3660: 		my $spec=$trole.'.'.$area;
                   3661: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3662: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3663:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3664:                 } elsif ($trole eq 'gr') {
                   3665:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3666: 		} else {
1.567     raeburn  3667:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3668: 		}
1.12      www      3669:             }
1.662     raeburn  3670:           }
1.191     harris41 3671:         }
1.743     albertel 3672:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3673:         $userroles{'user.adv'}    = $adv;
                   3674: 	$userroles{'user.author'} = $author;
1.620     albertel 3675:         $env{'user.adv'}=$adv;
1.11      www      3676:     }
1.743     albertel 3677:     return \%userroles;  
1.11      www      3678: }
                   3679: 
1.567     raeburn  3680: sub set_arearole {
                   3681:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3682: # log the associated role with the area
                   3683:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3684:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3685: }
                   3686: 
                   3687: sub custom_roleprivs {
                   3688:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3689:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3690:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3691:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3692:         my ($rdummy,$roledef)=
                   3693:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3694:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3695:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3696:             if (defined($syspriv)) {
                   3697:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3698:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3699:             }
                   3700:             if ($tdomain ne '') {
                   3701:                 if (defined($dompriv)) {
                   3702:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3703:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3704:                 }
                   3705:                 if (($trest ne '') && (defined($coursepriv))) {
                   3706:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3707:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3708:                 }
                   3709:             }
                   3710:         }
                   3711:     }
                   3712: }
                   3713: 
1.678     raeburn  3714: sub group_roleprivs {
                   3715:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3716:     my $access = 1;
                   3717:     my $now = time;
                   3718:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3719:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3720:     if ($access) {
1.811     albertel 3721:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3722:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3723:     }
                   3724: }
1.567     raeburn  3725: 
                   3726: sub standard_roleprivs {
                   3727:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3728:     if (defined($pr{$trole.':s'})) {
                   3729:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3730:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3731:     }
                   3732:     if ($tdomain ne '') {
                   3733:         if (defined($pr{$trole.':d'})) {
                   3734:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3735:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3736:         }
                   3737:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3738:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3739:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3740:         }
                   3741:     }
                   3742: }
                   3743: 
                   3744: sub set_userprivs {
1.678     raeburn  3745:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3746:     my $author=0;
                   3747:     my $adv=0;
1.678     raeburn  3748:     my %grouproles = ();
                   3749:     if (keys(%{$allgroups}) > 0) {
                   3750:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3751:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3752:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3753:                 $trole = $1;
                   3754:                 $area = $2;
1.681     raeburn  3755:                 $sec = $3;
                   3756:                 $extendedarea = $area.$sec;
                   3757:                 if (exists($$allgroups{$area})) {
                   3758:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3759:                         my $spec = $trole.'.'.$extendedarea;
                   3760:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3761:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3762:                     }
                   3763:                 }
                   3764:             }
                   3765:         }
                   3766:     }
1.800     albertel 3767:     foreach my $group (keys(%grouproles)) {
                   3768:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3769:     }
1.800     albertel 3770:     foreach my $role (keys(%{$allroles})) {
                   3771:         my %thesepriv;
1.941     raeburn  3772:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3773:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3774:             if ($item ne '') {
                   3775:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3776:                 if ($restrictions eq '') {
                   3777:                     $thesepriv{$privilege}='F';
                   3778:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3779:                     $thesepriv{$privilege}.=$restrictions;
                   3780:                 }
                   3781:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3782:             }
                   3783:         }
                   3784:         my $thesestr='';
1.800     albertel 3785:         foreach my $priv (keys(%thesepriv)) {
                   3786: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3787: 	}
                   3788:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3789:     }
                   3790:     return ($author,$adv);
                   3791: }
                   3792: 
1.12      www      3793: # --------------------------------------------------------------- get interface
                   3794: 
                   3795: sub get {
1.131     albertel 3796:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3797:    my $items='';
1.800     albertel 3798:    foreach my $item (@$storearr) {
                   3799:        $items.=&escape($item).'&';
1.191     harris41 3800:    }
1.12      www      3801:    $items=~s/\&$//;
1.620     albertel 3802:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3803:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3804:    my $uhome=&homeserver($uname,$udomain);
                   3805: 
1.133     albertel 3806:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3807:    my @pairs=split(/\&/,$rep);
1.273     albertel 3808:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3809:      return @pairs;
                   3810:    }
1.15      www      3811:    my %returnhash=();
1.42      www      3812:    my $i=0;
1.800     albertel 3813:    foreach my $item (@$storearr) {
                   3814:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3815:       $i++;
1.191     harris41 3816:    }
1.15      www      3817:    return %returnhash;
1.27      www      3818: }
                   3819: 
                   3820: # --------------------------------------------------------------- del interface
                   3821: 
                   3822: sub del {
1.133     albertel 3823:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3824:    my $items='';
1.800     albertel 3825:    foreach my $item (@$storearr) {
                   3826:        $items.=&escape($item).'&';
1.191     harris41 3827:    }
1.27      www      3828:    $items=~s/\&$//;
1.620     albertel 3829:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3830:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3831:    my $uhome=&homeserver($uname,$udomain);
                   3832: 
                   3833:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3834: }
                   3835: 
                   3836: # -------------------------------------------------------------- dump interface
                   3837: 
                   3838: sub dump {
1.755     albertel 3839:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3840:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3841:     if (!$uname) { $uname=$env{'user.name'}; }
                   3842:     my $uhome=&homeserver($uname,$udomain);
                   3843:     if ($regexp) {
                   3844: 	$regexp=&escape($regexp);
                   3845:     } else {
                   3846: 	$regexp='.';
                   3847:     }
                   3848:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3849:     my @pairs=split(/\&/,$rep);
                   3850:     my %returnhash=();
                   3851:     foreach my $item (@pairs) {
                   3852: 	my ($key,$value)=split(/=/,$item,2);
                   3853: 	$key = &unescape($key);
                   3854: 	next if ($key =~ /^error: 2 /);
                   3855: 	$returnhash{$key}=&thaw_unescape($value);
                   3856:     }
                   3857:     return %returnhash;
1.407     www      3858: }
                   3859: 
1.717     albertel 3860: # --------------------------------------------------------- dumpstore interface
                   3861: 
                   3862: sub dumpstore {
                   3863:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3864:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3865:    if (!$uname) { $uname=$env{'user.name'}; }
                   3866:    my $uhome=&homeserver($uname,$udomain);
                   3867:    if ($regexp) {
                   3868:        $regexp=&escape($regexp);
                   3869:    } else {
                   3870:        $regexp='.';
                   3871:    }
                   3872:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3873:    my @pairs=split(/\&/,$rep);
                   3874:    my %returnhash=();
                   3875:    foreach my $item (@pairs) {
                   3876:        my ($key,$value)=split(/=/,$item,2);
                   3877:        next if ($key =~ /^error: 2 /);
                   3878:        $returnhash{$key}=&thaw_unescape($value);
                   3879:    }
                   3880:    return %returnhash;
1.717     albertel 3881: }
                   3882: 
1.407     www      3883: # -------------------------------------------------------------- keys interface
                   3884: 
                   3885: sub getkeys {
                   3886:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3887:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3888:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3889:    my $uhome=&homeserver($uname,$udomain);
                   3890:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3891:    my @keyarray=();
1.800     albertel 3892:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3893:       next if ($key =~ /^error: 2 /);
1.800     albertel 3894:       push(@keyarray,&unescape($key));
1.407     www      3895:    }
                   3896:    return @keyarray;
1.318     matthew  3897: }
                   3898: 
1.319     matthew  3899: # --------------------------------------------------------------- currentdump
                   3900: sub currentdump {
1.328     matthew  3901:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3902:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3903:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3904:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3905:    my $uhome = &homeserver($sname,$sdom);
                   3906:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3907:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3908:    #
1.318     matthew  3909:    my %returnhash=();
1.319     matthew  3910:    #
                   3911:    if ($rep eq "unknown_cmd") { 
                   3912:        # an old lond will not know currentdump
                   3913:        # Do a dump and make it look like a currentdump
1.822     albertel 3914:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3915:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3916:        my %hash = @tmp;
                   3917:        @tmp=();
1.424     matthew  3918:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3919:    } else {
                   3920:        my @pairs=split(/\&/,$rep);
1.800     albertel 3921:        foreach my $pair (@pairs) {
                   3922:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3923:            my ($symb,$param) = split(/:/,$key);
                   3924:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3925:                                                         &thaw_unescape($value);
1.319     matthew  3926:        }
1.191     harris41 3927:    }
1.12      www      3928:    return %returnhash;
1.424     matthew  3929: }
                   3930: 
                   3931: sub convert_dump_to_currentdump{
                   3932:     my %hash = %{shift()};
                   3933:     my %returnhash;
                   3934:     # Code ripped from lond, essentially.  The only difference
                   3935:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3936:     # we might run in to problems with parameter names =~ /^v\./
                   3937:     while (my ($key,$value) = each(%hash)) {
                   3938:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3939: 	$symb  = &unescape($symb);
                   3940: 	$param = &unescape($param);
1.424     matthew  3941:         next if ($v eq 'version' || $symb eq 'keys');
                   3942:         next if (exists($returnhash{$symb}) &&
                   3943:                  exists($returnhash{$symb}->{$param}) &&
                   3944:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3945:         $returnhash{$symb}->{$param}=$value;
                   3946:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3947:     }
                   3948:     #
                   3949:     # Remove all of the keys in the hashes which keep track of
                   3950:     # the version of the parameter.
                   3951:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3952:         # use a foreach because we are going to delete from the hash.
                   3953:         foreach my $key (keys(%$param_hash)) {
                   3954:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3955:         }
                   3956:     }
                   3957:     return \%returnhash;
1.12      www      3958: }
                   3959: 
1.627     albertel 3960: # ------------------------------------------------------ critical inc interface
                   3961: 
                   3962: sub cinc {
                   3963:     return &inc(@_,'critical');
                   3964: }
                   3965: 
1.449     matthew  3966: # --------------------------------------------------------------- inc interface
                   3967: 
                   3968: sub inc {
1.627     albertel 3969:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3970:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3971:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3972:     my $uhome=&homeserver($uname,$udomain);
                   3973:     my $items='';
                   3974:     if (! ref($store)) {
                   3975:         # got a single value, so use that instead
                   3976:         $items = &escape($store).'=&';
                   3977:     } elsif (ref($store) eq 'SCALAR') {
                   3978:         $items = &escape($$store).'=&';        
                   3979:     } elsif (ref($store) eq 'ARRAY') {
                   3980:         $items = join('=&',map {&escape($_);} @{$store});
                   3981:     } elsif (ref($store) eq 'HASH') {
                   3982:         while (my($key,$value) = each(%{$store})) {
                   3983:             $items.= &escape($key).'='.&escape($value).'&';
                   3984:         }
                   3985:     }
                   3986:     $items=~s/\&$//;
1.627     albertel 3987:     if ($critical) {
                   3988: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3989:     } else {
                   3990: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3991:     }
1.449     matthew  3992: }
                   3993: 
1.12      www      3994: # --------------------------------------------------------------- put interface
                   3995: 
                   3996: sub put {
1.134     albertel 3997:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3998:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3999:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4000:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4001:    my $items='';
1.800     albertel 4002:    foreach my $item (keys(%$storehash)) {
                   4003:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4004:    }
1.12      www      4005:    $items=~s/\&$//;
1.134     albertel 4006:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4007: }
                   4008: 
1.631     albertel 4009: # ------------------------------------------------------------ newput interface
                   4010: 
                   4011: sub newput {
                   4012:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4013:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4014:    if (!$uname) { $uname=$env{'user.name'}; }
                   4015:    my $uhome=&homeserver($uname,$udomain);
                   4016:    my $items='';
                   4017:    foreach my $key (keys(%$storehash)) {
                   4018:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4019:    }
                   4020:    $items=~s/\&$//;
                   4021:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4022: }
                   4023: 
                   4024: # ---------------------------------------------------------  putstore interface
                   4025: 
1.524     raeburn  4026: sub putstore {
1.715     albertel 4027:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4028:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4029:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4030:    my $uhome=&homeserver($uname,$udomain);
                   4031:    my $items='';
1.715     albertel 4032:    foreach my $key (keys(%$storehash)) {
                   4033:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4034:    }
1.715     albertel 4035:    $items=~s/\&$//;
1.716     albertel 4036:    my $esc_symb=&escape($symb);
                   4037:    my $esc_v=&escape($version);
1.715     albertel 4038:    my $reply =
1.716     albertel 4039:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4040: 	      $uhome);
                   4041:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4042:        # gfall back to way things use to be done
1.715     albertel 4043:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4044: 			    $uname);
1.524     raeburn  4045:    }
1.715     albertel 4046:    return $reply;
                   4047: }
                   4048: 
                   4049: sub old_putstore {
1.716     albertel 4050:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4051:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4052:     if (!$uname) { $uname=$env{'user.name'}; }
                   4053:     my $uhome=&homeserver($uname,$udomain);
                   4054:     my %newstorehash;
1.800     albertel 4055:     foreach my $item (keys(%$storehash)) {
                   4056: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4057: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4058:     }
                   4059:     my $items='';
                   4060:     my %allitems = ();
1.800     albertel 4061:     foreach my $item (keys(%newstorehash)) {
                   4062: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4063: 	    my $key = $1.':keys:'.$2;
                   4064: 	    $allitems{$key} .= $3.':';
                   4065: 	}
1.800     albertel 4066: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4067:     }
1.800     albertel 4068:     foreach my $item (keys(%allitems)) {
                   4069: 	$allitems{$item} =~ s/\:$//;
                   4070: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4071:     }
                   4072:     $items=~s/\&$//;
                   4073:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4074: }
                   4075: 
1.47      www      4076: # ------------------------------------------------------ critical put interface
                   4077: 
                   4078: sub cput {
1.134     albertel 4079:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4080:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4081:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4082:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4083:    my $items='';
1.800     albertel 4084:    foreach my $item (keys(%$storehash)) {
                   4085:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4086:    }
1.47      www      4087:    $items=~s/\&$//;
1.134     albertel 4088:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4089: }
                   4090: 
                   4091: # -------------------------------------------------------------- eget interface
                   4092: 
                   4093: sub eget {
1.133     albertel 4094:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4095:    my $items='';
1.800     albertel 4096:    foreach my $item (@$storearr) {
                   4097:        $items.=&escape($item).'&';
1.191     harris41 4098:    }
1.12      www      4099:    $items=~s/\&$//;
1.620     albertel 4100:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4101:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4102:    my $uhome=&homeserver($uname,$udomain);
                   4103:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4104:    my @pairs=split(/\&/,$rep);
                   4105:    my %returnhash=();
1.42      www      4106:    my $i=0;
1.800     albertel 4107:    foreach my $item (@$storearr) {
                   4108:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4109:       $i++;
1.191     harris41 4110:    }
1.12      www      4111:    return %returnhash;
                   4112: }
                   4113: 
1.667     albertel 4114: # ------------------------------------------------------------ tmpput interface
                   4115: sub tmpput {
1.802     raeburn  4116:     my ($storehash,$server,$context)=@_;
1.667     albertel 4117:     my $items='';
1.800     albertel 4118:     foreach my $item (keys(%$storehash)) {
                   4119: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4120:     }
                   4121:     $items=~s/\&$//;
1.802     raeburn  4122:     if (defined($context)) {
                   4123:         $items .= ':'.&escape($context);
                   4124:     }
1.667     albertel 4125:     return &reply("tmpput:$items",$server);
                   4126: }
                   4127: 
                   4128: # ------------------------------------------------------------ tmpget interface
                   4129: sub tmpget {
1.688     albertel 4130:     my ($token,$server)=@_;
                   4131:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4132:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4133:     my %returnhash;
                   4134:     foreach my $item (split(/\&/,$rep)) {
                   4135: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4136:         next if ($key =~ /^error: 2 /);
1.667     albertel 4137: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4138:     }
                   4139:     return %returnhash;
                   4140: }
                   4141: 
1.688     albertel 4142: # ------------------------------------------------------------ tmpget interface
                   4143: sub tmpdel {
                   4144:     my ($token,$server)=@_;
                   4145:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4146:     return &reply("tmpdel:$token",$server);
                   4147: }
                   4148: 
1.765     albertel 4149: # -------------------------------------------------- portfolio access checking
                   4150: 
                   4151: sub portfolio_access {
1.766     albertel 4152:     my ($requrl) = @_;
1.765     albertel 4153:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4154:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4155:     if ($result) {
                   4156:         my %setters;
                   4157:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4158:             my ($startblock,$endblock) =
                   4159:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4160:             if ($startblock && $endblock) {
                   4161:                 return 'B';
                   4162:             }
                   4163:         } else {
                   4164:             my ($startblock,$endblock) =
                   4165:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4166:             if ($startblock && $endblock) {
                   4167:                 return 'B';
                   4168:             }
                   4169:         }
                   4170:     }
1.765     albertel 4171:     if ($result eq 'ok') {
1.766     albertel 4172:        return 'F';
1.765     albertel 4173:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4174:        return 'A';
1.765     albertel 4175:     }
1.766     albertel 4176:     return '';
1.765     albertel 4177: }
                   4178: 
                   4179: sub get_portfolio_access {
1.767     albertel 4180:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4181: 
                   4182:     if (!ref($access_hash)) {
                   4183: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4184: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4185: 						   $file_name);
                   4186: 	$access_hash = $access_controls{$file_name};
                   4187:     }
                   4188: 
1.765     albertel 4189:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4190:     my $now = time;
                   4191:     if (ref($access_hash) eq 'HASH') {
                   4192:         foreach my $key (keys(%{$access_hash})) {
                   4193:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4194:             if ($start > $now) {
                   4195:                 next;
                   4196:             }
                   4197:             if ($end && $end<$now) {
                   4198:                 next;
                   4199:             }
                   4200:             if ($scope eq 'public') {
                   4201:                 $public = $key;
                   4202:                 last;
                   4203:             } elsif ($scope eq 'guest') {
                   4204:                 $guest = $key;
                   4205:             } elsif ($scope eq 'domains') {
                   4206:                 push(@domains,$key);
                   4207:             } elsif ($scope eq 'users') {
                   4208:                 push(@users,$key);
                   4209:             } elsif ($scope eq 'course') {
                   4210:                 push(@courses,$key);
                   4211:             } elsif ($scope eq 'group') {
                   4212:                 push(@groups,$key);
                   4213:             }
                   4214:         }
                   4215:         if ($public) {
                   4216:             return 'ok';
                   4217:         }
                   4218:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4219:             if ($guest) {
                   4220:                 return $guest;
                   4221:             }
                   4222:         } else {
                   4223:             if (@domains > 0) {
                   4224:                 foreach my $domkey (@domains) {
                   4225:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4226:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4227:                             return 'ok';
                   4228:                         }
                   4229:                     }
                   4230:                 }
                   4231:             }
                   4232:             if (@users > 0) {
                   4233:                 foreach my $userkey (@users) {
1.865     raeburn  4234:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4235:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4236:                             if (ref($item) eq 'HASH') {
                   4237:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4238:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4239:                                     return 'ok';
                   4240:                                 }
                   4241:                             }
                   4242:                         }
                   4243:                     } 
1.765     albertel 4244:                 }
                   4245:             }
                   4246:             my %roleshash;
                   4247:             my @courses_and_groups = @courses;
                   4248:             push(@courses_and_groups,@groups); 
                   4249:             if (@courses_and_groups > 0) {
                   4250:                 my (%allgroups,%allroles); 
                   4251:                 my ($start,$end,$role,$sec,$group);
                   4252:                 foreach my $envkey (%env) {
1.811     albertel 4253:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4254:                         my $cid = $2.'_'.$3; 
                   4255:                         if ($1 eq 'gr') {
                   4256:                             $group = $4;
                   4257:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4258:                         } else {
                   4259:                             if ($4 eq '') {
                   4260:                                 $sec = 'none';
                   4261:                             } else {
                   4262:                                 $sec = $4;
                   4263:                             }
                   4264:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4265:                         }
1.811     albertel 4266:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4267:                         my $cid = $2.'_'.$3;
                   4268:                         if ($4 eq '') {
                   4269:                             $sec = 'none';
                   4270:                         } else {
                   4271:                             $sec = $4;
                   4272:                         }
                   4273:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4274:                     }
                   4275:                 }
                   4276:                 if (keys(%allroles) == 0) {
                   4277:                     return;
                   4278:                 }
                   4279:                 foreach my $key (@courses_and_groups) {
                   4280:                     my %content = %{$$access_hash{$key}};
                   4281:                     my $cnum = $content{'number'};
                   4282:                     my $cdom = $content{'domain'};
                   4283:                     my $cid = $cdom.'_'.$cnum;
                   4284:                     if (!exists($allroles{$cid})) {
                   4285:                         next;
                   4286:                     }    
                   4287:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4288:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4289:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4290:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4291:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4292:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4293:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4294:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4295:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4296:                                         if (grep/^all$/,@sections) {
                   4297:                                             return 'ok';
                   4298:                                         } else {
                   4299:                                             if (grep/^$sec$/,@sections) {
                   4300:                                                 return 'ok';
                   4301:                                             }
                   4302:                                         }
                   4303:                                     }
                   4304:                                 }
                   4305:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4306:                                     if (grep/^none$/,@groups) {
                   4307:                                         return 'ok';
                   4308:                                     }
                   4309:                                 } else {
                   4310:                                     if (grep/^all$/,@groups) {
                   4311:                                         return 'ok';
                   4312:                                     } 
                   4313:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4314:                                         if (grep/^$group$/,@groups) {
                   4315:                                             return 'ok';
                   4316:                                         }
                   4317:                                     }
                   4318:                                 } 
                   4319:                             }
                   4320:                         }
                   4321:                     }
                   4322:                 }
                   4323:             }
                   4324:             if ($guest) {
                   4325:                 return $guest;
                   4326:             }
                   4327:         }
                   4328:     }
                   4329:     return;
                   4330: }
                   4331: 
                   4332: sub course_group_datechecker {
                   4333:     my ($dates,$now,$status) = @_;
                   4334:     my ($start,$end) = split(/\./,$dates);
                   4335:     if (!$start && !$end) {
                   4336:         return 'ok';
                   4337:     }
                   4338:     if (grep/^active$/,@{$status}) {
                   4339:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4340:             return 'ok';
                   4341:         }
                   4342:     }
                   4343:     if (grep/^previous$/,@{$status}) {
                   4344:         if ($end > $now ) {
                   4345:             return 'ok';
                   4346:         }
                   4347:     }
                   4348:     if (grep/^future$/,@{$status}) {
                   4349:         if ($start > $now) {
                   4350:             return 'ok';
                   4351:         }
                   4352:     }
                   4353:     return; 
                   4354: }
                   4355: 
                   4356: sub parse_portfolio_url {
                   4357:     my ($url) = @_;
                   4358: 
                   4359:     my ($type,$udom,$unum,$group,$file_name);
                   4360:     
1.823     albertel 4361:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4362: 	$type = 1;
                   4363:         $udom = $1;
                   4364:         $unum = $2;
                   4365:         $file_name = $3;
1.823     albertel 4366:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4367: 	$type = 2;
                   4368:         $udom = $1;
                   4369:         $unum = $2;
                   4370:         $group = $3;
                   4371:         $file_name = $3.'/'.$4;
                   4372:     }
                   4373:     if (wantarray) {
                   4374: 	return ($type,$udom,$unum,$file_name,$group);
                   4375:     }
                   4376:     return $type;
                   4377: }
                   4378: 
                   4379: sub is_portfolio_url {
                   4380:     my ($url) = @_;
                   4381:     return scalar(&parse_portfolio_url($url));
                   4382: }
                   4383: 
1.798     raeburn  4384: sub is_portfolio_file {
                   4385:     my ($file) = @_;
1.820     raeburn  4386:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4387:         return 1;
                   4388:     }
                   4389:     return;
                   4390: }
                   4391: 
1.976     raeburn  4392: sub usertools_access {
1.976.2.1  raeburn  4393:     my ($uname,$udom,$tool,$action) = @_;
1.976     raeburn  4394:     my $access;
                   4395:     my %tools = (
                   4396:                   aboutme   => 1,
                   4397:                   blog      => 1,
                   4398:                   portfolio => 1,
                   4399:                 );
                   4400:     return if (!defined($tools{$tool}));
                   4401: 
                   4402:     if ((!defined($udom)) || (!defined($uname))) {
                   4403:         $udom = $env{'user.domain'};
                   4404:         $uname = $env{'user.name'};
                   4405:     }
                   4406: 
1.976.2.1  raeburn  4407:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4408:         if ($action ne 'reload') {
                   4409:             return $env{'environment.availabletools.'.$tool};
                   4410:         }
1.976     raeburn  4411:     }
                   4412: 
                   4413:     my ($toolstatus,$inststatus);
                   4414: 
                   4415:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4416:         $toolstatus = $env{'environment.tools.'.$tool};
                   4417:         $inststatus = $env{'environment.inststatus'};
                   4418:     } else {
                   4419:         my %userenv = &userenvironment($udom,$uname,'tools.'.$tool);
                   4420:         $toolstatus = $userenv{'tools.'.$tool};
                   4421:         $inststatus = $userenv{'inststatus'};
                   4422:     }
                   4423: 
                   4424:     if ($toolstatus ne '') {
                   4425:         if ($toolstatus) {
                   4426:             $access = 1;
                   4427:         } else {
                   4428:             $access = 0;
                   4429:         }
                   4430:         return $access;
                   4431:     }
                   4432: 
                   4433:     my $is_adv = &is_advanced_user($udom,$uname);
                   4434:     my %domdef = &get_domain_defaults($udom);
                   4435:     if (ref($domdef{$tool}) eq 'HASH') {
                   4436:         if ($is_adv) {
                   4437:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   4438:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   4439:                     $access = 1;
                   4440:                 } else {
                   4441:                     $access = 0;
                   4442:                 }
                   4443:                 return $access;
                   4444:             }
                   4445:         }
                   4446:         if ($inststatus ne '') {
                   4447:             my ($hasaccess,$hasnoaccess);
                   4448:             foreach my $affiliation (split(/:/,$inststatus)) {
                   4449:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   4450:                     if ($domdef{$tool}{$affiliation}) {
                   4451:                         $hasaccess = 1;
                   4452:                     } else {
                   4453:                         $hasnoaccess = 1;
                   4454:                     }
                   4455:                 }
                   4456:             }
                   4457:             if ($hasaccess || $hasnoaccess) {
                   4458:                 if ($hasaccess) {
                   4459:                     $access = 1;
                   4460:                 } elsif ($hasnoaccess) {
                   4461:                     $access = 0; 
                   4462:                 }
                   4463:                 return $access;
                   4464:             }
                   4465:         } else {
                   4466:             if ($domdef{$tool}{'default'} ne '') {
                   4467:                 if ($domdef{$tool}{'default'}) {
                   4468:                     $access = 1;
                   4469:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   4470:                     $access = 0;
                   4471:                 }
                   4472:                 return $access;
                   4473:             }
                   4474:         }
                   4475:     } else {
                   4476:         $access = 1;
                   4477:         return $access;
                   4478:     }
                   4479: }
                   4480: 
                   4481: sub is_advanced_user {
                   4482:     my ($udom,$uname) = @_;
                   4483:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   4484:     my %allroles;
                   4485:     my $is_adv;
                   4486:     foreach my $role (keys(%roleshash)) {
                   4487:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   4488:         my $area = '/'.$tdomain.'/'.$trest;
                   4489:         if ($sec ne '') {
                   4490:             $area .= '/'.$sec;
                   4491:         }
                   4492:         if (($area ne '') && ($trole ne '')) {
                   4493:             my $spec=$trole.'.'.$area;
                   4494:             if ($trole =~ /^cr\//) {
                   4495:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4496:             } elsif ($trole ne 'gr') {
                   4497:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4498:             }
                   4499:         }
                   4500:     }
                   4501:     foreach my $role (keys(%allroles)) {
                   4502:         last if ($is_adv);
                   4503:         foreach my $item (split(/:/,$allroles{$role})) {
                   4504:             if ($item ne '') {
                   4505:                 my ($privilege,$restrictions)=split(/&/,$item);
                   4506:                 if ($privilege eq 'adv') {
                   4507:                     $is_adv = 1;
                   4508:                     last;
                   4509:                 }
                   4510:             }
                   4511:         }
                   4512:     }
                   4513:     return $is_adv;
                   4514: }
1.798     raeburn  4515: 
1.341     www      4516: # ---------------------------------------------- Custom access rule evaluation
                   4517: 
                   4518: sub customaccess {
                   4519:     my ($priv,$uri)=@_;
1.807     albertel 4520:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4521:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4522:     $udom = &LONCAPA::clean_domain($udom);
                   4523:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4524:     my $access=0;
1.800     albertel 4525:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4526: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4527: 	if ($type eq 'user') {
                   4528: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4529: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4530: 		if ($tdom) {
                   4531: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4532: 		}
1.896     albertel 4533: 		if ($tuname) {
                   4534: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4535: 		}
                   4536: 		$access=($effect eq 'allow');
                   4537: 		last;
                   4538: 	    }
                   4539: 	} else {
                   4540: 	    if ($role) {
                   4541: 		if ($role ne $urole) { next; }
                   4542: 	    }
                   4543: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4544: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4545: 		if ($tdom) {
                   4546: 		    if ($tdom ne $udom) { next; }
                   4547: 		}
                   4548: 		if ($tcrs) {
                   4549: 		    if ($tcrs ne $ucrs) { next; }
                   4550: 		}
                   4551: 		if ($tsec) {
                   4552: 		    if ($tsec ne $usec) { next; }
                   4553: 		}
                   4554: 		$access=($effect eq 'allow');
                   4555: 		last;
                   4556: 	    }
                   4557: 	    if ($realm eq '' && $role eq '') {
                   4558: 		$access=($effect eq 'allow');
                   4559: 	    }
1.402     bowersj2 4560: 	}
1.341     www      4561:     }
                   4562:     return $access;
                   4563: }
                   4564: 
1.103     harris41 4565: # ------------------------------------------------- Check for a user privilege
1.12      www      4566: 
                   4567: sub allowed {
1.810     raeburn  4568:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4569:     my $ver_orguri=$uri;
1.439     www      4570:     $uri=&deversion($uri);
1.152     www      4571:     my $orguri=$uri;
1.52      www      4572:     $uri=&declutter($uri);
1.809     raeburn  4573: 
1.810     raeburn  4574:     if ($priv eq 'evb') {
                   4575: # Evade communication block restrictions for specified role in a course
                   4576:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4577:             return $1;
                   4578:         } else {
                   4579:             return;
                   4580:         }
                   4581:     }
                   4582: 
1.620     albertel 4583:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4584: # Free bre access to adm and meta resources
1.775     albertel 4585:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4586: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4587: 	&& ($priv eq 'bre')) {
1.14      www      4588: 	return 'F';
1.159     www      4589:     }
                   4590: 
1.545     banghart 4591: # Free bre access to user's own portfolio contents
1.714     raeburn  4592:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4593:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4594: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4595:         my %setters;
                   4596:         my ($startblock,$endblock) = 
                   4597:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4598:         if ($startblock && $endblock) {
                   4599:             return 'B';
                   4600:         } else {
                   4601:             return 'F';
                   4602:         }
1.545     banghart 4603:     }
                   4604: 
1.762     raeburn  4605: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4606:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4607:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4608:         if (exists($env{'request.course.id'})) {
                   4609:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4610:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4611:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4612:                 my $courseprivid=$env{'request.course.id'};
                   4613:                 $courseprivid=~s/\_/\//;
                   4614:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4615:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4616:                     return $1; 
1.762     raeburn  4617:                 } else {
                   4618:                     if ($env{'request.course.sec'}) {
                   4619:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4620:                     }
                   4621:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4622:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4623:                         return $2;
                   4624:                     }
1.714     raeburn  4625:                 }
                   4626:             }
                   4627:         }
                   4628:     }
                   4629: 
1.159     www      4630: # Free bre to public access
                   4631: 
                   4632:     if ($priv eq 'bre') {
1.238     www      4633:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4634: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4635:            return 'F'; 
                   4636:         }
1.238     www      4637:         if ($copyright eq 'priv') {
                   4638:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4639: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4640: 		return '';
                   4641:             }
                   4642:         }
                   4643:         if ($copyright eq 'domain') {
                   4644:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4645: 	    unless (($env{'user.domain'} eq $1) ||
                   4646:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4647: 		return '';
                   4648:             }
1.262     matthew  4649:         }
1.620     albertel 4650:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4651:             # Library role, so allow browsing of resources in this domain.
                   4652:             return 'F';
1.238     www      4653:         }
1.341     www      4654:         if ($copyright eq 'custom') {
                   4655: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4656:         }
1.14      www      4657:     }
1.264     matthew  4658:     # Domain coordinator is trying to create a course
1.620     albertel 4659:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4660:         # uri is the requested domain in this case.
                   4661:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4662:         # a role of dc for the domain in question.
1.620     albertel 4663:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4664:     }
1.29      www      4665: 
1.52      www      4666:     my $thisallowed='';
                   4667:     my $statecond=0;
                   4668:     my $courseprivid='';
                   4669: 
                   4670: # Course
                   4671: 
1.620     albertel 4672:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4673:        $thisallowed.=$1;
                   4674:     }
1.29      www      4675: 
1.52      www      4676: # Domain
                   4677: 
1.620     albertel 4678:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4679:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4680:        $thisallowed.=$1;
                   4681:     }
1.52      www      4682: 
                   4683: # Course: uri itself is a course
1.66      www      4684:     my $courseuri=$uri;
                   4685:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4686:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4687: 
1.620     albertel 4688:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4689:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4690:        $thisallowed.=$1;
                   4691:     }
1.29      www      4692: 
1.665     albertel 4693: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4694: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4695:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4696: 	$thisallowed='';
1.671     raeburn  4697:         my ($match)=&is_on_map($uri);
                   4698:         if ($match) {
                   4699:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4700:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4701:                 $thisallowed.=$1;
                   4702:             }
                   4703:         } else {
1.705     albertel 4704:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4705:             if ($refuri) {
                   4706:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4707:                     $thisallowed='F';
1.671     raeburn  4708:                 } else {
                   4709:                     $refuri=&declutter($refuri);
                   4710:                     my ($match) = &is_on_map($refuri);
                   4711:                     if ($match) {
                   4712:                         $thisallowed='F';
                   4713:                     }
1.669     raeburn  4714:                 }
1.671     raeburn  4715:             }
                   4716:         }
1.314     www      4717:     }
1.492     albertel 4718: 
1.766     albertel 4719:     if ($priv eq 'bre'
                   4720: 	&& $thisallowed ne 'F' 
                   4721: 	&& $thisallowed ne '2'
                   4722: 	&& &is_portfolio_url($uri)) {
                   4723: 	$thisallowed = &portfolio_access($uri);
                   4724:     }
                   4725:     
1.52      www      4726: # Full access at system, domain or course-wide level? Exit.
1.29      www      4727:     if ($thisallowed=~/F/) {
                   4728: 	return 'F';
                   4729:     }
                   4730: 
1.52      www      4731: # If this is generating or modifying users, exit with special codes
1.29      www      4732: 
1.643     www      4733:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4734: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4735: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4736: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4737: 	    unless ($auname) { return $thisallowed; }
                   4738: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4739: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4740: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4741: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4742: 	}
1.52      www      4743: 	return $thisallowed;
                   4744:     }
                   4745: #
1.103     harris41 4746: # Gathered so far: system, domain and course wide privileges
1.52      www      4747: #
                   4748: # Course: See if uri or referer is an individual resource that is part of 
                   4749: # the course
                   4750: 
1.620     albertel 4751:     if ($env{'request.course.id'}) {
1.232     www      4752: 
1.620     albertel 4753:        $courseprivid=$env{'request.course.id'};
                   4754:        if ($env{'request.course.sec'}) {
                   4755:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4756:        }
                   4757:        $courseprivid=~s/\_/\//;
                   4758:        my $checkreferer=1;
1.232     www      4759:        my ($match,$cond)=&is_on_map($uri);
                   4760:        if ($match) {
                   4761:            $statecond=$cond;
1.620     albertel 4762:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4763:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4764:                $thisallowed.=$1;
                   4765:                $checkreferer=0;
                   4766:            }
1.29      www      4767:        }
1.83      www      4768:        
1.148     www      4769:        if ($checkreferer) {
1.620     albertel 4770: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4771:             unless ($refuri) {
1.800     albertel 4772:                 foreach my $key (keys(%env)) {
                   4773: 		    if ($key=~/^httpref\..*\*/) {
                   4774: 			my $pattern=$key;
1.156     www      4775:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4776:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4777:                         $pattern=~s/\//\\\//g;
1.152     www      4778:                         if ($orguri=~/$pattern/) {
1.800     albertel 4779: 			    $refuri=$env{$key};
1.148     www      4780:                         }
                   4781:                     }
1.191     harris41 4782:                 }
1.148     www      4783:             }
1.232     www      4784: 
1.148     www      4785:          if ($refuri) { 
1.152     www      4786: 	  $refuri=&declutter($refuri);
1.232     www      4787:           my ($match,$cond)=&is_on_map($refuri);
                   4788:             if ($match) {
                   4789:               my $refstatecond=$cond;
1.620     albertel 4790:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4791:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4792:                   $thisallowed.=$1;
1.53      www      4793:                   $uri=$refuri;
                   4794:                   $statecond=$refstatecond;
1.52      www      4795:               }
                   4796:           }
1.148     www      4797:         }
1.29      www      4798:        }
1.52      www      4799:    }
1.29      www      4800: 
1.52      www      4801: #
1.103     harris41 4802: # Gathered now: all privileges that could apply, and condition number
1.52      www      4803: # 
                   4804: #
                   4805: # Full or no access?
                   4806: #
1.29      www      4807: 
1.52      www      4808:     if ($thisallowed=~/F/) {
                   4809: 	return 'F';
                   4810:     }
1.29      www      4811: 
1.52      www      4812:     unless ($thisallowed) {
                   4813:         return '';
                   4814:     }
1.29      www      4815: 
1.52      www      4816: # Restrictions exist, deal with them
                   4817: #
                   4818: #   C:according to course preferences
                   4819: #   R:according to resource settings
                   4820: #   L:unless locked
                   4821: #   X:according to user session state
                   4822: #
                   4823: 
                   4824: # Possibly locked functionality, check all courses
1.54      www      4825: # Locks might take effect only after 10 minutes cache expiration for other
                   4826: # courses, and 2 minutes for current course
1.52      www      4827: 
                   4828:     my $envkey;
                   4829:     if ($thisallowed=~/L/) {
1.620     albertel 4830:         foreach $envkey (keys %env) {
1.54      www      4831:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4832:                my $courseid=$2;
                   4833:                my $roleid=$1.'.'.$2;
1.92      www      4834:                $courseid=~s/^\///;
1.54      www      4835:                my $expiretime=600;
1.620     albertel 4836:                if ($env{'request.role'} eq $roleid) {
1.54      www      4837: 		  $expiretime=120;
                   4838:                }
                   4839: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4840:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4841:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4842: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4843:                }
1.620     albertel 4844:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4845:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4846: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4847:                        &log($env{'user.domain'},$env{'user.name'},
                   4848:                             $env{'user.home'},
1.57      www      4849:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4850:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4851:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4852: 		       return '';
                   4853:                    }
                   4854:                }
1.620     albertel 4855:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4856:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4857: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4858:                        &log($env{'user.domain'},$env{'user.name'},
                   4859:                             $env{'user.home'},
1.57      www      4860:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4861:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4862:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4863: 		       return '';
                   4864:                    }
                   4865:                }
                   4866: 	   }
1.29      www      4867:        }
1.52      www      4868:     }
                   4869:    
                   4870: #
                   4871: # Rest of the restrictions depend on selected course
                   4872: #
                   4873: 
1.620     albertel 4874:     unless ($env{'request.course.id'}) {
1.766     albertel 4875: 	if ($thisallowed eq 'A') {
                   4876: 	    return 'A';
1.814     raeburn  4877:         } elsif ($thisallowed eq 'B') {
                   4878:             return 'B';
1.766     albertel 4879: 	} else {
                   4880: 	    return '1';
                   4881: 	}
1.52      www      4882:     }
1.29      www      4883: 
1.52      www      4884: #
                   4885: # Now user is definitely in a course
                   4886: #
1.53      www      4887: 
                   4888: 
                   4889: # Course preferences
                   4890: 
                   4891:    if ($thisallowed=~/C/) {
1.620     albertel 4892:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4893:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4894:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4895: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4896: 	   if ($priv ne 'pch') { 
                   4897: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4898: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4899: 			$env{'request.course.id'});
                   4900: 	   }
1.237     www      4901:            return '';
                   4902:        }
                   4903: 
1.620     albertel 4904:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4905: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4906: 	   if ($priv ne 'pch') { 
                   4907: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4908: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4909: 			$env{'request.course.id'});
                   4910: 	   }
1.54      www      4911:            return '';
                   4912:        }
1.53      www      4913:    }
                   4914: 
                   4915: # Resource preferences
                   4916: 
                   4917:    if ($thisallowed=~/R/) {
1.620     albertel 4918:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4919:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4920: 	   if ($priv ne 'pch') { 
                   4921: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4922: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4923: 	   }
                   4924: 	   return '';
1.54      www      4925:        }
1.53      www      4926:    }
1.30      www      4927: 
1.246     www      4928: # Restricted by state or randomout?
1.30      www      4929: 
1.52      www      4930:    if ($thisallowed=~/X/) {
1.620     albertel 4931:       if ($env{'acc.randomout'}) {
1.579     albertel 4932: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4933:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4934:             return ''; 
                   4935:          }
1.247     www      4936:       }
                   4937:       if (&condval($statecond)) {
1.52      www      4938: 	 return '2';
                   4939:       } else {
                   4940:          return '';
                   4941:       }
                   4942:    }
1.30      www      4943: 
1.766     albertel 4944:     if ($thisallowed eq 'A') {
                   4945: 	return 'A';
1.814     raeburn  4946:     } elsif ($thisallowed eq 'B') {
                   4947:         return 'B';
1.766     albertel 4948:     }
1.52      www      4949:    return 'F';
1.232     www      4950: }
                   4951: 
1.710     albertel 4952: sub split_uri_for_cond {
                   4953:     my $uri=&deversion(&declutter(shift));
                   4954:     my @uriparts=split(/\//,$uri);
                   4955:     my $filename=pop(@uriparts);
                   4956:     my $pathname=join('/',@uriparts);
                   4957:     return ($pathname,$filename);
                   4958: }
1.232     www      4959: # --------------------------------------------------- Is a resource on the map?
                   4960: 
                   4961: sub is_on_map {
1.710     albertel 4962:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4963:     #Trying to find the conditional for the file
1.620     albertel 4964:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4965: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4966:     if ($match) {
1.289     bowersj2 4967: 	return (1,$1);
                   4968:     } else {
1.434     www      4969: 	return (0,0);
1.289     bowersj2 4970:     }
1.12      www      4971: }
                   4972: 
1.427     www      4973: # --------------------------------------------------------- Get symb from alias
                   4974: 
                   4975: sub get_symb_from_alias {
                   4976:     my $symb=shift;
                   4977:     my ($map,$resid,$url)=&decode_symb($symb);
                   4978: # Already is a symb
                   4979:     if ($url) { return $symb; }
                   4980: # Must be an alias
                   4981:     my $aliassymb='';
                   4982:     my %bighash;
1.620     albertel 4983:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4984:                             &GDBM_READER(),0640)) {
                   4985:         my $rid=$bighash{'mapalias_'.$symb};
                   4986: 	if ($rid) {
                   4987: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4988: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4989: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4990: 	}
                   4991:         untie %bighash;
                   4992:     }
                   4993:     return $aliassymb;
                   4994: }
                   4995: 
1.12      www      4996: # ----------------------------------------------------------------- Define Role
                   4997: 
                   4998: sub definerole {
                   4999:   if (allowed('mcr','/')) {
                   5000:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5001:     foreach my $role (split(':',$sysrole)) {
                   5002: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5003:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5004:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5005: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5006:                return "refused:s:$crole&$cqual"; 
                   5007:             }
                   5008:         }
1.191     harris41 5009:     }
1.800     albertel 5010:     foreach my $role (split(':',$domrole)) {
                   5011: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5012:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5013:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5014: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5015:                return "refused:d:$crole&$cqual"; 
                   5016:             }
                   5017:         }
1.191     harris41 5018:     }
1.800     albertel 5019:     foreach my $role (split(':',$courole)) {
                   5020: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5021:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5022:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5023: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5024:                return "refused:c:$crole&$cqual"; 
                   5025:             }
                   5026:         }
1.191     harris41 5027:     }
1.620     albertel 5028:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5029:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5030: 	        "rolesdef_$rolename=".
                   5031:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5032:     return reply($command,$env{'user.home'});
1.12      www      5033:   } else {
                   5034:     return 'refused';
                   5035:   }
1.105     harris41 5036: }
                   5037: 
                   5038: # ---------------- Make a metadata query against the network of library servers
                   5039: 
                   5040: sub metadata_query {
1.244     matthew  5041:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5042:     my %rhash;
1.845     albertel 5043:     my %libserv = &all_library();
1.244     matthew  5044:     my @server_list = (defined($server_array) ? @$server_array
                   5045:                                               : keys(%libserv) );
                   5046:     for my $server (@server_list) {
1.118     harris41 5047: 	unless ($custom or $customshow) {
                   5048: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5049: 	    $rhash{$server}=$reply;
                   5050: 	}
                   5051: 	else {
                   5052: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5053: 			     &escape($custom).':'.&escape($customshow),
                   5054: 			     $server);
                   5055: 	    $rhash{$server}=$reply;
                   5056: 	}
1.112     harris41 5057:     }
1.118     harris41 5058:     return \%rhash;
1.240     www      5059: }
                   5060: 
                   5061: # ----------------------------------------- Send log queries and wait for reply
                   5062: 
                   5063: sub log_query {
                   5064:     my ($uname,$udom,$query,%filters)=@_;
                   5065:     my $uhome=&homeserver($uname,$udom);
                   5066:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5067:     my $uhost=&hostname($uhome);
1.800     albertel 5068:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5069:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5070:                        $uhome);
1.479     albertel 5071:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5072:     return get_query_reply($queryid);
                   5073: }
                   5074: 
1.818     raeburn  5075: # -------------------------- Update MySQL table for portfolio file
                   5076: 
                   5077: sub update_portfolio_table {
1.821     raeburn  5078:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5079:     if ($group ne '') {
                   5080:         $file_name =~s /^\Q$group\E//;
                   5081:     }
1.818     raeburn  5082:     my $homeserver = &homeserver($uname,$udom);
                   5083:     my $queryid=
1.821     raeburn  5084:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5085:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5086:     my $reply = &get_query_reply($queryid);
                   5087:     return $reply;
                   5088: }
                   5089: 
1.899     raeburn  5090: # -------------------------- Update MySQL allusers table
                   5091: 
                   5092: sub update_allusers_table {
                   5093:     my ($uname,$udom,$names) = @_;
                   5094:     my $homeserver = &homeserver($uname,$udom);
                   5095:     my $queryid=
                   5096:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5097:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5098:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5099:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5100:                'generation='.&escape($names->{'generation'}).'%%'.
                   5101:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5102:                'id='.&escape($names->{'id'}),$homeserver);
                   5103:     my $reply = &get_query_reply($queryid);
                   5104:     return $reply;
                   5105: }
                   5106: 
1.508     raeburn  5107: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5108: 
                   5109: sub fetch_enrollment_query {
1.511     raeburn  5110:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5111:     my $homeserver;
1.547     raeburn  5112:     my $maxtries = 1;
1.508     raeburn  5113:     if ($context eq 'automated') {
                   5114:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5115:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5116:     } else {
                   5117:         $homeserver = &homeserver($cnum,$dom);
                   5118:     }
1.838     albertel 5119:     my $host=&hostname($homeserver);
1.506     raeburn  5120:     my $cmd = '';
1.800     albertel 5121:     foreach my $affiliate (keys %{$affiliatesref}) {
                   5122:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5123:     }
                   5124:     $cmd =~ s/%%$//;
                   5125:     $cmd = &escape($cmd);
                   5126:     my $query = 'fetchenrollment';
1.620     albertel 5127:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5128:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5129:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5130:         return 'error: '.$queryid;
                   5131:     }
1.506     raeburn  5132:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5133:     my $tries = 1;
                   5134:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5135:         $reply = &get_query_reply($queryid);
                   5136:         $tries ++;
                   5137:     }
1.526     raeburn  5138:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5139:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5140:     } else {
1.901     albertel 5141:         my @responses = split(/:/,$reply);
1.515     raeburn  5142:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5143:             foreach my $line (@responses) {
                   5144:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5145:                 $$replyref{$key} = $value;
                   5146:             }
                   5147:         } else {
1.506     raeburn  5148:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5149:             foreach my $line (@responses) {
                   5150:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5151:                 $$replyref{$key} = $value;
                   5152:                 if ($value > 0) {
1.800     albertel 5153:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5154:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5155:                         my $destname = $pathname.'/'.$filename;
                   5156:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5157:                         if ($xml_classlist =~ /^error/) {
                   5158:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5159:                         } else {
1.506     raeburn  5160:                             if ( open(FILE,">$destname") ) {
                   5161:                                 print FILE &unescape($xml_classlist);
                   5162:                                 close(FILE);
1.526     raeburn  5163:                             } else {
                   5164:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5165:                             }
                   5166:                         }
                   5167:                     }
                   5168:                 }
                   5169:             }
                   5170:         }
                   5171:         return 'ok';
                   5172:     }
                   5173:     return 'error';
                   5174: }
                   5175: 
1.242     www      5176: sub get_query_reply {
                   5177:     my $queryid=shift;
1.240     www      5178:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5179:     my $reply='';
                   5180:     for (1..100) {
                   5181: 	sleep 2;
                   5182:         if (-e $replyfile.'.end') {
1.448     albertel 5183: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5184: 		$reply = join('',<$fh>);
                   5185: 		close($fh);
1.240     www      5186: 	   } else { return 'error: reply_file_error'; }
1.242     www      5187:            return &unescape($reply);
                   5188: 	}
1.240     www      5189:     }
1.242     www      5190:     return 'timeout:'.$queryid;
1.240     www      5191: }
                   5192: 
                   5193: sub courselog_query {
1.241     www      5194: #
                   5195: # possible filters:
                   5196: # url: url or symb
                   5197: # username
                   5198: # domain
                   5199: # action: view, submit, grade
                   5200: # start: timestamp
                   5201: # end: timestamp
                   5202: #
1.240     www      5203:     my (%filters)=@_;
1.620     albertel 5204:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5205:     if ($filters{'url'}) {
                   5206: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5207:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5208:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5209:     }
1.620     albertel 5210:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5211:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5212:     return &log_query($cname,$cdom,'courselog',%filters);
                   5213: }
                   5214: 
                   5215: sub userlog_query {
1.858     raeburn  5216: #
                   5217: # possible filters:
                   5218: # action: log check role
                   5219: # start: timestamp
                   5220: # end: timestamp
                   5221: #
1.240     www      5222:     my ($uname,$udom,%filters)=@_;
                   5223:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5224: }
                   5225: 
1.506     raeburn  5226: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5227: 
                   5228: sub auto_run {
1.508     raeburn  5229:     my ($cnum,$cdom) = @_;
1.876     raeburn  5230:     my $response = 0;
                   5231:     my $settings;
                   5232:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5233:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5234:         $settings = $domconfig{'autoenroll'};
                   5235:         if ($settings->{'run'} eq '1') {
                   5236:             $response = 1;
                   5237:         }
                   5238:     } else {
1.934     raeburn  5239:         my $homeserver;
                   5240:         if (&is_course($cdom,$cnum)) {
                   5241:             $homeserver = &homeserver($cnum,$cdom);
                   5242:         } else {
                   5243:             $homeserver = &domain($cdom,'primary');
                   5244:         }
                   5245:         if ($homeserver ne 'no_host') {
                   5246:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5247:         }
1.876     raeburn  5248:     }
1.506     raeburn  5249:     return $response;
                   5250: }
1.776     albertel 5251: 
1.506     raeburn  5252: sub auto_get_sections {
1.508     raeburn  5253:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   5254:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  5255:     my @secs = ();
1.511     raeburn  5256:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  5257:     unless ($response eq 'refused') {
1.901     albertel 5258:         @secs = split(/:/,$response);
1.506     raeburn  5259:     }
                   5260:     return @secs;
                   5261: }
1.776     albertel 5262: 
1.506     raeburn  5263: sub auto_new_course {
1.508     raeburn  5264:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5265:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5266:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5267:     return $response;
                   5268: }
1.776     albertel 5269: 
1.506     raeburn  5270: sub auto_validate_courseID {
1.508     raeburn  5271:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5272:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5273:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5274:     return $response;
                   5275: }
1.776     albertel 5276: 
1.506     raeburn  5277: sub auto_create_password {
1.873     raeburn  5278:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5279:     my ($homeserver,$response);
1.506     raeburn  5280:     my $create_passwd = 0;
                   5281:     my $authchk = '';
1.873     raeburn  5282:     if ($udom =~ /^$match_domain$/) {
                   5283:         $homeserver = &domain($udom,'primary');
                   5284:     }
                   5285:     if ($homeserver eq '') {
                   5286:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5287:             $homeserver = &homeserver($cnum,$cdom);
                   5288:         }
                   5289:     }
                   5290:     if ($homeserver eq '') {
                   5291:         $authchk = 'nodomain';
1.506     raeburn  5292:     } else {
1.873     raeburn  5293:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5294:         if ($response eq 'refused') {
                   5295:             $authchk = 'refused';
                   5296:         } else {
1.901     albertel 5297:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5298:         }
1.506     raeburn  5299:     }
                   5300:     return ($authparam,$create_passwd,$authchk);
                   5301: }
                   5302: 
1.706     raeburn  5303: sub auto_photo_permission {
                   5304:     my ($cnum,$cdom,$students) = @_;
                   5305:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5306:     my ($outcome,$perm_reqd,$conditions) = 
                   5307: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5308:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5309: 	return (undef,undef);
                   5310:     }
1.706     raeburn  5311:     return ($outcome,$perm_reqd,$conditions);
                   5312: }
                   5313: 
                   5314: sub auto_checkphotos {
                   5315:     my ($uname,$udom,$pid) = @_;
                   5316:     my $homeserver = &homeserver($uname,$udom);
                   5317:     my ($result,$resulttype);
                   5318:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5319: 				   &escape($uname).':'.&escape($pid),
                   5320: 				   $homeserver));
1.709     albertel 5321:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5322: 	return (undef,undef);
                   5323:     }
1.706     raeburn  5324:     if ($outcome) {
                   5325:         ($result,$resulttype) = split(/:/,$outcome);
                   5326:     } 
                   5327:     return ($result,$resulttype);
                   5328: }
                   5329: 
                   5330: sub auto_photochoice {
                   5331:     my ($cnum,$cdom) = @_;
                   5332:     my $homeserver = &homeserver($cnum,$cdom);
                   5333:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5334: 						       &escape($cdom),
                   5335: 						       $homeserver)));
1.709     albertel 5336:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5337: 	return (undef,undef);
                   5338:     }
1.706     raeburn  5339:     return ($update,$comment);
                   5340: }
                   5341: 
                   5342: sub auto_photoupdate {
                   5343:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5344:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5345:     my $host=&hostname($homeserver);
1.706     raeburn  5346:     my $cmd = '';
                   5347:     my $maxtries = 1;
1.800     albertel 5348:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5349:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5350:     }
                   5351:     $cmd =~ s/%%$//;
                   5352:     $cmd = &escape($cmd);
                   5353:     my $query = 'institutionalphotos';
                   5354:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5355:     unless ($queryid=~/^\Q$host\E\_/) {
                   5356:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5357:         return 'error: '.$queryid;
                   5358:     }
                   5359:     my $reply = &get_query_reply($queryid);
                   5360:     my $tries = 1;
                   5361:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5362:         $reply = &get_query_reply($queryid);
                   5363:         $tries ++;
                   5364:     }
                   5365:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5366:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5367:     } else {
                   5368:         my @responses = split(/:/,$reply);
                   5369:         my $outcome = shift(@responses); 
                   5370:         foreach my $item (@responses) {
                   5371:             my ($key,$value) = split(/=/,$item);
                   5372:             $$photo{$key} = $value;
                   5373:         }
                   5374:         return $outcome;
                   5375:     }
                   5376:     return 'error';
                   5377: }
                   5378: 
1.521     raeburn  5379: sub auto_instcode_format {
1.793     albertel 5380:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5381: 	$cat_order) = @_;
1.521     raeburn  5382:     my $courses = '';
1.772     raeburn  5383:     my @homeservers;
1.521     raeburn  5384:     if ($caller eq 'global') {
1.841     albertel 5385: 	my %servers = &get_servers($codedom,'library');
                   5386: 	foreach my $tryserver (keys(%servers)) {
                   5387: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5388: 		push(@homeservers,$tryserver);
                   5389: 	    }
1.584     raeburn  5390:         }
1.521     raeburn  5391:     } else {
1.772     raeburn  5392:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5393:     }
1.793     albertel 5394:     foreach my $code (keys(%{$instcodes})) {
                   5395:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5396:     }
                   5397:     chop($courses);
1.772     raeburn  5398:     my $ok_response = 0;
                   5399:     my $response;
                   5400:     while (@homeservers > 0 && $ok_response == 0) {
                   5401:         my $server = shift(@homeservers); 
                   5402:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5403:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5404:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5405: 		split(/:/,$response);
1.772     raeburn  5406:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5407:             push(@{$codetitles},&str2array($codetitles_str));
                   5408:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5409:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5410:             $ok_response = 1;
                   5411:         }
                   5412:     }
                   5413:     if ($ok_response) {
1.521     raeburn  5414:         return 'ok';
1.772     raeburn  5415:     } else {
                   5416:         return $response;
1.521     raeburn  5417:     }
                   5418: }
                   5419: 
1.792     raeburn  5420: sub auto_instcode_defaults {
                   5421:     my ($domain,$returnhash,$code_order) = @_;
                   5422:     my @homeservers;
1.841     albertel 5423: 
                   5424:     my %servers = &get_servers($domain,'library');
                   5425:     foreach my $tryserver (keys(%servers)) {
                   5426: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5427: 	    push(@homeservers,$tryserver);
                   5428: 	}
1.792     raeburn  5429:     }
1.841     albertel 5430: 
1.792     raeburn  5431:     my $response;
1.841     albertel 5432:     foreach my $server (@homeservers) {
1.792     raeburn  5433:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5434:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5435: 	
                   5436: 	foreach my $pair (split(/\&/,$response)) {
                   5437: 	    my ($name,$value)=split(/\=/,$pair);
                   5438: 	    if ($name eq 'code_order') {
                   5439: 		@{$code_order} = split(/\&/,&unescape($value));
                   5440: 	    } else {
                   5441: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5442: 	    }
                   5443: 	}
                   5444: 	return 'ok';
1.792     raeburn  5445:     }
1.841     albertel 5446: 
                   5447:     return $response;
1.792     raeburn  5448: } 
                   5449: 
1.777     albertel 5450: sub auto_validate_class_sec {
1.918     raeburn  5451:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5452:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5453:     my $ownerlist;
                   5454:     if (ref($owners) eq 'ARRAY') {
                   5455:         $ownerlist = join(',',@{$owners});
                   5456:     } else {
                   5457:         $ownerlist = $owners;
                   5458:     }
1.773     raeburn  5459:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5460:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5461:     return $response;
                   5462: }
                   5463: 
1.679     raeburn  5464: # ------------------------------------------------------- Course Group routines
                   5465: 
                   5466: sub get_coursegroups {
1.809     raeburn  5467:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5468:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5469: }
                   5470: 
1.679     raeburn  5471: sub modify_coursegroup {
                   5472:     my ($cdom,$cnum,$groupsettings) = @_;
                   5473:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5474: }
                   5475: 
1.809     raeburn  5476: sub toggle_coursegroup_status {
                   5477:     my ($cdom,$cnum,$group,$action) = @_;
                   5478:     my ($from_namespace,$to_namespace);
                   5479:     if ($action eq 'delete') {
                   5480:         $from_namespace = 'coursegroups';
                   5481:         $to_namespace = 'deleted_groups';
                   5482:     } else {
                   5483:         $from_namespace = 'deleted_groups';
                   5484:         $to_namespace = 'coursegroups';
                   5485:     }
                   5486:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5487:     if (my $tmp = &error(%curr_group)) {
                   5488:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5489:         return ('read error',$tmp);
                   5490:     } else {
                   5491:         my %savedsettings = %curr_group; 
1.809     raeburn  5492:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5493:         my $deloutcome;
                   5494:         if ($result eq 'ok') {
1.809     raeburn  5495:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5496:         } else {
                   5497:             return ('write error',$result);
                   5498:         }
                   5499:         if ($deloutcome eq 'ok') {
                   5500:             return 'ok';
                   5501:         } else {
                   5502:             return ('delete error',$deloutcome);
                   5503:         }
                   5504:     }
                   5505: }
                   5506: 
1.679     raeburn  5507: sub modify_group_roles {
1.957     raeburn  5508:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  5509:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5510:     my $role = 'gr/'.&escape($userprivs);
                   5511:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  5512:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  5513:     if ($result eq 'ok') {
                   5514:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5515:     }
1.679     raeburn  5516:     return $result;
                   5517: }
                   5518: 
                   5519: sub modify_coursegroup_membership {
                   5520:     my ($cdom,$cnum,$membership) = @_;
                   5521:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5522:     return $result;
                   5523: }
                   5524: 
1.682     raeburn  5525: sub get_active_groups {
                   5526:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5527:     my $now = time;
                   5528:     my %groups = ();
                   5529:     foreach my $key (keys(%env)) {
1.811     albertel 5530:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5531:             my ($start,$end) = split(/\./,$env{$key});
                   5532:             if (($end!=0) && ($end<$now)) { next; }
                   5533:             if (($start!=0) && ($start>$now)) { next; }
                   5534:             if ($1 eq $cdom && $2 eq $cnum) {
                   5535:                 $groups{$3} = $env{$key} ;
                   5536:             }
                   5537:         }
                   5538:     }
                   5539:     return %groups;
                   5540: }
                   5541: 
1.683     raeburn  5542: sub get_group_membership {
                   5543:     my ($cdom,$cnum,$group) = @_;
                   5544:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5545: }
                   5546: 
                   5547: sub get_users_groups {
                   5548:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5549:     my @usersgroups;
1.683     raeburn  5550:     my $cachetime=1800;
                   5551: 
                   5552:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5553:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5554:     if (defined($cached)) {
1.734     albertel 5555:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5556:     } else {  
                   5557:         $grouplist = '';
1.816     raeburn  5558:         my $courseurl = &courseid_to_courseurl($courseid);
                   5559:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5560:         my $access_end = $env{'course.'.$courseid.
                   5561:                               '.default_enrollment_end_date'};
                   5562:         my $now = time;
                   5563:         foreach my $key (keys(%roleshash)) {
                   5564:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5565:                 my $group = $1;
                   5566:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5567:                     my $start = $2;
                   5568:                     my $end = $1;
                   5569:                     if ($start == -1) { next; } # deleted from group
                   5570:                     if (($start!=0) && ($start>$now)) { next; }
                   5571:                     if (($end!=0) && ($end<$now)) {
                   5572:                         if ($access_end && $access_end < $now) {
                   5573:                             if ($access_end - $end < 86400) {
                   5574:                                 push(@usersgroups,$group);
1.733     raeburn  5575:                             }
                   5576:                         }
1.817     raeburn  5577:                         next;
1.733     raeburn  5578:                     }
1.817     raeburn  5579:                     push(@usersgroups,$group);
1.683     raeburn  5580:                 }
                   5581:             }
                   5582:         }
1.817     raeburn  5583:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5584:         $grouplist = join(':',@usersgroups);
                   5585:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5586:     }
1.733     raeburn  5587:     return @usersgroups;
1.683     raeburn  5588: }
                   5589: 
                   5590: sub devalidate_getgroups_cache {
                   5591:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5592:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5593: 
1.683     raeburn  5594:     my $hashid="$udom:$uname:$courseid";
                   5595:     &devalidate_cache_new('getgroups',$hashid);
                   5596: }
                   5597: 
1.12      www      5598: # ------------------------------------------------------------------ Plain Text
                   5599: 
                   5600: sub plaintext {
1.742     raeburn  5601:     my ($short,$type,$cid) = @_;
1.758     albertel 5602:     if ($short =~ /^cr/) {
                   5603: 	return (split('/',$short))[-1];
                   5604:     }
1.742     raeburn  5605:     if (!defined($cid)) {
                   5606:         $cid = $env{'request.course.id'};
                   5607:     }
                   5608:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5609:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5610:                                           '.plaintext'});
                   5611:     }
                   5612:     my %rolenames = (
                   5613:                       Course => 'std',
                   5614:                       Group => 'alt1',
                   5615:                     );
                   5616:     if (defined($type) && 
                   5617:          defined($rolenames{$type}) && 
                   5618:          defined($prp{$short}{$rolenames{$type}})) {
                   5619:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5620:     } else {
                   5621:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5622:     }
1.12      www      5623: }
                   5624: 
                   5625: # ----------------------------------------------------------------- Assign Role
                   5626: 
                   5627: sub assignrole {
1.957     raeburn  5628:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   5629:         $context)=@_;
1.21      www      5630:     my $mrole;
                   5631:     if ($role =~ /^cr\//) {
1.393     www      5632:         my $cwosec=$url;
1.811     albertel 5633:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5634: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5635:            &logthis('Refused custom assignrole: '.
                   5636:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5637: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5638:            return 'refused'; 
                   5639:         }
1.21      www      5640:         $mrole='cr';
1.678     raeburn  5641:     } elsif ($role =~ /^gr\//) {
                   5642:         my $cwogrp=$url;
1.811     albertel 5643:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5644:         unless (&allowed('mdg',$cwogrp)) {
                   5645:             &logthis('Refused group assignrole: '.
                   5646:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5647:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5648:             return 'refused';
                   5649:         }
                   5650:         $mrole='gr';
1.21      www      5651:     } else {
1.82      www      5652:         my $cwosec=$url;
1.811     albertel 5653:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5654:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5655:             my $refused;
                   5656:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5657:                 if (!(&allowed('c'.$role,$url))) {
                   5658:                     $refused = 1;
                   5659:                 }
                   5660:             } else {
                   5661:                 $refused = 1;
                   5662:             }
1.947     raeburn  5663:             if ($refused) {
                   5664:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5665:                     $refused = '';
                   5666:                 } else {
                   5667:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   5668:                              ' '.$role.' '.$end.' '.$start.' by '.
                   5669: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   5670:                     return 'refused';
                   5671:                 }
1.932     raeburn  5672:             }
1.104     www      5673:         }
1.21      www      5674:         $mrole=$role;
                   5675:     }
1.620     albertel 5676:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5677:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5678:     if ($end) { $command.='_'.$end; }
1.21      www      5679:     if ($start) {
                   5680: 	if ($end) { 
1.81      www      5681:            $command.='_'.$start; 
1.21      www      5682:         } else {
1.81      www      5683:            $command.='_0_'.$start;
1.21      www      5684:         }
                   5685:     }
1.739     raeburn  5686:     my $origstart = $start;
                   5687:     my $origend = $end;
1.957     raeburn  5688:     my $delflag;
1.357     www      5689: # actually delete
                   5690:     if ($deleteflag) {
1.373     www      5691: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5692: # modify command to delete the role
1.620     albertel 5693:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5694:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5695: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5696: # set start and finish to negative values for userrolelog
                   5697:            $start=-1;
                   5698:            $end=-1;
1.957     raeburn  5699:            $delflag = 1;
1.357     www      5700:         }
                   5701:     }
                   5702: # send command
1.349     www      5703:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5704: # log new user role if status is ok
1.349     www      5705:     if ($answer eq 'ok') {
1.663     raeburn  5706: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5707: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  5708:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  5709:         unless ($role =~ /^gr/) {
                   5710:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  5711:                                              $origstart,$selfenroll,$context);
1.739     raeburn  5712:         }
1.349     www      5713:     }
                   5714:     return $answer;
1.169     harris41 5715: }
                   5716: 
                   5717: # -------------------------------------------------- Modify user authentication
1.197     www      5718: # Overrides without validation
                   5719: 
1.169     harris41 5720: sub modifyuserauth {
                   5721:     my ($udom,$uname,$umode,$upass)=@_;
                   5722:     my $uhome=&homeserver($uname,$udom);
1.197     www      5723:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5724:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5725:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5726:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5727:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5728: 		     &escape($upass),$uhome);
1.620     albertel 5729:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5730:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5731:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5732:     &log($udom,,$uname,$uhome,
1.620     albertel 5733:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5734:                                      $env{'user.name'}.', '.$umode.
1.197     www      5735:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5736:     unless ($reply eq 'ok') {
1.197     www      5737:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5738: 	return 'error: '.$reply;
                   5739:     }   
1.170     harris41 5740:     return 'ok';
1.80      www      5741: }
                   5742: 
1.81      www      5743: # --------------------------------------------------------------- Modify a user
1.80      www      5744: 
1.81      www      5745: sub modifyuser {
1.206     matthew  5746:     my ($udom,    $uname, $uid,
                   5747:         $umode,   $upass, $first,
                   5748:         $middle,  $last,  $gene,
1.963     raeburn  5749:         $forceid, $desiredhome, $email, $inststatus)=@_;
1.807     albertel 5750:     $udom= &LONCAPA::clean_domain($udom);
                   5751:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5752:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5753:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5754: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5755:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5756:                                      ' desiredhome not specified'). 
1.620     albertel 5757:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5758:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5759:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5760: # ----------------------------------------------------------------- Create User
1.406     albertel 5761:     if (($uhome eq 'no_host') && 
                   5762: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5763:         my $unhome='';
1.844     albertel 5764:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5765:             $unhome = $desiredhome;
1.620     albertel 5766: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5767: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5768:         } else { # load balancing routine for determining $unhome
1.81      www      5769:             my $loadm=10000000;
1.841     albertel 5770: 	    my %servers = &get_servers($udom,'library');
                   5771: 	    foreach my $tryserver (keys(%servers)) {
                   5772: 		my $answer=reply('load',$tryserver);
                   5773: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5774: 		    $loadm=$answer;
                   5775: 		    $unhome=$tryserver;
                   5776: 		}
1.80      www      5777: 	    }
                   5778:         }
                   5779:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5780: 	    return 'error: unable to find a home server for '.$uname.
                   5781:                    ' in domain '.$udom;
1.80      www      5782:         }
                   5783:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5784:                          &escape($upass),$unhome);
                   5785: 	unless ($reply eq 'ok') {
                   5786:             return 'error: '.$reply;
                   5787:         }   
1.230     stredwic 5788:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5789:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5790: 	    return 'error: unable verify users home machine.';
1.80      www      5791:         }
1.209     matthew  5792:     }   # End of creation of new user
1.80      www      5793: # ---------------------------------------------------------------------- Add ID
                   5794:     if ($uid) {
                   5795:        $uid=~tr/A-Z/a-z/;
                   5796:        my %uidhash=&idrget($udom,$uname);
1.196     www      5797:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5798:          && (!$forceid)) {
1.80      www      5799: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5800: 	      return 'error: user id "'.$uid.'" does not match '.
                   5801:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5802:           }
                   5803:        } else {
                   5804: 	  &idput($udom,($uname => $uid));
                   5805:        }
                   5806:     }
                   5807: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5808:     my @tmp=&get('environment',
1.899     raeburn  5809: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  5810:                     'permanentemail','inststatus'],
1.134     albertel 5811: 		   $udom,$uname);
1.313     matthew  5812:     my %names;
                   5813:     if ($tmp[0] =~ m/^error:.*/) { 
                   5814:         %names=(); 
                   5815:     } else {
                   5816:         %names = @tmp;
                   5817:     }
1.388     www      5818: #
                   5819: # Make sure to not trash student environment if instructor does not bother
                   5820: # to supply name and email information
                   5821: #
                   5822:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5823:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5824:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5825:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5826:     if ($email) {
                   5827:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  5828:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      5829:     }
1.899     raeburn  5830:     if ($uid) { $names{'id'}  = $uid; }
1.963     raeburn  5831:     if (defined($inststatus)) { $names{'inststatus'} = $inststatus; } 
1.134     albertel 5832:     my $reply = &put('environment', \%names, $udom,$uname);
                   5833:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5834:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5835:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963     raeburn  5836:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
                   5837:                  $umode.', '.$first.', '.$middle.', '.
                   5838: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
                   5839:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   5840:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   5841:     } else {
                   5842:         $logmsg .= ' during self creation';
                   5843:     }
                   5844:     &logthis($logmsg);
1.134     albertel 5845:     return 'ok';
1.80      www      5846: }
                   5847: 
1.81      www      5848: # -------------------------------------------------------------- Modify student
1.80      www      5849: 
1.81      www      5850: sub modifystudent {
                   5851:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  5852:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
                   5853:         $selfenroll,$context)=@_;
1.455     albertel 5854:     if (!$cid) {
1.620     albertel 5855: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5856: 	    return 'not_in_class';
                   5857: 	}
1.80      www      5858:     }
                   5859: # --------------------------------------------------------------- Make the user
1.81      www      5860:     my $reply=&modifyuser
1.209     matthew  5861: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5862:          $desiredhome,$email);
1.80      www      5863:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5864:     # This will cause &modify_student_enrollment to get the uid from the
                   5865:     # students environment
                   5866:     $uid = undef if (!$forceid);
1.455     albertel 5867:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  5868: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  5869:     return $reply;
                   5870: }
                   5871: 
                   5872: sub modify_student_enrollment {
1.957     raeburn  5873:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 5874:     my ($cdom,$cnum,$chome);
                   5875:     if (!$cid) {
1.620     albertel 5876: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5877: 	    return 'not_in_class';
                   5878: 	}
1.620     albertel 5879: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5880: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5881:     } else {
                   5882: 	($cdom,$cnum)=split(/_/,$cid);
                   5883:     }
1.620     albertel 5884:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5885:     if (!$chome) {
1.457     raeburn  5886: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5887:     }
1.455     albertel 5888:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5889:     # Make sure the user exists
1.81      www      5890:     my $uhome=&homeserver($uname,$udom);
                   5891:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5892: 	return 'error: no such user';
                   5893:     }
1.297     matthew  5894:     # Get student data if we were not given enough information
                   5895:     if (!defined($first)  || $first  eq '' || 
                   5896:         !defined($last)   || $last   eq '' || 
                   5897:         !defined($uid)    || $uid    eq '' || 
                   5898:         !defined($middle) || $middle eq '' || 
                   5899:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5900:         # They did not supply us with enough data to enroll the student, so
                   5901:         # we need to pick up more information.
1.297     matthew  5902:         my %tmp = &get('environment',
1.294     matthew  5903:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5904:                        ,$udom,$uname);
                   5905: 
1.800     albertel 5906:         #foreach my $key (keys(%tmp)) {
                   5907:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5908:         #}
1.294     matthew  5909:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5910:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5911:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5912:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5913:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5914:     }
1.556     albertel 5915:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5916:     my $reply=cput('classlist',
                   5917: 		   {"$uname:$udom" => 
1.515     raeburn  5918: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5919: 		   $cdom,$cnum);
1.81      www      5920:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5921: 	return 'error: '.$reply;
1.652     albertel 5922:     } else {
                   5923: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5924:     }
1.297     matthew  5925:     # Add student role to user
1.83      www      5926:     my $uurl='/'.$cid;
1.81      www      5927:     $uurl=~s/\_/\//g;
                   5928:     if ($usec) {
                   5929: 	$uurl.='/'.$usec;
                   5930:     }
1.957     raeburn  5931:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      5932: }
                   5933: 
1.556     albertel 5934: sub format_name {
                   5935:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5936:     my $name;
                   5937:     if ($first ne 'lastname') {
                   5938: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5939:     } else {
                   5940: 	if ($lastname=~/\S/) {
                   5941: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5942: 	    $name=~s/\s+,/,/;
                   5943: 	} else {
                   5944: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5945: 	}
                   5946:     }
                   5947:     $name=~s/^\s+//;
                   5948:     $name=~s/\s+$//;
                   5949:     $name=~s/\s+/ /g;
                   5950:     return $name;
                   5951: }
                   5952: 
1.84      www      5953: # ------------------------------------------------- Write to course preferences
                   5954: 
                   5955: sub writecoursepref {
                   5956:     my ($courseid,%prefs)=@_;
                   5957:     $courseid=~s/^\///;
                   5958:     $courseid=~s/\_/\//g;
                   5959:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5960:     my $chome=homeserver($cnum,$cdomain);
                   5961:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5962: 	return 'error: no such course';
                   5963:     }
                   5964:     my $cstring='';
1.800     albertel 5965:     foreach my $pref (keys(%prefs)) {
                   5966: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5967:     }
1.84      www      5968:     $cstring=~s/\&$//;
                   5969:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5970: }
                   5971: 
                   5972: # ---------------------------------------------------------- Make/modify course
                   5973: 
                   5974: sub createcourse {
1.741     raeburn  5975:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5976:         $course_owner,$crstype)=@_;
1.84      www      5977:     $url=&declutter($url);
                   5978:     my $cid='';
1.264     matthew  5979:     unless (&allowed('ccc',$udom)) {
1.84      www      5980:         return 'refused';
                   5981:     }
                   5982: # ------------------------------------------------------------------- Create ID
1.674     www      5983:    my $uname=int(1+rand(9)).
                   5984:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5985:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5986:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5987: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5988:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5989:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5990:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5991:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5992:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5993:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5994:            return 'error: unable to generate unique course-ID';
                   5995:        } 
                   5996:    }
1.264     matthew  5997: # ------------------------------------------------ Check supplied server name
1.620     albertel 5998:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5999:     if (! &is_library($course_server)) {
1.264     matthew  6000:         return 'error:bad server name '.$course_server;
                   6001:     }
1.84      www      6002: # ------------------------------------------------------------- Make the course
                   6003:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  6004:                       $course_server);
1.84      www      6005:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 6006:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      6007:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6008: 	return 'error: no such course';
                   6009:     }
1.271     www      6010: # ----------------------------------------------------------------- Course made
1.516     raeburn  6011: # log existence
1.918     raeburn  6012:     my $newcourse = {
                   6013:                     $udom.'_'.$uname => {
1.921     raeburn  6014:                                      description => $description,
                   6015:                                      inst_code   => $inst_code,
                   6016:                                      owner       => $course_owner,
                   6017:                                      type        => $crstype,
1.918     raeburn  6018:                                                 },
                   6019:                     };
1.921     raeburn  6020:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      6021: # set toplevel url
1.271     www      6022:     my $topurl=$url;
                   6023:     unless ($nonstandard) {
                   6024: # ------------------------------------------ For standard courses, make top url
                   6025:         my $mapurl=&clutter($url);
1.278     www      6026:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 6027:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      6028: <map>
                   6029: <resource id="1" type="start"></resource>
                   6030: <resource id="2" src="$mapurl"></resource>
                   6031: <resource id="3" type="finish"></resource>
                   6032: <link index="1" from="1" to="2"></link>
                   6033: <link index="2" from="2" to="3"></link>
                   6034: </map>
                   6035: ENDINITMAP
                   6036:         $topurl=&declutter(
1.638     albertel 6037:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      6038:                           );
                   6039:     }
                   6040: # ----------------------------------------------------------- Write preferences
1.84      www      6041:     &writecoursepref($udom.'_'.$uname,
                   6042:                      ('description' => $description,
1.271     www      6043:                       'url'         => $topurl));
1.84      www      6044:     return '/'.$udom.'/'.$uname;
                   6045: }
                   6046: 
1.813     albertel 6047: sub is_course {
                   6048:     my ($cdom,$cnum) = @_;
                   6049:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  6050: 				undef,'.');
1.813     albertel 6051:     if (exists($courses{$cdom.'_'.$cnum})) {
                   6052:         return 1;
                   6053:     }
                   6054:     return 0;
                   6055: }
                   6056: 
1.21      www      6057: # ---------------------------------------------------------- Assign Custom Role
                   6058: 
                   6059: sub assigncustomrole {
1.957     raeburn  6060:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6061:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  6062:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      6063: }
                   6064: 
                   6065: # ----------------------------------------------------------------- Revoke Role
                   6066: 
                   6067: sub revokerole {
1.957     raeburn  6068:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6069:     my $now=time;
1.965     raeburn  6070:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      6071: }
                   6072: 
                   6073: # ---------------------------------------------------------- Revoke Custom Role
                   6074: 
                   6075: sub revokecustomrole {
1.957     raeburn  6076:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6077:     my $now=time;
1.357     www      6078:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  6079:            $deleteflag,$selfenroll,$context);
1.17      www      6080: }
                   6081: 
1.533     banghart 6082: # ------------------------------------------------------------ Disk usage
1.535     albertel 6083: sub diskusage {
1.955     raeburn  6084:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   6085:     $directorypath =~ s/\/$//;
                   6086:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   6087:                        .&escape($getpropath).':'.&escape($uname).':'
                   6088:                        .&escape($udom),homeserver($uname,$udom));
                   6089:     if ($listing eq 'unknown_cmd') {
                   6090:         if ($getpropath) {
                   6091:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   6092:         }
                   6093:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   6094:     }
1.514     albertel 6095:     return $listing;
1.512     banghart 6096: }
                   6097: 
1.566     banghart 6098: sub is_locked {
                   6099:     my ($file_name, $domain, $user) = @_;
                   6100:     my @check;
                   6101:     my $is_locked;
                   6102:     push @check, $file_name;
1.613     albertel 6103:     my %locked = &get('file_permissions',\@check,
1.620     albertel 6104: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 6105:     my ($tmp)=keys(%locked);
                   6106:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  6107:     
1.566     banghart 6108:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  6109:         $is_locked = 'false';
                   6110:         foreach my $entry (@{$locked{$file_name}}) {
                   6111:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  6112:                $is_locked = 'true';
                   6113:                last;
1.745     raeburn  6114:            }
                   6115:        }
1.566     banghart 6116:     } else {
                   6117:         $is_locked = 'false';
                   6118:     }
                   6119: }
                   6120: 
1.759     albertel 6121: sub declutter_portfile {
                   6122:     my ($file) = @_;
1.833     albertel 6123:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 6124:     return $file;
                   6125: }
                   6126: 
1.559     banghart 6127: # ------------------------------------------------------------- Mark as Read Only
                   6128: 
                   6129: sub mark_as_readonly {
                   6130:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 6131:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6132:     my ($tmp)=keys(%current_permissions);
                   6133:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 6134:     foreach my $file (@{$files}) {
1.759     albertel 6135: 	$file = &declutter_portfile($file);
1.561     banghart 6136:         push(@{$current_permissions{$file}},$what);
1.559     banghart 6137:     }
1.613     albertel 6138:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6139:     return;
                   6140: }
                   6141: 
1.572     banghart 6142: # ------------------------------------------------------------Save Selected Files
                   6143: 
                   6144: sub save_selected_files {
                   6145:     my ($user, $path, @files) = @_;
                   6146:     my $filename = $user."savedfiles";
1.573     banghart 6147:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 6148:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 6149:     foreach my $file (@files) {
1.620     albertel 6150:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 6151:     }
                   6152:     foreach my $file (@other_files) {
1.574     banghart 6153:         print (OUT $file."\n");
1.572     banghart 6154:     }
1.574     banghart 6155:     close (OUT);
1.572     banghart 6156:     return 'ok';
                   6157: }
                   6158: 
1.574     banghart 6159: sub clear_selected_files {
                   6160:     my ($user) = @_;
                   6161:     my $filename = $user."savedfiles";
                   6162:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6163:     print (OUT undef);
                   6164:     close (OUT);
                   6165:     return ("ok");    
                   6166: }
                   6167: 
1.572     banghart 6168: sub files_in_path {
                   6169:     my ($user, $path) = @_;
                   6170:     my $filename = $user."savedfiles";
                   6171:     my %return_files;
1.574     banghart 6172:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 6173:     while (my $line_in = <IN>) {
1.574     banghart 6174:         chomp ($line_in);
                   6175:         my @paths_and_file = split (m!/!, $line_in);
                   6176:         my $file_part = pop (@paths_and_file);
                   6177:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 6178:         $path_part.='/';
                   6179:         my $path_and_file = $path_part.$file_part;
                   6180:         if ($path_part eq $path) {
                   6181:             $return_files{$file_part}= 'selected';
                   6182:         }
                   6183:     }
1.574     banghart 6184:     close (IN);
                   6185:     return (\%return_files);
1.572     banghart 6186: }
                   6187: 
                   6188: # called in portfolio select mode, to show files selected NOT in current directory
                   6189: sub files_not_in_path {
                   6190:     my ($user, $path) = @_;
                   6191:     my $filename = $user."savedfiles";
                   6192:     my @return_files;
                   6193:     my $path_part;
1.800     albertel 6194:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6195:     while (my $line = <IN>) {
1.572     banghart 6196:         #ok, I know it's clunky, but I want it to work
1.800     albertel 6197:         my @paths_and_file = split(m|/|, $line);
                   6198:         my $file_part = pop(@paths_and_file);
                   6199:         chomp($file_part);
                   6200:         my $path_part = join('/', @paths_and_file);
1.572     banghart 6201:         $path_part .= '/';
                   6202:         my $path_and_file = $path_part.$file_part;
                   6203:         if ($path_part ne $path) {
1.800     albertel 6204:             push(@return_files, ($path_and_file));
1.572     banghart 6205:         }
                   6206:     }
1.800     albertel 6207:     close(OUT);
1.574     banghart 6208:     return (@return_files);
1.572     banghart 6209: }
                   6210: 
1.745     raeburn  6211: #----------------------------------------------Get portfolio file permissions
1.629     banghart 6212: 
1.745     raeburn  6213: sub get_portfile_permissions {
                   6214:     my ($domain,$user) = @_;
1.613     albertel 6215:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6216:     my ($tmp)=keys(%current_permissions);
                   6217:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6218:     return \%current_permissions;
                   6219: }
                   6220: 
                   6221: #---------------------------------------------Get portfolio file access controls
                   6222: 
1.749     raeburn  6223: sub get_access_controls {
1.745     raeburn  6224:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 6225:     my %access;
                   6226:     my $real_file = $file;
                   6227:     $file =~ s/\.meta$//;
1.745     raeburn  6228:     if (defined($file)) {
1.749     raeburn  6229:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   6230:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 6231:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  6232:             }
                   6233:         }
1.745     raeburn  6234:     } else {
1.749     raeburn  6235:         foreach my $key (keys(%{$current_permissions})) {
                   6236:             if ($key =~ /\0accesscontrol$/) {
                   6237:                 if (defined($group)) {
                   6238:                     if ($key !~ m-^\Q$group\E/-) {
                   6239:                         next;
                   6240:                     }
                   6241:                 }
                   6242:                 my ($fullpath) = split(/\0/,$key);
                   6243:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   6244:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   6245:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   6246:                     }
                   6247:                 }
                   6248:             }
                   6249:         }
                   6250:     }
                   6251:     return %access;
                   6252: }
                   6253: 
                   6254: sub modify_access_controls {
                   6255:     my ($file_name,$changes,$domain,$user)=@_;
                   6256:     my ($outcome,$deloutcome);
                   6257:     my %store_permissions;
                   6258:     my %new_values;
                   6259:     my %new_control;
                   6260:     my %translation;
                   6261:     my @deletions = ();
                   6262:     my $now = time;
                   6263:     if (exists($$changes{'activate'})) {
                   6264:         if (ref($$changes{'activate'}) eq 'HASH') {
                   6265:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   6266:             my $numnew = scalar(@newitems);
                   6267:             for (my $i=0; $i<$numnew; $i++) {
                   6268:                 my $newkey = $newitems[$i];
                   6269:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  6270:                 if ($newkey =~ /^\d+:/) { 
                   6271:                     $newkey =~ s/^(\d+)/$newid/;
                   6272:                     $translation{$1} = $newid;
                   6273:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   6274:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   6275:                     $translation{$1} = $newid;
                   6276:                 }
1.749     raeburn  6277:                 $new_values{$file_name."\0".$newkey} = 
                   6278:                                           $$changes{'activate'}{$newitems[$i]};
                   6279:                 $new_control{$newkey} = $now;
                   6280:             }
                   6281:         }
                   6282:     }
                   6283:     my %todelete;
                   6284:     my %changed_items;
                   6285:     foreach my $action ('delete','update') {
                   6286:         if (exists($$changes{$action})) {
                   6287:             if (ref($$changes{$action}) eq 'HASH') {
                   6288:                 foreach my $key (keys(%{$$changes{$action}})) {
                   6289:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   6290:                     if ($action eq 'delete') { 
                   6291:                         $todelete{$itemnum} = 1;
                   6292:                     } else {
                   6293:                         $changed_items{$itemnum} = $key;
                   6294:                     }
                   6295:                 }
1.745     raeburn  6296:             }
                   6297:         }
1.749     raeburn  6298:     }
                   6299:     # get lock on access controls for file.
                   6300:     my $lockhash = {
                   6301:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   6302:                                                        ':'.$env{'user.domain'},
                   6303:                    }; 
                   6304:     my $tries = 0;
                   6305:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6306:    
                   6307:     while (($gotlock ne 'ok') && $tries <3) {
                   6308:         $tries ++;
                   6309:         sleep 1;
                   6310:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6311:     }
                   6312:     if ($gotlock eq 'ok') {
                   6313:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6314:         my ($tmp)=keys(%curr_permissions);
                   6315:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6316:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6317:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6318:             if (ref($curr_controls) eq 'HASH') {
                   6319:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6320:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6321:                     if (defined($todelete{$itemnum})) {
                   6322:                         push(@deletions,$file_name."\0".$control_item);
                   6323:                     } else {
                   6324:                         if (defined($changed_items{$itemnum})) {
                   6325:                             $new_control{$changed_items{$itemnum}} = $now;
                   6326:                             push(@deletions,$file_name."\0".$control_item);
                   6327:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6328:                         } else {
                   6329:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6330:                         }
                   6331:                     }
1.745     raeburn  6332:                 }
                   6333:             }
                   6334:         }
1.970     raeburn  6335:         my ($group);
                   6336:         if (&is_course($domain,$user)) {
                   6337:             ($group,my $file) = split(/\//,$file_name,2);
                   6338:         }
1.749     raeburn  6339:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6340:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6341:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6342:         #  remove lock
                   6343:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6344:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6345:         my $sqlresult =
1.970     raeburn  6346:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  6347:                                     $group);
1.749     raeburn  6348:     } else {
                   6349:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6350:     }
1.749     raeburn  6351:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6352: }
                   6353: 
1.827     raeburn  6354: sub make_public_indefinitely {
                   6355:     my ($requrl) = @_;
                   6356:     my $now = time;
                   6357:     my $action = 'activate';
                   6358:     my $aclnum = 0;
                   6359:     if (&is_portfolio_url($requrl)) {
                   6360:         my (undef,$udom,$unum,$file_name,$group) =
                   6361:             &parse_portfolio_url($requrl);
                   6362:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6363:         my %access_controls = &get_access_controls($current_perms,
                   6364:                                                    $group,$file_name);
                   6365:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6366:             my ($num,$scope,$end,$start) = 
                   6367:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6368:             if ($scope eq 'public') {
                   6369:                 if ($start <= $now && $end == 0) {
                   6370:                     $action = 'none';
                   6371:                 } else {
                   6372:                     $action = 'update';
                   6373:                     $aclnum = $num;
                   6374:                 }
                   6375:                 last;
                   6376:             }
                   6377:         }
                   6378:         if ($action eq 'none') {
                   6379:              return 'ok';
                   6380:         } else {
                   6381:             my %changes;
                   6382:             my $newend = 0;
                   6383:             my $newstart = $now;
                   6384:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6385:             $changes{$action}{$newkey} = {
                   6386:                 type => 'public',
                   6387:                 time => {
                   6388:                     start => $newstart,
                   6389:                     end   => $newend,
                   6390:                 },
                   6391:             };
                   6392:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6393:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6394:             return $outcome;
                   6395:         }
                   6396:     } else {
                   6397:         return 'invalid';
                   6398:     }
                   6399: }
                   6400: 
1.745     raeburn  6401: #------------------------------------------------------Get Marked as Read Only
                   6402: 
                   6403: sub get_marked_as_readonly {
                   6404:     my ($domain,$user,$what,$group) = @_;
                   6405:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6406:     my @readonly_files;
1.629     banghart 6407:     my $cmp1=$what;
                   6408:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6409:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6410:         if (defined($group)) {
                   6411:             if ($file_name !~ m-^\Q$group\E/-) {
                   6412:                 next;
                   6413:             }
                   6414:         }
1.561     banghart 6415:         if (ref($value) eq "ARRAY"){
                   6416:             foreach my $stored_what (@{$value}) {
1.629     banghart 6417:                 my $cmp2=$stored_what;
1.759     albertel 6418:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6419:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6420:                 }
1.629     banghart 6421:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6422:                     push(@readonly_files, $file_name);
1.745     raeburn  6423:                     last;
1.563     banghart 6424:                 } elsif (!defined($what)) {
                   6425:                     push(@readonly_files, $file_name);
1.745     raeburn  6426:                     last;
1.561     banghart 6427:                 }
                   6428:             }
1.745     raeburn  6429:         }
1.561     banghart 6430:     }
                   6431:     return @readonly_files;
                   6432: }
1.577     banghart 6433: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6434: 
1.577     banghart 6435: sub get_marked_as_readonly_hash {
1.745     raeburn  6436:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6437:     my %readonly_files;
1.745     raeburn  6438:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6439:         if (defined($group)) {
                   6440:             if ($file_name !~ m-^\Q$group\E/-) {
                   6441:                 next;
                   6442:             }
                   6443:         }
1.577     banghart 6444:         if (ref($value) eq "ARRAY"){
                   6445:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6446:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6447:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6448:                         if ($lock_descriptor eq 'graded') {
                   6449:                             $readonly_files{$file_name} = 'graded';
                   6450:                         } elsif ($lock_descriptor eq 'handback') {
                   6451:                             $readonly_files{$file_name} = 'handback';
                   6452:                         } else {
                   6453:                             if (!exists($readonly_files{$file_name})) {
                   6454:                                 $readonly_files{$file_name} = 'locked';
                   6455:                             }
                   6456:                         }
1.745     raeburn  6457:                     }
1.750     banghart 6458:                 } 
1.577     banghart 6459:             }
                   6460:         } 
                   6461:     }
                   6462:     return %readonly_files;
                   6463: }
1.559     banghart 6464: # ------------------------------------------------------------ Unmark as Read Only
                   6465: 
                   6466: sub unmark_as_readonly {
1.629     banghart 6467:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6468:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6469:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6470:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6471:     my $symb_crs = $what;
                   6472:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6473:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6474:     my ($tmp)=keys(%current_permissions);
                   6475:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6476:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6477:     foreach my $file (@readonly_files) {
1.759     albertel 6478: 	my $clean_file = &declutter_portfile($file);
                   6479: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6480: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6481:         my @new_locks;
                   6482:         my @del_keys;
                   6483:         if (ref($current_locks) eq "ARRAY"){
                   6484:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6485:                 my $compare=$locker;
1.749     raeburn  6486:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6487:                     $compare=join('',@{$locker});
1.746     raeburn  6488:                     if ($compare ne $symb_crs) {
                   6489:                         push(@new_locks, $locker);
                   6490:                     }
1.563     banghart 6491:                 }
                   6492:             }
1.650     albertel 6493:             if (scalar(@new_locks) > 0) {
1.563     banghart 6494:                 $current_permissions{$file} = \@new_locks;
                   6495:             } else {
                   6496:                 push(@del_keys, $file);
1.613     albertel 6497:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6498:                 delete($current_permissions{$file});
1.563     banghart 6499:             }
                   6500:         }
1.561     banghart 6501:     }
1.613     albertel 6502:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6503:     return;
                   6504: }
1.512     banghart 6505: 
1.17      www      6506: # ------------------------------------------------------------ Directory lister
                   6507: 
                   6508: sub dirlist {
1.955     raeburn  6509:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      6510:     $uri=~s/^\///;
                   6511:     $uri=~s/\/$//;
1.253     stredwic 6512:     my ($udom, $uname);
1.955     raeburn  6513:     if ($getuserdir) {
1.253     stredwic 6514:         $udom = $userdomain;
                   6515:         $uname = $username;
1.955     raeburn  6516:     } else {
                   6517:         (undef,$udom,$uname)=split(/\//,$uri);
                   6518:         if(defined($userdomain)) {
                   6519:             $udom = $userdomain;
                   6520:         }
                   6521:         if(defined($username)) {
                   6522:             $uname = $username;
                   6523:         }
1.253     stredwic 6524:     }
1.955     raeburn  6525:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 6526: 
1.955     raeburn  6527:     $dirRoot = $perlvar{'lonDocRoot'};
                   6528:     if (defined($getpropath)) {
                   6529:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 6530:         $dirRoot =~ s/\/$//;
1.955     raeburn  6531:     } elsif (defined($getuserdir)) {
                   6532:         my $subdir=$uname.'__';
                   6533:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6534:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   6535:                    ."/$udom/$subdir/$uname";
                   6536:     } elsif (defined($alternateRoot)) {
                   6537:         $dirRoot = $alternateRoot;
1.751     banghart 6538:     }
1.253     stredwic 6539: 
                   6540:     if($udom) {
                   6541:         if($uname) {
1.955     raeburn  6542:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  6543:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  6544:                               .':'.&escape($uname).':'.&escape($udom),
                   6545:                               &homeserver($uname,$udom));
                   6546:             if ($listing eq 'unknown_cmd') {
                   6547:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6548:                                   &homeserver($uname,$udom));
                   6549:             } else {
                   6550:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6551:             }
1.605     matthew  6552:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6553:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6554: 				  &homeserver($uname,$udom));
1.605     matthew  6555:                 @listing_results = split(/:/,$listing);
                   6556:             } else {
                   6557:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6558:             }
                   6559:             return @listing_results;
1.955     raeburn  6560:         } elsif(!$alternateRoot) {
1.800     albertel 6561:             my %allusers;
1.841     albertel 6562: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  6563:  	    foreach my $tryserver (keys(%servers)) {
                   6564:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   6565:                                   &escape($udom),$tryserver);
                   6566:                 if ($listing eq 'unknown_cmd') {
                   6567: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6568: 				      $udom, $tryserver);
                   6569:                 } else {
                   6570:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6571:                 }
1.841     albertel 6572: 		if ($listing eq 'unknown_cmd') {
                   6573: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6574: 				      $udom, $tryserver);
                   6575: 		    @listing_results = split(/:/,$listing);
                   6576: 		} else {
                   6577: 		    @listing_results =
                   6578: 			map { &unescape($_); } split(/:/,$listing);
                   6579: 		}
                   6580: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6581: 		    $listing_results[0] ne 'empty'       &&
                   6582: 		    $listing_results[0] ne 'con_lost') {
                   6583: 		    foreach my $line (@listing_results) {
                   6584: 			my ($entry) = split(/&/,$line,2);
                   6585: 			$allusers{$entry} = 1;
                   6586: 		    }
                   6587: 		}
1.253     stredwic 6588:             }
                   6589:             my $alluserstr='';
1.800     albertel 6590:             foreach my $user (sort(keys(%allusers))) {
                   6591:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6592:             }
                   6593:             $alluserstr=~s/:$//;
                   6594:             return split(/:/,$alluserstr);
                   6595:         } else {
1.800     albertel 6596:             return ('missing user name');
1.253     stredwic 6597:         }
1.955     raeburn  6598:     } elsif(!defined($getpropath)) {
1.841     albertel 6599:         my @all_domains = sort(&all_domains());
1.955     raeburn  6600:         foreach my $domain (@all_domains) {
                   6601:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6602:         }
                   6603:         return @all_domains;
                   6604:     } else {
1.800     albertel 6605:         return ('missing domain');
1.275     stredwic 6606:     }
                   6607: }
                   6608: 
                   6609: # --------------------------------------------- GetFileTimestamp
                   6610: # This function utilizes dirlist and returns the date stamp for
                   6611: # when it was last modified.  It will also return an error of -1
                   6612: # if an error occurs
                   6613: 
                   6614: sub GetFileTimestamp {
1.955     raeburn  6615:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 6616:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6617:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  6618:     my ($fileStat) = 
                   6619:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   6620:                                  undef,$getuserdir);
1.275     stredwic 6621:     my @stats = split('&', $fileStat);
                   6622:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6623:         # @stats contains first the filename, then the stat output
                   6624:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6625:     } else {
                   6626:         return -1;
1.253     stredwic 6627:     }
1.26      www      6628: }
                   6629: 
1.712     albertel 6630: sub stat_file {
                   6631:     my ($uri) = @_;
1.787     albertel 6632:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6633: 
1.955     raeburn  6634:     my ($udom,$uname,$file);
1.712     albertel 6635:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6636: 	($udom,$uname,$file) =
1.811     albertel 6637: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6638: 	$file = 'userfiles/'.$file;
                   6639:     }
                   6640:     if ($uri =~ m-^/res/-) {
                   6641: 	($udom,$uname) = 
1.807     albertel 6642: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6643: 	$file = $uri;
                   6644:     }
                   6645: 
                   6646:     if (!$udom || !$uname || !$file) {
                   6647: 	# unable to handle the uri
                   6648: 	return ();
                   6649:     }
1.956     raeburn  6650:     my $getpropath;
                   6651:     if ($file =~ /^userfiles\//) {
                   6652:         $getpropath = 1;
                   6653:     }
1.955     raeburn  6654:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 6655:     my @stats = split('&', $result);
1.721     banghart 6656:     
1.712     albertel 6657:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6658: 	shift(@stats); #filename is first
                   6659: 	return @stats;
                   6660:     }
                   6661:     return ();
                   6662: }
                   6663: 
1.26      www      6664: # -------------------------------------------------------- Value of a Condition
                   6665: 
1.713     albertel 6666: # gets the value of a specific preevaluated condition
                   6667: #    stored in the string  $env{user.state.<cid>}
                   6668: # or looks up a condition reference in the bighash and if if hasn't
                   6669: # already been evaluated recurses into docondval to get the value of
                   6670: # the condition, then memoizing it to 
                   6671: #   $env{user.state.<cid>.<condition>}
1.40      www      6672: sub directcondval {
                   6673:     my $number=shift;
1.620     albertel 6674:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6675: 	&Apache::lonuserstate::evalstate();
                   6676:     }
1.713     albertel 6677:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6678: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6679:     } elsif ($number =~ /^_/) {
                   6680: 	my $sub_condition;
                   6681: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6682: 		&GDBM_READER(),0640)) {
                   6683: 	    $sub_condition=$bighash{'conditions'.$number};
                   6684: 	    untie(%bighash);
                   6685: 	}
                   6686: 	my $value = &docondval($sub_condition);
1.949     raeburn  6687: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 6688: 	return $value;
                   6689:     }
1.620     albertel 6690:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6691:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6692:     } else {
                   6693:        return 2;
                   6694:     }
                   6695: }
                   6696: 
1.713     albertel 6697: # get the collection of conditions for this resource
1.26      www      6698: sub condval {
                   6699:     my $condidx=shift;
1.54      www      6700:     my $allpathcond='';
1.713     albertel 6701:     foreach my $cond (split(/\|/,$condidx)) {
                   6702: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6703: 	    $allpathcond.=
                   6704: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6705: 	}
1.191     harris41 6706:     }
1.54      www      6707:     $allpathcond=~s/\|$//;
1.713     albertel 6708:     return &docondval($allpathcond);
                   6709: }
                   6710: 
                   6711: #evaluates an expression of conditions
                   6712: sub docondval {
                   6713:     my ($allpathcond) = @_;
                   6714:     my $result=0;
                   6715:     if ($env{'request.course.id'}
                   6716: 	&& defined($allpathcond)) {
                   6717: 	my $operand='|';
                   6718: 	my @stack;
                   6719: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6720: 	    if ($chunk eq '(') {
                   6721: 		push @stack,($operand,$result);
                   6722: 	    } elsif ($chunk eq ')') {
                   6723: 		my $before=pop @stack;
                   6724: 		if (pop @stack eq '&') {
                   6725: 		    $result=$result>$before?$before:$result;
                   6726: 		} else {
                   6727: 		    $result=$result>$before?$result:$before;
                   6728: 		}
                   6729: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6730: 		$operand=$chunk;
                   6731: 	    } else {
                   6732: 		my $new=directcondval($chunk);
                   6733: 		if ($operand eq '&') {
                   6734: 		    $result=$result>$new?$new:$result;
                   6735: 		} else {
                   6736: 		    $result=$result>$new?$result:$new;
                   6737: 		}
                   6738: 	    }
                   6739: 	}
1.26      www      6740:     }
                   6741:     return $result;
1.421     albertel 6742: }
                   6743: 
                   6744: # ---------------------------------------------------- Devalidate courseresdata
                   6745: 
                   6746: sub devalidatecourseresdata {
                   6747:     my ($coursenum,$coursedomain)=@_;
                   6748:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6749:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6750: }
                   6751: 
1.763     www      6752: 
1.200     www      6753: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6754: #
                   6755: #  Parameters:
                   6756: #      $coursenum    - Number of the course.
                   6757: #      $coursedomain - Domain at which the course was created.
                   6758: #  Returns:
                   6759: #     A hash of the course parameters along (I think) with timestamps
                   6760: #     and version info.
1.877     foxr     6761: 
1.624     albertel 6762: sub get_courseresdata {
                   6763:     my ($coursenum,$coursedomain)=@_;
1.200     www      6764:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6765:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6766:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6767:     my %dumpreply;
1.417     albertel 6768:     unless (defined($cached)) {
1.624     albertel 6769: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6770: 	$result=\%dumpreply;
1.251     albertel 6771: 	my ($tmp) = keys(%dumpreply);
                   6772: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6773: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6774: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6775: 	    return $tmp;
1.416     albertel 6776: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6777: 	    $result=undef;
1.599     albertel 6778: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6779: 	}
                   6780:     }
1.624     albertel 6781:     return $result;
                   6782: }
                   6783: 
1.633     albertel 6784: sub devalidateuserresdata {
                   6785:     my ($uname,$udom)=@_;
                   6786:     my $hashid="$udom:$uname";
                   6787:     &devalidate_cache_new('userres',$hashid);
                   6788: }
                   6789: 
1.624     albertel 6790: sub get_userresdata {
                   6791:     my ($uname,$udom)=@_;
                   6792:     #most student don\'t have any data set, check if there is some data
                   6793:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6794: 
                   6795:     my $hashid="$udom:$uname";
                   6796:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6797:     if (!defined($cached)) {
                   6798: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6799: 	$result=\%resourcedata;
                   6800: 	&do_cache_new('userres',$hashid,$result,600);
                   6801:     }
                   6802:     my ($tmp)=keys(%$result);
                   6803:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6804: 	return $result;
                   6805:     }
                   6806:     #error 2 occurs when the .db doesn't exist
                   6807:     if ($tmp!~/error: 2 /) {
1.672     albertel 6808: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6809: 		 " Trying to get resource data for ".
                   6810: 		 $uname." at ".$udom.": ".
                   6811: 		 $tmp."</font>");
                   6812:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6813: 	#&EXT_cache_set($udom,$uname);
                   6814: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6815: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6816:     }
                   6817:     return $tmp;
                   6818: }
1.879     foxr     6819: #----------------------------------------------- resdata - return resource data
                   6820: #  Purpose:
                   6821: #    Return resource data for either users or for a course.
                   6822: #  Parameters:
                   6823: #     $name      - Course/user name.
                   6824: #     $domain    - Name of the domain the user/course is registered on.
                   6825: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6826: #     @which     - Array of names of resources desired.
                   6827: #  Returns:
                   6828: #     The value of the first reasource in @which that is found in the
                   6829: #     resource hash.
                   6830: #  Exceptional Conditions:
                   6831: #     If the $type passed in is not valid (not the string 'course' or 
                   6832: #     'user', an undefined  reference is returned.
                   6833: #     If none of the resources are found, an undef is returned
1.624     albertel 6834: sub resdata {
                   6835:     my ($name,$domain,$type,@which)=@_;
                   6836:     my $result;
                   6837:     if ($type eq 'course') {
                   6838: 	$result=&get_courseresdata($name,$domain);
                   6839:     } elsif ($type eq 'user') {
                   6840: 	$result=&get_userresdata($name,$domain);
                   6841:     }
                   6842:     if (!ref($result)) { return $result; }    
1.251     albertel 6843:     foreach my $item (@which) {
1.927     albertel 6844: 	if (defined($result->{$item->[0]})) {
                   6845: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 6846: 	}
1.250     albertel 6847:     }
1.291     albertel 6848:     return undef;
1.200     www      6849: }
                   6850: 
1.379     matthew  6851: #
                   6852: # EXT resource caching routines
                   6853: #
                   6854: 
                   6855: sub clear_EXT_cache_status {
1.383     albertel 6856:     &delenv('cache.EXT.');
1.379     matthew  6857: }
                   6858: 
                   6859: sub EXT_cache_status {
                   6860:     my ($target_domain,$target_user) = @_;
1.383     albertel 6861:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6862:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6863:         # We know already the user has no data
                   6864:         return 1;
                   6865:     } else {
                   6866:         return 0;
                   6867:     }
                   6868: }
                   6869: 
                   6870: sub EXT_cache_set {
                   6871:     my ($target_domain,$target_user) = @_;
1.383     albertel 6872:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  6873:     #&appenv({$cachename => time});
1.379     matthew  6874: }
                   6875: 
1.28      www      6876: # --------------------------------------------------------- Value of a Variable
1.58      www      6877: sub EXT {
1.715     albertel 6878: 
1.395     albertel 6879:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6880:     unless ($varname) { return ''; }
1.218     albertel 6881:     #get real user name/domain, courseid and symb
                   6882:     my $courseid;
1.359     albertel 6883:     my $publicuser;
1.427     www      6884:     if ($symbparm) {
                   6885: 	$symbparm=&get_symb_from_alias($symbparm);
                   6886:     }
1.218     albertel 6887:     if (!($uname && $udom)) {
1.790     albertel 6888:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6889:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6890:     } else {
1.620     albertel 6891: 	$courseid=$env{'request.course.id'};
1.218     albertel 6892:     }
1.48      www      6893:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6894:     my $rest;
1.320     albertel 6895:     if (defined($therest[0])) {
1.48      www      6896:        $rest=join('.',@therest);
                   6897:     } else {
                   6898:        $rest='';
                   6899:     }
1.320     albertel 6900: 
1.57      www      6901:     my $qualifierrest=$qualifier;
                   6902:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6903:     my $spacequalifierrest=$space;
                   6904:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6905:     if ($realm eq 'user') {
1.48      www      6906: # --------------------------------------------------------------- user.resource
                   6907: 	if ($space eq 'resource') {
1.651     albertel 6908: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6909: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6910: 		 &&
1.744     albertel 6911: 		 ($symbparm eq &symbread()) ) {	
                   6912: 		# if we are in the middle of processing the resource the
                   6913: 		# get the value we are planning on committing
                   6914:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6915:                     return $Apache::lonhomework::results{$qualifierrest};
                   6916:                 } else {
                   6917:                     return $Apache::lonhomework::history{$qualifierrest};
                   6918:                 }
1.335     albertel 6919: 	    } else {
1.359     albertel 6920: 		my %restored;
1.620     albertel 6921: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6922: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6923: 		} else {
                   6924: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6925: 		}
1.335     albertel 6926: 		return $restored{$qualifierrest};
                   6927: 	    }
1.48      www      6928: # ----------------------------------------------------------------- user.access
                   6929:         } elsif ($space eq 'access') {
1.218     albertel 6930: 	    # FIXME - not supporting calls for a specific user
1.48      www      6931:             return &allowed($qualifier,$rest);
                   6932: # ------------------------------------------ user.preferences, user.environment
                   6933:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6934: 	    if (($uname eq $env{'user.name'}) &&
                   6935: 		($udom eq $env{'user.domain'})) {
                   6936: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6937: 	    } else {
1.359     albertel 6938: 		my %returnhash;
                   6939: 		if (!$publicuser) {
                   6940: 		    %returnhash=&userenvironment($udom,$uname,
                   6941: 						 $qualifierrest);
                   6942: 		}
1.218     albertel 6943: 		return $returnhash{$qualifierrest};
                   6944: 	    }
1.48      www      6945: # ----------------------------------------------------------------- user.course
                   6946:         } elsif ($space eq 'course') {
1.218     albertel 6947: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6948:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6949: # ------------------------------------------------------------------- user.role
                   6950:         } elsif ($space eq 'role') {
1.218     albertel 6951: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6952:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6953:             if ($qualifier eq 'value') {
                   6954: 		return $role;
                   6955:             } elsif ($qualifier eq 'extent') {
                   6956:                 return $where;
                   6957:             }
                   6958: # ----------------------------------------------------------------- user.domain
                   6959:         } elsif ($space eq 'domain') {
1.218     albertel 6960:             return $udom;
1.48      www      6961: # ------------------------------------------------------------------- user.name
                   6962:         } elsif ($space eq 'name') {
1.218     albertel 6963:             return $uname;
1.48      www      6964: # ---------------------------------------------------- Any other user namespace
1.29      www      6965:         } else {
1.359     albertel 6966: 	    my %reply;
                   6967: 	    if (!$publicuser) {
                   6968: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6969: 	    }
                   6970: 	    return $reply{$qualifierrest};
1.48      www      6971:         }
1.236     www      6972:     } elsif ($realm eq 'query') {
                   6973: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6974:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6975: 						[$spacequalifierrest]);
1.620     albertel 6976: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6977:    } elsif ($realm eq 'request') {
1.48      www      6978: # ------------------------------------------------------------- request.browser
                   6979:         if ($space eq 'browser') {
1.430     www      6980: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6981: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6982: 		    return 1;
                   6983: 		} else {
                   6984: 		    return 0;
                   6985: 		}
                   6986: 	    } else {
1.620     albertel 6987: 		return $env{'browser.'.$qualifier};
1.430     www      6988: 	    }
1.57      www      6989: # ------------------------------------------------------------ request.filename
                   6990:         } else {
1.620     albertel 6991:             return $env{'request.'.$spacequalifierrest};
1.29      www      6992:         }
1.28      www      6993:     } elsif ($realm eq 'course') {
1.48      www      6994: # ---------------------------------------------------------- course.description
1.620     albertel 6995:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6996:     } elsif ($realm eq 'resource') {
1.165     www      6997: 
1.620     albertel 6998: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6999: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   7000: 	}
1.693     albertel 7001: 
                   7002: 	if ($space eq 'title') {
                   7003: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   7004: 	    return &gettitle($symbparm);
                   7005: 	}
                   7006: 	
                   7007: 	if ($space eq 'map') {
                   7008: 	    my ($map) = &decode_symb($symbparm);
                   7009: 	    return &symbread($map);
                   7010: 	}
1.905     albertel 7011: 	if ($space eq 'filename') {
                   7012: 	    if ($symbparm) {
                   7013: 		return &clutter((&decode_symb($symbparm))[2]);
                   7014: 	    }
                   7015: 	    return &hreflocation('',$env{'request.filename'});
                   7016: 	}
1.693     albertel 7017: 
                   7018: 	my ($section, $group, @groups);
1.593     albertel 7019: 	my ($courselevelm,$courselevel);
1.539     albertel 7020: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7021: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      7022: 
1.218     albertel 7023: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      7024: 
1.60      www      7025: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 7026: 	    my $symbp=$symbparm;
1.735     albertel 7027: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 7028: 
                   7029: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   7030: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   7031: 
1.620     albertel 7032: 	    if (($env{'user.name'} eq $uname) &&
                   7033: 		($env{'user.domain'} eq $udom)) {
                   7034: 		$section=$env{'request.course.sec'};
1.733     raeburn  7035:                 @groups = split(/:/,$env{'request.course.groups'});  
                   7036:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 7037: 	    } else {
1.539     albertel 7038: 		if (! defined($usection)) {
1.551     albertel 7039: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 7040: 		} else {
                   7041: 		    $section = $usection;
                   7042: 		}
1.733     raeburn  7043:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 7044: 	    }
                   7045: 
                   7046: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   7047: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   7048: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   7049: 
1.593     albertel 7050: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 7051: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 7052: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      7053: 
1.60      www      7054: # ----------------------------------------------------------- first, check user
1.624     albertel 7055: 
                   7056: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 7057: 				       ([$courselevelr,'resource'],
                   7058: 					[$courselevelm,'map'     ],
                   7059: 					[$courselevel, 'course'  ]));
1.931     albertel 7060: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      7061: 
1.594     albertel 7062: # ------------------------------------------------ second, check some of course
1.684     raeburn  7063:             my $coursereply;
1.691     raeburn  7064:             if (@groups > 0) {
                   7065:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   7066:                                        $mapparm,$spacequalifierrest);
1.927     albertel 7067:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  7068:             }
1.96      www      7069: 
1.684     raeburn  7070: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 7071: 				  $env{'course.'.$courseid.'.domain'},
                   7072: 				  'course',
                   7073: 				  ([$seclevelr,   'resource'],
                   7074: 				   [$seclevelm,   'map'     ],
                   7075: 				   [$seclevel,    'course'  ],
                   7076: 				   [$courselevelr,'resource']));
                   7077: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      7078: 
1.60      www      7079: # ------------------------------------------------------ third, check map parms
1.218     albertel 7080: 	    my %parmhash=();
                   7081: 	    my $thisparm='';
                   7082: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 7083: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 7084: 		    &GDBM_READER(),0640)) {
1.218     albertel 7085: 		$thisparm=$parmhash{$symbparm};
                   7086: 		untie(%parmhash);
                   7087: 	    }
1.927     albertel 7088: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 7089: 	}
1.594     albertel 7090: # ------------------------------------------ fourth, look in resource metadata
1.71      www      7091: 
1.218     albertel 7092: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 7093: 	my $filename;
                   7094: 	if (!$symbparm) { $symbparm=&symbread(); }
                   7095: 	if ($symbparm) {
1.409     www      7096: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 7097: 	} else {
1.620     albertel 7098: 	    $filename=$env{'request.filename'};
1.282     albertel 7099: 	}
                   7100: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 7101: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 7102: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 7103: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      7104: 
1.927     albertel 7105: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 7106: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7107: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 7108: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   7109: 				     $env{'course.'.$courseid.'.domain'},
                   7110: 				     'course',
1.927     albertel 7111: 				     ([$courselevelm,'map'   ],
                   7112: 				      [$courselevel, 'course']));
                   7113: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 7114: 	}
1.145     www      7115: # ------------------------------------------------------------------ Cascade up
1.218     albertel 7116: 	unless ($space eq '0') {
1.336     albertel 7117: 	    my @parts=split(/_/,$space);
                   7118: 	    my $id=pop(@parts);
                   7119: 	    my $part=join('_',@parts);
                   7120: 	    if ($part eq '') { $part='0'; }
1.927     albertel 7121: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 7122: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  7123: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 7124: 	}
1.395     albertel 7125: 	if ($recurse) { return undef; }
                   7126: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 7127: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      7128: # ---------------------------------------------------- Any other user namespace
                   7129:     } elsif ($realm eq 'environment') {
                   7130: # ----------------------------------------------------------------- environment
1.620     albertel 7131: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   7132: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 7133: 	} else {
1.770     albertel 7134: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   7135: 		return '';
                   7136: 	    }
1.219     albertel 7137: 	    my %returnhash=&userenvironment($udom,$uname,
                   7138: 					    $spacequalifierrest);
                   7139: 	    return $returnhash{$spacequalifierrest};
                   7140: 	}
1.28      www      7141:     } elsif ($realm eq 'system') {
1.48      www      7142: # ----------------------------------------------------------------- system.time
                   7143: 	if ($space eq 'time') {
                   7144: 	    return time;
                   7145:         }
1.696     albertel 7146:     } elsif ($realm eq 'server') {
                   7147: # ----------------------------------------------------------------- system.time
                   7148: 	if ($space eq 'name') {
                   7149: 	    return $ENV{'SERVER_NAME'};
                   7150:         }
1.28      www      7151:     }
1.48      www      7152:     return '';
1.61      www      7153: }
                   7154: 
1.927     albertel 7155: sub get_reply {
                   7156:     my ($reply_value) = @_;
1.940     raeburn  7157:     if (ref($reply_value) eq 'ARRAY') {
                   7158:         if (wantarray) {
                   7159: 	    return @$reply_value;
                   7160:         }
                   7161:         return $reply_value->[0];
                   7162:     } else {
                   7163:         return $reply_value;
1.927     albertel 7164:     }
                   7165: }
                   7166: 
1.691     raeburn  7167: sub check_group_parms {
                   7168:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   7169:     my @groupitems = ();
                   7170:     my $resultitem;
1.927     albertel 7171:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  7172:     foreach my $group (@{$groups}) {
                   7173:         foreach my $level (@levels) {
1.927     albertel 7174:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   7175:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  7176:         }
                   7177:     }
                   7178:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   7179:                             $env{'course.'.$courseid.'.domain'},
                   7180:                                      'course',@groupitems);
                   7181:     return $coursereply;
                   7182: }
                   7183: 
                   7184: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  7185:     my ($courseid,@groups) = @_;
                   7186:     @groups = sort(@groups);
1.691     raeburn  7187:     return @groups;
                   7188: }
                   7189: 
1.395     albertel 7190: sub packages_tab_default {
                   7191:     my ($uri,$varname)=@_;
                   7192:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 7193: 
                   7194:     my (@extension,@specifics,$do_default);
                   7195:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 7196: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 7197: 	if ($pack_type eq 'default') {
                   7198: 	    $do_default=1;
                   7199: 	} elsif ($pack_type eq 'extension') {
                   7200: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 7201: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 7202: 	    # only look at packages defaults for packages that this id is
1.738     albertel 7203: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   7204: 	}
                   7205:     }
                   7206:     # first look for a package that matches the requested part id
                   7207:     foreach my $package (@specifics) {
                   7208: 	my (undef,$pack_type,$pack_part)=@{$package};
                   7209: 	next if ($pack_part ne $part);
                   7210: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7211: 	    return $packagetab{"$pack_type&$name&default"};
                   7212: 	}
                   7213:     }
                   7214:     # look for any possible matching non extension_ package
                   7215:     foreach my $package (@specifics) {
                   7216: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 7217: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7218: 	    return $packagetab{"$pack_type&$name&default"};
                   7219: 	}
1.585     albertel 7220: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 7221: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   7222: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 7223: 	}
                   7224:     }
1.738     albertel 7225:     # look for any posible extension_ match
                   7226:     foreach my $package (@extension) {
                   7227: 	my ($package,$pack_type)=@{$package};
                   7228: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7229: 	    return $packagetab{"$pack_type&$name&default"};
                   7230: 	}
                   7231: 	if (defined($packagetab{$package."&$name&default"})) {
                   7232: 	    return $packagetab{$package."&$name&default"};
                   7233: 	}
                   7234:     }
                   7235:     # look for a global default setting
                   7236:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   7237: 	return $packagetab{"default&$name&default"};
                   7238:     }
1.395     albertel 7239:     return undef;
                   7240: }
                   7241: 
1.334     albertel 7242: sub add_prefix_and_part {
                   7243:     my ($prefix,$part)=@_;
                   7244:     my $keyroot;
                   7245:     if (defined($prefix) && $prefix !~ /^__/) {
                   7246: 	# prefix that has a part already
                   7247: 	$keyroot=$prefix;
                   7248:     } elsif (defined($prefix)) {
                   7249: 	# prefix that is missing a part
                   7250: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   7251:     } else {
                   7252: 	# no prefix at all
                   7253: 	if (defined($part)) { $keyroot='_'.$part; }
                   7254:     }
                   7255:     return $keyroot;
                   7256: }
                   7257: 
1.71      www      7258: # ---------------------------------------------------------------- Get metadata
                   7259: 
1.599     albertel 7260: my %metaentry;
1.71      www      7261: sub metadata {
1.176     www      7262:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      7263:     $uri=&declutter($uri);
1.288     albertel 7264:     # if it is a non metadata possible uri return quickly
1.529     albertel 7265:     if (($uri eq '') || 
                   7266: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 7267: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 7268:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   7269: 	return undef;
                   7270:     }
                   7271:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   7272: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 7273: 	return undef;
1.288     albertel 7274:     }
1.73      www      7275:     my $filename=$uri;
                   7276:     $uri=~s/\.meta$//;
1.172     www      7277: #
                   7278: # Is the metadata already cached?
1.177     www      7279: # Look at timestamp of caching
1.172     www      7280: # Everything is cached by the main uri, libraries are never directly cached
                   7281: #
1.428     albertel 7282:     if (!defined($liburi)) {
1.599     albertel 7283: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 7284: 	if (defined($cached)) { return $result->{':'.$what}; }
                   7285:     }
                   7286:     {
1.172     www      7287: #
                   7288: # Is this a recursive call for a library?
                   7289: #
1.599     albertel 7290: #	if (! exists($metacache{$uri})) {
                   7291: #	    $metacache{$uri}={};
                   7292: #	}
1.924     albertel 7293: 	my $cachetime = 60*60;
1.171     www      7294:         if ($liburi) {
                   7295: 	    $liburi=&declutter($liburi);
                   7296:             $filename=$liburi;
1.401     bowersj2 7297:         } else {
1.599     albertel 7298: 	    &devalidate_cache_new('meta',$uri);
                   7299: 	    undef(%metaentry);
1.401     bowersj2 7300: 	}
1.140     www      7301:         my %metathesekeys=();
1.73      www      7302:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 7303: 	my $metastring;
1.924     albertel 7304: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 7305: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 7306: 	    $metastring = 
1.929     albertel 7307: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 7308: 					  ('grade_target' => 'meta'));
                   7309: 	    $cachetime = 1; # only want this cached in the child not long term
                   7310: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 7311: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 7312: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 7313: 	    $metastring=&getfile($file);
1.489     albertel 7314: 	}
1.208     albertel 7315:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      7316:         my $token;
1.140     www      7317:         undef %metathesekeys;
1.71      www      7318:         while ($token=$parser->get_token) {
1.339     albertel 7319: 	    if ($token->[0] eq 'S') {
                   7320: 		if (defined($token->[2]->{'package'})) {
1.172     www      7321: #
                   7322: # This is a package - get package info
                   7323: #
1.339     albertel 7324: 		    my $package=$token->[2]->{'package'};
                   7325: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7326: 		    if (defined($token->[2]->{'id'})) { 
                   7327: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7328: 		    }
1.599     albertel 7329: 		    if ($metaentry{':packages'}) {
                   7330: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7331: 		    } else {
1.599     albertel 7332: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7333: 		    }
1.736     albertel 7334: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7335: 			my $part=$keyroot;
                   7336: 			$part=~s/^\_//;
1.736     albertel 7337: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7338: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7339: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7340: 			    # ignore package.tab specified default values
                   7341:                             # here &package_tab_default() will fetch those
                   7342: 			    if ($subp eq 'default') { next; }
1.736     albertel 7343: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7344: 			    my $unikey;
                   7345: 			    if ($pack =~ /_0$/) {
                   7346: 				$unikey='parameter_0_'.$name;
                   7347: 				$part=0;
                   7348: 			    } else {
                   7349: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7350: 			    }
1.339     albertel 7351: 			    if ($subp eq 'display') {
                   7352: 				$value.=' [Part: '.$part.']';
                   7353: 			    }
1.599     albertel 7354: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7355: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7356: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7357: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7358: 			    }
1.599     albertel 7359: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7360: 				$metaentry{':'.$unikey}=
                   7361: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7362: 			    }
1.339     albertel 7363: 			}
                   7364: 		    }
                   7365: 		} else {
1.172     www      7366: #
                   7367: # This is not a package - some other kind of start tag
1.339     albertel 7368: #
                   7369: 		    my $entry=$token->[1];
                   7370: 		    my $unikey;
                   7371: 		    if ($entry eq 'import') {
                   7372: 			$unikey='';
                   7373: 		    } else {
                   7374: 			$unikey=$entry;
                   7375: 		    }
                   7376: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7377: 
                   7378: 		    if (defined($token->[2]->{'id'})) { 
                   7379: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7380: 		    }
1.175     www      7381: 
1.339     albertel 7382: 		    if ($entry eq 'import') {
1.175     www      7383: #
                   7384: # Importing a library here
1.339     albertel 7385: #
                   7386: 			if ($depthcount<20) {
                   7387: 			    my $location=$parser->get_text('/import');
                   7388: 			    my $dir=$filename;
                   7389: 			    $dir=~s|[^/]*$||;
                   7390: 			    $location=&filelocation($dir,$location);
1.736     albertel 7391: 			    my $metadata = 
                   7392: 				&metadata($uri,'keys', $location,$unikey,
                   7393: 					  $depthcount+1);
                   7394: 			    foreach my $meta (split(',',$metadata)) {
                   7395: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7396: 				$metathesekeys{$meta}=1;
1.339     albertel 7397: 			    }
                   7398: 			}
                   7399: 		    } else { 
                   7400: 			
                   7401: 			if (defined($token->[2]->{'name'})) { 
                   7402: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7403: 			}
                   7404: 			$metathesekeys{$unikey}=1;
1.736     albertel 7405: 			foreach my $param (@{$token->[3]}) {
                   7406: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7407: 				$token->[2]->{$param};
1.339     albertel 7408: 			}
                   7409: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7410: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7411: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7412: 		 # only ws inside the tag, and not in default, so use default
                   7413: 		 # as value
1.599     albertel 7414: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7415: 			} elsif ( $internaltext =~ /\S/ ) {
                   7416: 		  # something interesting inside the tag
                   7417: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7418: 			} else {
1.908     albertel 7419: 		  # no interesting values, don't set a default
1.339     albertel 7420: 			}
1.172     www      7421: # end of not-a-package not-a-library import
1.339     albertel 7422: 		    }
1.172     www      7423: # end of not-a-package start tag
1.339     albertel 7424: 		}
1.172     www      7425: # the next is the end of "start tag"
1.339     albertel 7426: 	    }
                   7427: 	}
1.483     albertel 7428: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7429: 	$extension = lc($extension);
                   7430: 	if ($extension eq 'htm') { $extension='html'; }
                   7431: 
1.737     albertel 7432: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7433: 	    #no specific packages #how's our extension
                   7434: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7435: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7436: 					 \%metathesekeys);
                   7437: 	}
1.883     albertel 7438: 
                   7439: 	if (!exists($metaentry{':packages'})
                   7440: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7441: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7442: 		#no specific packages well let's get default then
                   7443: 		if ($key!~/^default&/) { next; }
1.488     albertel 7444: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7445: 					     \%metathesekeys);
                   7446: 	    }
                   7447: 	}
1.338     www      7448: # are there custom rights to evaluate
1.599     albertel 7449: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7450: 
1.338     www      7451:     #
                   7452:     # Importing a rights file here
1.339     albertel 7453:     #
                   7454: 	    unless ($depthcount) {
1.599     albertel 7455: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7456: 		my $dir=$filename;
                   7457: 		$dir=~s|[^/]*$||;
                   7458: 		$location=&filelocation($dir,$location);
1.736     albertel 7459: 		my $rights_metadata =
                   7460: 		    &metadata($uri,'keys',$location,'_rights',
                   7461: 			      $depthcount+1);
                   7462: 		foreach my $rights (split(',',$rights_metadata)) {
                   7463: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7464: 		    $metathesekeys{$rights}=1;
1.339     albertel 7465: 		}
                   7466: 	    }
                   7467: 	}
1.737     albertel 7468: 	# uniqifiy package listing
                   7469: 	my %seen;
                   7470: 	my @uniq_packages =
                   7471: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7472: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7473: 
                   7474: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7475: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7476: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7477: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7478: # this is the end of "was not already recently cached
1.71      www      7479:     }
1.599     albertel 7480:     return $metaentry{':'.$what};
1.261     albertel 7481: }
                   7482: 
1.488     albertel 7483: sub metadata_create_package_def {
1.483     albertel 7484:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7485:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7486:     if ($subp eq 'default') { next; }
                   7487:     
1.599     albertel 7488:     if (defined($metaentry{':packages'})) {
                   7489: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7490:     } else {
1.599     albertel 7491: 	$metaentry{':packages'}=$package;
1.483     albertel 7492:     }
                   7493:     my $value=$packagetab{$key};
                   7494:     my $unikey;
                   7495:     $unikey='parameter_0_'.$name;
1.599     albertel 7496:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7497:     $$metathesekeys{$unikey}=1;
1.599     albertel 7498:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7499: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7500:     }
1.599     albertel 7501:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7502: 	$metaentry{':'.$unikey}=
                   7503: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7504:     }
                   7505: }
                   7506: 
1.261     albertel 7507: sub metadata_generate_part0 {
                   7508:     my ($metadata,$metacache,$uri) = @_;
                   7509:     my %allnames;
1.737     albertel 7510:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7511: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7512: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7513: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7514: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7515: 	    $allnames{$name}=$part;
                   7516: 	  }
                   7517: 	}
                   7518:     }
                   7519:     foreach my $name (keys(%allnames)) {
                   7520:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7521:       my $key=":parameter_0_$name";
1.261     albertel 7522:       $$metacache{"$key.part"}='0';
                   7523:       $$metacache{"$key.name"}=$name;
1.428     albertel 7524:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7525: 					   $allnames{$name}.'_'.$name.
                   7526: 					   '.type'};
1.428     albertel 7527:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7528: 			     '.display'};
1.644     www      7529:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7530:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7531:       $$metacache{"$key.display"}=$olddis;
                   7532:     }
1.71      www      7533: }
                   7534: 
1.764     albertel 7535: # ------------------------------------------------------ Devalidate title cache
                   7536: 
                   7537: sub devalidate_title_cache {
                   7538:     my ($url)=@_;
                   7539:     if (!$env{'request.course.id'}) { return; }
                   7540:     my $symb=&symbread($url);
                   7541:     if (!$symb) { return; }
                   7542:     my $key=$env{'request.course.id'}."\0".$symb;
                   7543:     &devalidate_cache_new('title',$key);
                   7544: }
                   7545: 
1.301     www      7546: # ------------------------------------------------- Get the title of a resource
                   7547: 
                   7548: sub gettitle {
                   7549:     my $urlsymb=shift;
                   7550:     my $symb=&symbread($urlsymb);
1.534     albertel 7551:     if ($symb) {
1.620     albertel 7552: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7553: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7554: 	if (defined($cached)) { 
                   7555: 	    return $result;
                   7556: 	}
1.534     albertel 7557: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7558: 	my $title='';
1.907     albertel 7559: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7560: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7561: 	} else {
                   7562: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7563: 		    &GDBM_READER(),0640)) {
                   7564: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7565: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7566: 		untie(%bighash);
                   7567: 	    }
1.534     albertel 7568: 	}
                   7569: 	$title=~s/\&colon\;/\:/gs;
                   7570: 	if ($title) {
1.599     albertel 7571: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7572: 	}
                   7573: 	$urlsymb=$url;
                   7574:     }
                   7575:     my $title=&metadata($urlsymb,'title');
                   7576:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7577:     return $title;
1.301     www      7578: }
1.613     albertel 7579: 
1.614     albertel 7580: sub get_slot {
                   7581:     my ($which,$cnum,$cdom)=@_;
                   7582:     if (!$cnum || !$cdom) {
1.790     albertel 7583: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7584: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7585: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7586:     }
1.703     albertel 7587:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7588:     my %slotinfo;
                   7589:     if (exists($remembered{$key})) {
                   7590: 	$slotinfo{$which} = $remembered{$key};
                   7591:     } else {
                   7592: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7593: 	&Apache::lonhomework::showhash(%slotinfo);
                   7594: 	my ($tmp)=keys(%slotinfo);
                   7595: 	if ($tmp=~/^error:/) { return (); }
                   7596: 	$remembered{$key} = $slotinfo{$which};
                   7597:     }
1.616     albertel 7598:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7599: 	return %{$slotinfo{$which}};
                   7600:     }
                   7601:     return $slotinfo{$which};
1.614     albertel 7602: }
1.31      www      7603: # ------------------------------------------------- Update symbolic store links
                   7604: 
                   7605: sub symblist {
                   7606:     my ($mapname,%newhash)=@_;
1.438     www      7607:     $mapname=&deversion(&declutter($mapname));
1.31      www      7608:     my %hash;
1.620     albertel 7609:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7610:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7611:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7612: 	    foreach my $url (keys %newhash) {
                   7613: 		next if ($url eq 'last_known'
                   7614: 			 && $env{'form.no_update_last_known'});
                   7615: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7616: 						    $newhash{$url}->[1],
                   7617: 						    $newhash{$url}->[0]);
1.191     harris41 7618:             }
1.31      www      7619:             if (untie(%hash)) {
                   7620: 		return 'ok';
                   7621:             }
                   7622:         }
                   7623:     }
                   7624:     return 'error';
1.212     www      7625: }
                   7626: 
                   7627: # --------------------------------------------------------------- Verify a symb
                   7628: 
                   7629: sub symbverify {
1.510     www      7630:     my ($symb,$thisurl)=@_;
                   7631:     my $thisfn=$thisurl;
1.439     www      7632:     $thisfn=&declutter($thisfn);
1.215     www      7633: # direct jump to resource in page or to a sequence - will construct own symbs
                   7634:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7635: # check URL part
1.409     www      7636:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7637: 
1.431     www      7638:     unless ($url eq $thisfn) { return 0; }
1.213     www      7639: 
1.216     www      7640:     $symb=&symbclean($symb);
1.510     www      7641:     $thisurl=&deversion($thisurl);
1.439     www      7642:     $thisfn=&deversion($thisfn);
1.213     www      7643: 
                   7644:     my %bighash;
                   7645:     my $okay=0;
1.431     www      7646: 
1.620     albertel 7647:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7648:                             &GDBM_READER(),0640)) {
1.510     www      7649:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7650:         unless ($ids) { 
1.510     www      7651:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7652:         }
                   7653:         if ($ids) {
                   7654: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7655: 	    foreach my $id (split(/\,/,$ids)) {
                   7656: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7657:                if (
                   7658:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7659:    eq $symb) { 
1.620     albertel 7660: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7661: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7662: 		       $okay=1; 
                   7663: 		   }
                   7664: 	       }
1.216     www      7665: 	   }
                   7666:         }
1.213     www      7667: 	untie(%bighash);
                   7668:     }
                   7669:     return $okay;
1.31      www      7670: }
                   7671: 
1.210     www      7672: # --------------------------------------------------------------- Clean-up symb
                   7673: 
                   7674: sub symbclean {
                   7675:     my $symb=shift;
1.568     albertel 7676:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7677: # remove version from map
                   7678:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7679: 
1.210     www      7680: # remove version from URL
                   7681:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7682: 
1.507     www      7683: # remove wrapper
                   7684: 
1.510     www      7685:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7686:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7687:     return $symb;
1.409     www      7688: }
                   7689: 
                   7690: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7691: 
                   7692: sub encode_symb {
                   7693:     my ($map,$resid,$url)=@_;
                   7694:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7695: }
1.409     www      7696: 
                   7697: sub decode_symb {
1.568     albertel 7698:     my $symb=shift;
                   7699:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7700:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7701:     return (&fixversion($map),$resid,&fixversion($url));
                   7702: }
                   7703: 
                   7704: sub fixversion {
                   7705:     my $fn=shift;
1.609     banghart 7706:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7707:     my %bighash;
                   7708:     my $uri=&clutter($fn);
1.620     albertel 7709:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7710: # is this cached?
1.599     albertel 7711:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7712:     if (defined($cached)) { return $result; }
                   7713: # unfortunately not cached, or expired
1.620     albertel 7714:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7715: 	    &GDBM_READER(),0640)) {
                   7716:  	if ($bighash{'version_'.$uri}) {
                   7717:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7718:  	    unless (($version eq 'mostrecent') || 
                   7719: 		    ($version==&getversion($uri))) {
1.440     www      7720:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7721:  	    }
                   7722:  	}
                   7723:  	untie %bighash;
1.413     www      7724:     }
1.599     albertel 7725:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7726: }
                   7727: 
                   7728: sub deversion {
                   7729:     my $url=shift;
                   7730:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7731:     return $url;
1.210     www      7732: }
                   7733: 
1.31      www      7734: # ------------------------------------------------------ Return symb list entry
                   7735: 
                   7736: sub symbread {
1.249     www      7737:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7738:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7739:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7740: # no filename provided? try from environment
1.44      www      7741:     unless ($thisfn) {
1.620     albertel 7742:         if ($env{'request.symb'}) {
                   7743: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7744: 	}
1.620     albertel 7745: 	$thisfn=$env{'request.filename'};
1.44      www      7746:     }
1.569     albertel 7747:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7748: # is that filename actually a symb? Verify, clean, and return
                   7749:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7750: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7751: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7752: 	}
1.242     www      7753:     }
1.44      www      7754:     $thisfn=declutter($thisfn);
1.31      www      7755:     my %hash;
1.37      www      7756:     my %bighash;
                   7757:     my $syval='';
1.620     albertel 7758:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7759:         my $targetfn = $thisfn;
1.609     banghart 7760:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7761:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7762:         }
1.687     albertel 7763: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7764: 	    $targetfn=$1;
                   7765: 	}
1.620     albertel 7766:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7767:                       &GDBM_READER(),0640)) {
1.481     raeburn  7768: 	    $syval=$hash{$targetfn};
1.37      www      7769:             untie(%hash);
                   7770:         }
                   7771: # ---------------------------------------------------------- There was an entry
                   7772:         if ($syval) {
1.601     albertel 7773: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7774: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  7775: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7776: 		    #return $env{$cache_str}='';
1.601     albertel 7777: 		#}    
                   7778: 		#$syval.=$1;
                   7779: 	    #}
1.37      www      7780:         } else {
                   7781: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7782:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7783:                             &GDBM_READER(),0640)) {
1.37      www      7784: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7785:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7786:               unless ($ids) { 
                   7787:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7788:               }
                   7789:               unless ($ids) {
                   7790: # alias?
                   7791: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7792:               }
1.37      www      7793:               if ($ids) {
                   7794: # ------------------------------------------------------------------- Has ID(s)
                   7795:                  my @possibilities=split(/\,/,$ids);
1.39      www      7796:                  if ($#possibilities==0) {
                   7797: # ----------------------------------------------- There is only one possibility
1.37      www      7798: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7799: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7800: 						    $resid,$thisfn);
1.249     www      7801:                  } elsif (!$donotrecurse) {
1.39      www      7802: # ------------------------------------------ There is more than one possibility
                   7803:                      my $realpossible=0;
1.800     albertel 7804:                      foreach my $id (@possibilities) {
                   7805: 			 my $file=$bighash{'src_'.$id};
1.39      www      7806:                          if (&allowed('bre',$file)) {
1.800     albertel 7807:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7808:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7809: 				$realpossible++;
1.626     albertel 7810:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7811: 						    $resid,$thisfn);
1.39      www      7812:                             }
                   7813: 			 }
1.191     harris41 7814:                      }
1.39      www      7815: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7816:                  } else {
                   7817:                      $syval='';
1.37      www      7818:                  }
                   7819: 	      }
                   7820:               untie(%bighash)
1.481     raeburn  7821:            }
1.31      www      7822:         }
1.62      www      7823:         if ($syval) {
1.620     albertel 7824: 	    return $env{$cache_str}=$syval;
1.62      www      7825:         }
1.31      www      7826:     }
1.949     raeburn  7827:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7828:     return $env{$cache_str}='';
1.31      www      7829: }
                   7830: 
                   7831: # ---------------------------------------------------------- Return random seed
                   7832: 
1.32      www      7833: sub numval {
                   7834:     my $txt=shift;
                   7835:     $txt=~tr/A-J/0-9/;
                   7836:     $txt=~tr/a-j/0-9/;
                   7837:     $txt=~tr/K-T/0-9/;
                   7838:     $txt=~tr/k-t/0-9/;
                   7839:     $txt=~tr/U-Z/0-5/;
                   7840:     $txt=~tr/u-z/0-5/;
                   7841:     $txt=~s/\D//g;
1.564     albertel 7842:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7843:     return int($txt);
1.368     albertel 7844: }
                   7845: 
1.484     albertel 7846: sub numval2 {
                   7847:     my $txt=shift;
                   7848:     $txt=~tr/A-J/0-9/;
                   7849:     $txt=~tr/a-j/0-9/;
                   7850:     $txt=~tr/K-T/0-9/;
                   7851:     $txt=~tr/k-t/0-9/;
                   7852:     $txt=~tr/U-Z/0-5/;
                   7853:     $txt=~tr/u-z/0-5/;
                   7854:     $txt=~s/\D//g;
                   7855:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7856:     my $total;
                   7857:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7858:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7859:     return int($total);
                   7860: }
                   7861: 
1.575     albertel 7862: sub numval3 {
                   7863:     use integer;
                   7864:     my $txt=shift;
                   7865:     $txt=~tr/A-J/0-9/;
                   7866:     $txt=~tr/a-j/0-9/;
                   7867:     $txt=~tr/K-T/0-9/;
                   7868:     $txt=~tr/k-t/0-9/;
                   7869:     $txt=~tr/U-Z/0-5/;
                   7870:     $txt=~tr/u-z/0-5/;
                   7871:     $txt=~s/\D//g;
                   7872:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7873:     my $total;
                   7874:     foreach my $val (@txts) { $total+=$val; }
                   7875:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7876:     return $total;
                   7877: }
                   7878: 
1.675     albertel 7879: sub digest {
                   7880:     my ($data)=@_;
                   7881:     my $digest=&Digest::MD5::md5($data);
                   7882:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7883:     my ($e,$f);
                   7884:     {
                   7885:         use integer;
                   7886:         $e=($a+$b);
                   7887:         $f=($c+$d);
                   7888:         if ($_64bit) {
                   7889:             $e=(($e<<32)>>32);
                   7890:             $f=(($f<<32)>>32);
                   7891:         }
                   7892:     }
                   7893:     if (wantarray) {
                   7894: 	return ($e,$f);
                   7895:     } else {
                   7896: 	my $g;
                   7897: 	{
                   7898: 	    use integer;
                   7899: 	    $g=($e+$f);
                   7900: 	    if ($_64bit) {
                   7901: 		$g=(($g<<32)>>32);
                   7902: 	    }
                   7903: 	}
                   7904: 	return $g;
                   7905:     }
                   7906: }
                   7907: 
1.368     albertel 7908: sub latest_rnd_algorithm_id {
1.675     albertel 7909:     return '64bit5';
1.366     albertel 7910: }
1.32      www      7911: 
1.503     albertel 7912: sub get_rand_alg {
                   7913:     my ($courseid)=@_;
1.790     albertel 7914:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7915:     if ($courseid) {
1.620     albertel 7916: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7917:     }
                   7918:     return &latest_rnd_algorithm_id();
                   7919: }
                   7920: 
1.562     albertel 7921: sub validCODE {
                   7922:     my ($CODE)=@_;
                   7923:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7924:     return 0;
                   7925: }
                   7926: 
1.491     albertel 7927: sub getCODE {
1.620     albertel 7928:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7929:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7930: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7931: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7932: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7933:     }
                   7934:     return undef;
                   7935: }
                   7936: 
1.31      www      7937: sub rndseed {
1.155     albertel 7938:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7939:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7940:     if (!defined($symb)) {
1.366     albertel 7941: 	unless ($symb=$wsymb) { return time; }
                   7942:     }
                   7943:     if (!$courseid) { $courseid=$wcourseid; }
                   7944:     if (!$domain) { $domain=$wdomain; }
                   7945:     if (!$username) { $username=$wusername }
1.503     albertel 7946:     my $which=&get_rand_alg();
1.803     albertel 7947: 
1.491     albertel 7948:     if (defined(&getCODE())) {
1.675     albertel 7949: 	if ($which eq '64bit5') {
                   7950: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7951: 	} elsif ($which eq '64bit4') {
1.575     albertel 7952: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7953: 	} else {
                   7954: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7955: 	}
1.675     albertel 7956:     } elsif ($which eq '64bit5') {
                   7957: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7958:     } elsif ($which eq '64bit4') {
                   7959: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7960:     } elsif ($which eq '64bit3') {
                   7961: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7962:     } elsif ($which eq '64bit2') {
                   7963: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7964:     } elsif ($which eq '64bit') {
                   7965: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7966:     }
                   7967:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7968: }
                   7969: 
                   7970: sub rndseed_32bit {
                   7971:     my ($symb,$courseid,$domain,$username)=@_;
                   7972:     {
                   7973: 	use integer;
                   7974: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7975: 	my $symbseed=numval($symb) << 22;
                   7976: 	my $namechck=unpack("%32C*",$username) << 17;
                   7977: 	my $nameseed=numval($username) << 12;
                   7978: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7979: 	my $courseseed=unpack("%32C*",$courseid);
                   7980: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7981: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7982: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7983: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7984: 	return $num;
                   7985:     }
                   7986: }
                   7987: 
                   7988: sub rndseed_64bit {
                   7989:     my ($symb,$courseid,$domain,$username)=@_;
                   7990:     {
                   7991: 	use integer;
                   7992: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7993: 	my $symbseed=numval($symb) << 10;
                   7994: 	my $namechck=unpack("%32S*",$username);
                   7995: 	
                   7996: 	my $nameseed=numval($username) << 21;
                   7997: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7998: 	my $courseseed=unpack("%32S*",$courseid);
                   7999: 	
                   8000: 	my $num1=$symbchck+$symbseed+$namechck;
                   8001: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8002: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8003: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8004: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 8005: 	return "$num1,$num2";
1.155     albertel 8006:     }
1.366     albertel 8007: }
                   8008: 
1.443     albertel 8009: sub rndseed_64bit2 {
                   8010:     my ($symb,$courseid,$domain,$username)=@_;
                   8011:     {
                   8012: 	use integer;
                   8013: 	# strings need to be an even # of cahracters long, it it is odd the
                   8014:         # last characters gets thrown away
                   8015: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8016: 	my $symbseed=numval($symb) << 10;
                   8017: 	my $namechck=unpack("%32S*",$username.' ');
                   8018: 	
                   8019: 	my $nameseed=numval($username) << 21;
1.501     albertel 8020: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8021: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8022: 	
                   8023: 	my $num1=$symbchck+$symbseed+$namechck;
                   8024: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8025: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8026: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 8027: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 8028: 	return "$num1,$num2";
                   8029:     }
                   8030: }
                   8031: 
                   8032: sub rndseed_64bit3 {
                   8033:     my ($symb,$courseid,$domain,$username)=@_;
                   8034:     {
                   8035: 	use integer;
                   8036: 	# strings need to be an even # of cahracters long, it it is odd the
                   8037:         # last characters gets thrown away
                   8038: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8039: 	my $symbseed=numval2($symb) << 10;
                   8040: 	my $namechck=unpack("%32S*",$username.' ');
                   8041: 	
                   8042: 	my $nameseed=numval2($username) << 21;
1.443     albertel 8043: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8044: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8045: 	
                   8046: 	my $num1=$symbchck+$symbseed+$namechck;
                   8047: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8048: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8049: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 8050: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8051: 	
1.503     albertel 8052: 	return "$num1:$num2";
1.443     albertel 8053:     }
                   8054: }
                   8055: 
1.575     albertel 8056: sub rndseed_64bit4 {
                   8057:     my ($symb,$courseid,$domain,$username)=@_;
                   8058:     {
                   8059: 	use integer;
                   8060: 	# strings need to be an even # of cahracters long, it it is odd the
                   8061:         # last characters gets thrown away
                   8062: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8063: 	my $symbseed=numval3($symb) << 10;
                   8064: 	my $namechck=unpack("%32S*",$username.' ');
                   8065: 	
                   8066: 	my $nameseed=numval3($username) << 21;
                   8067: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8068: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8069: 	
                   8070: 	my $num1=$symbchck+$symbseed+$namechck;
                   8071: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8072: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8073: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 8074: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8075: 	
                   8076: 	return "$num1:$num2";
                   8077:     }
                   8078: }
                   8079: 
1.675     albertel 8080: sub rndseed_64bit5 {
                   8081:     my ($symb,$courseid,$domain,$username)=@_;
                   8082:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   8083:     return "$num1:$num2";
                   8084: }
                   8085: 
1.366     albertel 8086: sub rndseed_CODE_64bit {
                   8087:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 8088:     {
1.366     albertel 8089: 	use integer;
1.443     albertel 8090: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 8091: 	my $symbseed=numval2($symb);
1.491     albertel 8092: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8093: 	my $CODEseed=numval(&getCODE());
1.443     albertel 8094: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 8095: 	my $num1=$symbseed+$CODEchck;
                   8096: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8097: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8098: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 8099: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8100: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 8101: 	return "$num1:$num2";
1.366     albertel 8102:     }
                   8103: }
                   8104: 
1.575     albertel 8105: sub rndseed_CODE_64bit4 {
                   8106:     my ($symb,$courseid,$domain,$username)=@_;
                   8107:     {
                   8108: 	use integer;
                   8109: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   8110: 	my $symbseed=numval3($symb);
                   8111: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8112: 	my $CODEseed=numval3(&getCODE());
                   8113: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8114: 	my $num1=$symbseed+$CODEchck;
                   8115: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8116: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8117: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 8118: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8119: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   8120: 	return "$num1:$num2";
                   8121:     }
                   8122: }
                   8123: 
1.675     albertel 8124: sub rndseed_CODE_64bit5 {
                   8125:     my ($symb,$courseid,$domain,$username)=@_;
                   8126:     my $code = &getCODE();
                   8127:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   8128:     return "$num1:$num2";
                   8129: }
                   8130: 
1.366     albertel 8131: sub setup_random_from_rndseed {
                   8132:     my ($rndseed)=@_;
1.503     albertel 8133:     if ($rndseed =~/([,:])/) {
                   8134: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 8135: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   8136:     } else {
                   8137: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 8138:     }
1.36      albertel 8139: }
                   8140: 
1.474     albertel 8141: sub latest_receipt_algorithm_id {
1.835     albertel 8142:     return 'receipt3';
1.474     albertel 8143: }
                   8144: 
1.480     www      8145: sub recunique {
                   8146:     my $fucourseid=shift;
                   8147:     my $unique;
1.835     albertel 8148:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   8149: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8150: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      8151:     } else {
                   8152: 	$unique=$perlvar{'lonReceipt'};
                   8153:     }
                   8154:     return unpack("%32C*",$unique);
                   8155: }
                   8156: 
                   8157: sub recprefix {
                   8158:     my $fucourseid=shift;
                   8159:     my $prefix;
1.835     albertel 8160:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   8161: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8162: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      8163:     } else {
                   8164: 	$prefix=$perlvar{'lonHostID'};
                   8165:     }
                   8166:     return unpack("%32C*",$prefix);
                   8167: }
                   8168: 
1.76      www      8169: sub ireceipt {
1.474     albertel 8170:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 8171: 
                   8172:     my $return =&recprefix($fucourseid).'-';
                   8173: 
                   8174:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   8175: 	$env{'request.state'} eq 'construct') {
                   8176: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   8177: 	return $return;
                   8178:     }
                   8179: 
1.76      www      8180:     my $cuname=unpack("%32C*",$funame);
                   8181:     my $cudom=unpack("%32C*",$fudom);
                   8182:     my $cucourseid=unpack("%32C*",$fucourseid);
                   8183:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      8184:     my $cunique=&recunique($fucourseid);
1.474     albertel 8185:     my $cpart=unpack("%32S*",$part);
1.835     albertel 8186:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   8187: 
1.790     albertel 8188: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 8189: 			       
                   8190: 	$return.= ($cunique%$cuname+
                   8191: 		   $cunique%$cudom+
                   8192: 		   $cusymb%$cuname+
                   8193: 		   $cusymb%$cudom+
                   8194: 		   $cucourseid%$cuname+
                   8195: 		   $cucourseid%$cudom+
                   8196: 		   $cpart%$cuname+
                   8197: 		   $cpart%$cudom);
                   8198:     } else {
                   8199: 	$return.= ($cunique%$cuname+
                   8200: 		   $cunique%$cudom+
                   8201: 		   $cusymb%$cuname+
                   8202: 		   $cusymb%$cudom+
                   8203: 		   $cucourseid%$cuname+
                   8204: 		   $cucourseid%$cudom);
                   8205:     }
                   8206:     return $return;
1.76      www      8207: }
                   8208: 
                   8209: sub receipt {
1.474     albertel 8210:     my ($part)=@_;
1.790     albertel 8211:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 8212:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      8213: }
1.260     ng       8214: 
1.790     albertel 8215: sub whichuser {
                   8216:     my ($passedsymb)=@_;
                   8217:     my ($symb,$courseid,$domain,$name,$publicuser);
                   8218:     if (defined($env{'form.grade_symb'})) {
                   8219: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   8220: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   8221: 	if (!$allowed &&
                   8222: 	    exists($env{'request.course.sec'}) &&
                   8223: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   8224: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   8225: 			      '/'.$env{'request.course.sec'});
                   8226: 	}
                   8227: 	if ($allowed) {
                   8228: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   8229: 	    $courseid=$tmp_courseid;
                   8230: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   8231: 	    ($name)=&get_env_multiple('form.grade_username');
                   8232: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   8233: 	}
                   8234:     }
                   8235:     if (!$passedsymb) {
                   8236: 	$symb=&symbread();
                   8237:     } else {
                   8238: 	$symb=$passedsymb;
                   8239:     }
                   8240:     $courseid=$env{'request.course.id'};
                   8241:     $domain=$env{'user.domain'};
                   8242:     $name=$env{'user.name'};
                   8243:     if ($name eq 'public' && $domain eq 'public') {
                   8244: 	if (!defined($env{'form.username'})) {
                   8245: 	    $env{'form.username'}.=time.rand(10000000);
                   8246: 	}
                   8247: 	$name.=$env{'form.username'};
                   8248:     }
                   8249:     return ($symb,$courseid,$domain,$name,$publicuser);
                   8250: 
                   8251: }
                   8252: 
1.36      albertel 8253: # ------------------------------------------------------------ Serves up a file
1.472     albertel 8254: # returns either the contents of the file or 
                   8255: # -1 if the file doesn't exist
1.481     raeburn  8256: #
                   8257: # if the target is a file that was uploaded via DOCS, 
                   8258: # a check will be made to see if a current copy exists on the local server,
                   8259: # if it does this will be served, otherwise a copy will be retrieved from
                   8260: # the home server for the course and stored in /home/httpd/html/userfiles on
                   8261: # the local server.   
1.472     albertel 8262: 
1.36      albertel 8263: sub getfile {
1.538     albertel 8264:     my ($file) = @_;
1.609     banghart 8265:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 8266:     &repcopy($file);
                   8267:     return &readfile($file);
                   8268: }
                   8269: 
                   8270: sub repcopy_userfile {
                   8271:     my ($file)=@_;
1.609     banghart 8272:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 8273:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 8274:     my ($cdom,$cnum,$filename) = 
1.811     albertel 8275: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 8276:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   8277:     if (-e "$file") {
1.828     www      8278: # we already have a local copy, check it out
1.538     albertel 8279: 	my @fileinfo = stat($file);
1.828     www      8280: 	my $rtncode;
                   8281: 	my $info;
1.538     albertel 8282: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 8283: 	if ($lwpresp ne 'ok') {
1.828     www      8284: # there is no such file anymore, even though we had a local copy
1.482     albertel 8285: 	    if ($rtncode eq '404') {
1.538     albertel 8286: 		unlink($file);
1.482     albertel 8287: 	    }
                   8288: 	    return -1;
                   8289: 	}
                   8290: 	if ($info < $fileinfo[9]) {
1.828     www      8291: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  8292: 	    return 'ok';
1.828     www      8293: 	} else {
                   8294: # the file is outdated, get rid of it
                   8295: 	    unlink($file);
1.482     albertel 8296: 	}
1.828     www      8297:     }
                   8298: # one way or the other, at this point, we don't have the file
                   8299: # construct the correct path for the file
                   8300:     my @parts = ($cdom,$cnum); 
                   8301:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   8302: 	push @parts, split(/\//,$1);
                   8303:     }
                   8304:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   8305:     foreach my $part (@parts) {
                   8306: 	$path .= '/'.$part;
                   8307: 	if (!-e $path) {
                   8308: 	    mkdir($path,0770);
1.482     albertel 8309: 	}
                   8310:     }
1.828     www      8311: # now the path exists for sure
                   8312: # get a user agent
                   8313:     my $ua=new LWP::UserAgent;
                   8314:     my $transferfile=$file.'.in.transfer';
                   8315: # FIXME: this should flock
                   8316:     if (-e $transferfile) { return 'ok'; }
                   8317:     my $request;
                   8318:     $uri=~s/^\///;
1.976.2.3  raeburn  8319:     my $homeserver = &homeserver($cnum,$cdom);
                   8320:     my $protocol = $protocol{$homeserver};
                   8321:     $protocol = 'http' if ($protocol ne 'https');
                   8322:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      8323:     my $response=$ua->request($request,$transferfile);
                   8324: # did it work?
                   8325:     if ($response->is_error()) {
                   8326: 	unlink($transferfile);
                   8327: 	&logthis("Userfile repcopy failed for $uri");
                   8328: 	return -1;
                   8329:     }
                   8330: # worked, rename the transfer file
                   8331:     rename($transferfile,$file);
1.607     raeburn  8332:     return 'ok';
1.481     raeburn  8333: }
                   8334: 
1.517     albertel 8335: sub tokenwrapper {
                   8336:     my $uri=shift;
1.976.2.3  raeburn  8337:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 8338:     $uri=~s|^/||;
1.620     albertel 8339:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8340:     my $token=$1;
1.552     albertel 8341:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8342:     if ($udom && $uname && $file) {
                   8343: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8344:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.976.2.3  raeburn  8345:         my $homeserver = &homeserver($uname,$udom);
                   8346:         my $protocol = $protocol{$homeserver};
                   8347:         $protocol = 'http' if ($protocol ne 'https');
                   8348:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 8349:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8350:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8351:     } else {
                   8352:         return '/adm/notfound.html';
                   8353:     }
                   8354: }
                   8355: 
1.828     www      8356: # call with reqtype HEAD: get last modification time
                   8357: # call with reqtype GET: get the file contents
                   8358: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8359: #
1.481     raeburn  8360: sub getuploaded {
                   8361:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8362:     $uri=~s/^\///;
1.976.2.3  raeburn  8363:     my $homeserver = &homeserver($cnum,$cdom);
                   8364:     my $protocol = $protocol{$homeserver};
                   8365:     $protocol = 'http' if ($protocol ne 'https');
                   8366:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  8367:     my $ua=new LWP::UserAgent;
                   8368:     my $request=new HTTP::Request($reqtype,$uri);
                   8369:     my $response=$ua->request($request);
                   8370:     $$rtncode = $response->code;
1.482     albertel 8371:     if (! $response->is_success()) {
                   8372: 	return 'failed';
                   8373:     }      
                   8374:     if ($reqtype eq 'HEAD') {
1.486     www      8375: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8376:     } elsif ($reqtype eq 'GET') {
                   8377: 	$$info = $response->content;
1.472     albertel 8378:     }
1.482     albertel 8379:     return 'ok';
1.36      albertel 8380: }
                   8381: 
1.481     raeburn  8382: sub readfile {
                   8383:     my $file = shift;
                   8384:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8385:     my $fh;
                   8386:     open($fh,"<$file");
                   8387:     my $a='';
1.800     albertel 8388:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8389:     return $a;
                   8390: }
                   8391: 
1.36      albertel 8392: sub filelocation {
1.590     banghart 8393:     my ($dir,$file) = @_;
                   8394:     my $location;
                   8395:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8396: 
                   8397:     if ($file =~ m-^/adm/-) {
                   8398: 	$file=~s-^/adm/wrapper/-/-;
                   8399: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8400:     }
1.882     albertel 8401: 
1.590     banghart 8402:     if ($file=~m:^/~:) { # is a contruction space reference
                   8403:         $location = $file;
                   8404:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8405:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8406: 	# is a correct contruction space reference
                   8407:         $location = $file;
1.956     raeburn  8408:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   8409:         $location = $file;
1.609     banghart 8410:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8411:         my ($udom,$uname,$filename)=
1.811     albertel 8412:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8413:         my $home=&homeserver($uname,$udom);
                   8414:         my $is_me=0;
                   8415:         my @ids=&current_machine_ids();
                   8416:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8417:         if ($is_me) {
1.955     raeburn  8418:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 8419:         } else {
                   8420:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8421:   	      $udom.'/'.$uname.'/'.$filename;
                   8422:         }
1.882     albertel 8423:     } elsif ($file =~ m-^/adm/-) {
                   8424: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8425:     } else {
                   8426:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8427:         $file=~s:^/res/:/:;
                   8428:         if ( !( $file =~ m:^/:) ) {
                   8429:             $location = $dir. '/'.$file;
                   8430:         } else {
                   8431:             $location = '/home/httpd/html/res'.$file;
                   8432:         }
1.59      albertel 8433:     }
1.590     banghart 8434:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8435:     while ($location=~m{/\.\./}) {
                   8436: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8437: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8438: 	} else {
                   8439: 	    $location=~ s{/\.\./}{/}g;
                   8440: 	}
                   8441:     } #remove dir/..
1.590     banghart 8442:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8443:     return $location;
1.46      www      8444: }
1.36      albertel 8445: 
1.46      www      8446: sub hreflocation {
                   8447:     my ($dir,$file)=@_;
1.976.2.3  raeburn  8448:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 8449: 	$file=filelocation($dir,$file);
1.700     albertel 8450:     } elsif ($file=~m-^/adm/-) {
                   8451: 	$file=~s-^/adm/wrapper/-/-;
                   8452: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8453:     }
                   8454:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8455: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8456:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8457: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8458:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8459: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8460: 	    -/uploaded/$1/$2/-x;
1.46      www      8461:     }
1.913     albertel 8462:     if ($file=~ m{^/userfiles/}) {
                   8463: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8464:     }
1.462     albertel 8465:     return $file;
1.465     albertel 8466: }
                   8467: 
                   8468: sub current_machine_domains {
1.853     albertel 8469:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8470: }
                   8471: 
                   8472: sub machine_domains {
                   8473:     my ($hostname) = @_;
1.465     albertel 8474:     my @domains;
1.838     albertel 8475:     my %hostname = &all_hostnames();
1.465     albertel 8476:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8477: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8478: 	if ($hostname eq $name) {
1.844     albertel 8479: 	    push(@domains,&host_domain($id));
1.465     albertel 8480: 	}
                   8481:     }
                   8482:     return @domains;
                   8483: }
                   8484: 
                   8485: sub current_machine_ids {
1.853     albertel 8486:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8487: }
                   8488: 
                   8489: sub machine_ids {
                   8490:     my ($hostname) = @_;
                   8491:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8492:     my @ids;
1.888     albertel 8493:     my %name_to_host = &all_names();
1.889     albertel 8494:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8495: 	return @{ $name_to_host{$hostname} };
                   8496:     }
                   8497:     return;
1.31      www      8498: }
                   8499: 
1.824     raeburn  8500: sub additional_machine_domains {
                   8501:     my @domains;
                   8502:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8503:     while( my $line = <$fh>) {
                   8504:         $line =~ s/\s//g;
                   8505:         push(@domains,$line);
                   8506:     }
                   8507:     return @domains;
                   8508: }
                   8509: 
                   8510: sub default_login_domain {
                   8511:     my $domain = $perlvar{'lonDefDomain'};
                   8512:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8513:     foreach my $posdom (&current_machine_domains(),
                   8514:                         &additional_machine_domains()) {
                   8515:         if (lc($posdom) eq lc($testdomain)) {
                   8516:             $domain=$posdom;
                   8517:             last;
                   8518:         }
                   8519:     }
                   8520:     return $domain;
                   8521: }
                   8522: 
1.31      www      8523: # ------------------------------------------------------------- Declutters URLs
                   8524: 
                   8525: sub declutter {
                   8526:     my $thisfn=shift;
1.569     albertel 8527:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8528:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8529:     $thisfn=~s/^\///;
1.697     albertel 8530:     $thisfn=~s|^adm/wrapper/||;
                   8531:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8532:     $thisfn=~s/^res\///;
1.235     www      8533:     $thisfn=~s/\?.+$//;
1.268     www      8534:     return $thisfn;
                   8535: }
                   8536: 
                   8537: # ------------------------------------------------------------- Clutter up URLs
                   8538: 
                   8539: sub clutter {
                   8540:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8541:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8542: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8543:        $thisfn='/res'.$thisfn; 
                   8544:     }
1.694     albertel 8545:     if ($thisfn !~m|/adm|) {
1.695     albertel 8546: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8547: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8548: 	} else {
                   8549: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8550: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8551: 	    if ($embstyle eq 'ssi'
                   8552: 		|| ($embstyle eq 'hdn')
                   8553: 		|| ($embstyle eq 'rat')
                   8554: 		|| ($embstyle eq 'prv')
                   8555: 		|| ($embstyle eq 'ign')) {
                   8556: 		#do nothing with these
                   8557: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8558: 		|| ($embstyle eq 'emb')
                   8559: 		|| ($embstyle eq 'wrp')) {
                   8560: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8561: 	    } elsif ($embstyle eq 'unk'
                   8562: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8563: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8564: 	    } else {
1.718     www      8565: #		&logthis("Got a blank emb style");
1.695     albertel 8566: 	    }
1.694     albertel 8567: 	}
                   8568:     }
1.31      www      8569:     return $thisfn;
1.12      www      8570: }
                   8571: 
1.787     albertel 8572: sub clutter_with_no_wrapper {
                   8573:     my $uri = &clutter(shift);
                   8574:     if ($uri =~ m-^/adm/-) {
                   8575: 	$uri =~ s-^/adm/wrapper/-/-;
                   8576: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8577:     }
                   8578:     return $uri;
                   8579: }
                   8580: 
1.557     albertel 8581: sub freeze_escape {
                   8582:     my ($value)=@_;
                   8583:     if (ref($value)) {
                   8584: 	$value=&nfreeze($value);
                   8585: 	return '__FROZEN__'.&escape($value);
                   8586:     }
                   8587:     return &escape($value);
                   8588: }
                   8589: 
1.11      www      8590: 
1.557     albertel 8591: sub thaw_unescape {
                   8592:     my ($value)=@_;
                   8593:     if ($value =~ /^__FROZEN__/) {
                   8594: 	substr($value,0,10,undef);
                   8595: 	$value=&unescape($value);
                   8596: 	return &thaw($value);
                   8597:     }
                   8598:     return &unescape($value);
                   8599: }
                   8600: 
1.436     albertel 8601: sub correct_line_ends {
                   8602:     my ($result)=@_;
                   8603:     $$result =~s/\r\n/\n/mg;
                   8604:     $$result =~s/\r/\n/mg;
1.415     albertel 8605: }
1.1       albertel 8606: # ================================================================ Main Program
                   8607: 
1.184     www      8608: sub goodbye {
1.204     albertel 8609:    &logthis("Starting Shut down");
1.443     albertel 8610: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8611:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8612: #converted
1.599     albertel 8613: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8614:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8615: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8616: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8617: #1.1 only
1.870     albertel 8618: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8619: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8620: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8621: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8622:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8623:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8624:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8625:    &flushcourselogs();
                   8626:    &logthis("Shutting down");
                   8627: }
                   8628: 
1.852     albertel 8629: sub get_dns {
1.869     albertel 8630:     my ($url,$func,$ignore_cache) = @_;
                   8631:     if (!$ignore_cache) {
                   8632: 	my ($content,$cached)=
                   8633: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8634: 	if ($cached) {
                   8635: 	    &$func($content);
                   8636: 	    return;
                   8637: 	}
                   8638:     }
                   8639: 
                   8640:     my %alldns;
1.852     albertel 8641:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8642:     foreach my $dns (<$config>) {
                   8643: 	next if ($dns !~ /^\^(\S*)/x);
1.976.2.2  raeburn  8644:         my $line = $1;
                   8645:         my ($host,$protocol) = split(/:/,$line);
                   8646:         if ($protocol ne 'https') {
                   8647:             $protocol = 'http';
                   8648:         }
                   8649: 	$alldns{$host} = $protocol;
1.869     albertel 8650:     }
                   8651:     while (%alldns) {
                   8652: 	my ($dns) = keys(%alldns);
1.852     albertel 8653: 	my $ua=new LWP::UserAgent;
1.976.2.2  raeburn  8654: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 8655: 	my $response=$ua->request($request);
1.976.2.2  raeburn  8656:         delete($alldns{$dns});
1.852     albertel 8657: 	next if ($response->is_error());
                   8658: 	my @content = split("\n",$response->content);
1.869     albertel 8659: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8660: 	&$func(\@content);
1.869     albertel 8661: 	return;
1.852     albertel 8662:     }
                   8663:     close($config);
1.871     albertel 8664:     my $which = (split('/',$url))[3];
                   8665:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8666:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8667:     my @content = <$config>;
                   8668:     &$func(\@content);
                   8669:     return;
1.852     albertel 8670: }
1.327     albertel 8671: # ------------------------------------------------------------ Read domain file
                   8672: {
1.852     albertel 8673:     my $loaded;
1.846     albertel 8674:     my %domain;
                   8675: 
1.852     albertel 8676:     sub parse_domain_tab {
                   8677: 	my ($lines) = @_;
                   8678: 	foreach my $line (@$lines) {
                   8679: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8680: 
1.846     albertel 8681: 	    chomp($line);
1.852     albertel 8682: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8683: 	    my %this_domain;
                   8684: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8685: 			       'lang_def', 'city', 'longi', 'lati',
                   8686: 			       'primary') {
                   8687: 		$this_domain{$field} = shift(@elements);
                   8688: 	    }
                   8689: 	    $domain{$name} = \%this_domain;
1.852     albertel 8690: 	}
                   8691:     }
1.864     albertel 8692: 
                   8693:     sub reset_domain_info {
                   8694: 	undef($loaded);
                   8695: 	undef(%domain);
                   8696:     }
                   8697: 
1.852     albertel 8698:     sub load_domain_tab {
1.869     albertel 8699: 	my ($ignore_cache) = @_;
                   8700: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8701: 	my $fh;
                   8702: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8703: 	    my @lines = <$fh>;
                   8704: 	    &parse_domain_tab(\@lines);
1.448     albertel 8705: 	}
1.852     albertel 8706: 	close($fh);
                   8707: 	$loaded = 1;
1.327     albertel 8708:     }
1.846     albertel 8709: 
                   8710:     sub domain {
1.852     albertel 8711: 	&load_domain_tab() if (!$loaded);
                   8712: 
1.846     albertel 8713: 	my ($name,$what) = @_;
                   8714: 	return if ( !exists($domain{$name}) );
                   8715: 
                   8716: 	if (!$what) {
                   8717: 	    return $domain{$name}{'description'};
                   8718: 	}
                   8719: 	return $domain{$name}{$what};
                   8720:     }
1.974     raeburn  8721: 
                   8722:     sub domain_info {
                   8723:         &load_domain_tab() if (!$loaded);
                   8724:         return %domain;
                   8725:     }
                   8726: 
1.327     albertel 8727: }
                   8728: 
                   8729: 
1.1       albertel 8730: # ------------------------------------------------------------- Read hosts file
                   8731: {
1.838     albertel 8732:     my %hostname;
1.844     albertel 8733:     my %hostdom;
1.845     albertel 8734:     my %libserv;
1.852     albertel 8735:     my $loaded;
1.888     albertel 8736:     my %name_to_host;
1.852     albertel 8737: 
                   8738:     sub parse_hosts_tab {
                   8739: 	my ($file) = @_;
                   8740: 	foreach my $configline (@$file) {
                   8741: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8742: 	    next if ($configline =~ /^\^/);
                   8743: 	    chomp($configline);
1.968     raeburn  8744: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852     albertel 8745: 	    $name=~s/\s//g;
                   8746: 	    if ($id && $domain && $role && $name) {
                   8747: 		$hostname{$id}=$name;
1.888     albertel 8748: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8749: 		$hostdom{$id}=$domain;
                   8750: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  8751:                 if (defined($protocol)) {
                   8752:                     if ($protocol eq 'https') {
                   8753:                         $protocol{$id} = $protocol;
                   8754:                     } else {
                   8755:                         $protocol{$id} = 'http'; 
                   8756:                     }
1.968     raeburn  8757:                 } else {
1.969     raeburn  8758:                     $protocol{$id} = 'http';
1.968     raeburn  8759:                 }
1.852     albertel 8760: 	    }
                   8761: 	}
                   8762:     }
1.864     albertel 8763:     
                   8764:     sub reset_hosts_info {
1.897     albertel 8765: 	&purge_remembered();
1.864     albertel 8766: 	&reset_domain_info();
                   8767: 	&reset_hosts_ip_info();
1.892     albertel 8768: 	undef(%name_to_host);
1.864     albertel 8769: 	undef(%hostname);
                   8770: 	undef(%hostdom);
                   8771: 	undef(%libserv);
                   8772: 	undef($loaded);
                   8773:     }
1.1       albertel 8774: 
1.852     albertel 8775:     sub load_hosts_tab {
1.869     albertel 8776: 	my ($ignore_cache) = @_;
                   8777: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8778: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8779: 	my @config = <$config>;
                   8780: 	&parse_hosts_tab(\@config);
                   8781: 	close($config);
                   8782: 	$loaded=1;
1.1       albertel 8783:     }
1.852     albertel 8784: 
1.838     albertel 8785:     sub hostname {
1.852     albertel 8786: 	&load_hosts_tab() if (!$loaded);
                   8787: 
1.838     albertel 8788: 	my ($lonid) = @_;
                   8789: 	return $hostname{$lonid};
                   8790:     }
1.845     albertel 8791: 
1.838     albertel 8792:     sub all_hostnames {
1.852     albertel 8793: 	&load_hosts_tab() if (!$loaded);
                   8794: 
1.838     albertel 8795: 	return %hostname;
                   8796:     }
1.845     albertel 8797: 
1.888     albertel 8798:     sub all_names {
                   8799: 	&load_hosts_tab() if (!$loaded);
                   8800: 
                   8801: 	return %name_to_host;
                   8802:     }
                   8803: 
1.974     raeburn  8804:     sub all_host_domain {
                   8805:         &load_hosts_tab() if (!$loaded);
                   8806:         return %hostdom;
                   8807:     }
                   8808: 
1.845     albertel 8809:     sub is_library {
1.852     albertel 8810: 	&load_hosts_tab() if (!$loaded);
                   8811: 
1.845     albertel 8812: 	return exists($libserv{$_[0]});
                   8813:     }
                   8814: 
                   8815:     sub all_library {
1.852     albertel 8816: 	&load_hosts_tab() if (!$loaded);
                   8817: 
1.845     albertel 8818: 	return %libserv;
                   8819:     }
                   8820: 
1.841     albertel 8821:     sub get_servers {
1.852     albertel 8822: 	&load_hosts_tab() if (!$loaded);
                   8823: 
1.841     albertel 8824: 	my ($domain,$type) = @_;
                   8825: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8826: 	                                          : %hostname;
                   8827: 	my %result;
1.842     albertel 8828: 	if (ref($domain) eq 'ARRAY') {
                   8829: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8830: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8831: 		    $result{$host} = $hostname;
                   8832: 		}
                   8833: 	    }
                   8834: 	} else {
                   8835: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8836: 		if ($hostdom{$host} eq $domain) {
                   8837: 		    $result{$host} = $hostname;
                   8838: 		}
1.841     albertel 8839: 	    }
                   8840: 	}
                   8841: 	return %result;
                   8842:     }
1.845     albertel 8843: 
1.844     albertel 8844:     sub host_domain {
1.852     albertel 8845: 	&load_hosts_tab() if (!$loaded);
                   8846: 
1.844     albertel 8847: 	my ($lonid) = @_;
                   8848: 	return $hostdom{$lonid};
                   8849:     }
                   8850: 
1.841     albertel 8851:     sub all_domains {
1.852     albertel 8852: 	&load_hosts_tab() if (!$loaded);
                   8853: 
1.841     albertel 8854: 	my %seen;
                   8855: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8856: 	return @uniq;
                   8857:     }
1.1       albertel 8858: }
                   8859: 
1.847     albertel 8860: { 
                   8861:     my %iphost;
1.856     albertel 8862:     my %name_to_ip;
                   8863:     my %lonid_to_ip;
1.869     albertel 8864: 
1.847     albertel 8865:     sub get_hosts_from_ip {
                   8866: 	my ($ip) = @_;
                   8867: 	my %iphosts = &get_iphost();
                   8868: 	if (ref($iphosts{$ip})) {
                   8869: 	    return @{$iphosts{$ip}};
                   8870: 	}
                   8871: 	return;
1.839     albertel 8872:     }
1.864     albertel 8873:     
                   8874:     sub reset_hosts_ip_info {
                   8875: 	undef(%iphost);
                   8876: 	undef(%name_to_ip);
                   8877: 	undef(%lonid_to_ip);
                   8878:     }
1.856     albertel 8879: 
                   8880:     sub get_host_ip {
                   8881: 	my ($lonid) = @_;
                   8882: 	if (exists($lonid_to_ip{$lonid})) {
                   8883: 	    return $lonid_to_ip{$lonid};
                   8884: 	}
                   8885: 	my $name=&hostname($lonid);
                   8886:    	my $ip = gethostbyname($name);
                   8887: 	return if (!$ip || length($ip) ne 4);
                   8888: 	$ip=inet_ntoa($ip);
                   8889: 	$name_to_ip{$name}   = $ip;
                   8890: 	$lonid_to_ip{$lonid} = $ip;
                   8891: 	return $ip;
                   8892:     }
1.847     albertel 8893:     
                   8894:     sub get_iphost {
1.869     albertel 8895: 	my ($ignore_cache) = @_;
1.894     albertel 8896: 
1.869     albertel 8897: 	if (!$ignore_cache) {
                   8898: 	    if (%iphost) {
                   8899: 		return %iphost;
                   8900: 	    }
                   8901: 	    my ($ip_info,$cached)=
                   8902: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8903: 	    if ($cached) {
                   8904: 		%iphost      = %{$ip_info->[0]};
                   8905: 		%name_to_ip  = %{$ip_info->[1]};
                   8906: 		%lonid_to_ip = %{$ip_info->[2]};
                   8907: 		return %iphost;
                   8908: 	    }
                   8909: 	}
1.894     albertel 8910: 
                   8911: 	# get yesterday's info for fallback
                   8912: 	my %old_name_to_ip;
                   8913: 	my ($ip_info,$cached)=
                   8914: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8915: 	if ($cached) {
                   8916: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8917: 	}
                   8918: 
1.888     albertel 8919: 	my %name_to_host = &all_names();
                   8920: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8921: 	    my $ip;
                   8922: 	    if (!exists($name_to_ip{$name})) {
                   8923: 		$ip = gethostbyname($name);
                   8924: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8925: 		    if (defined($old_name_to_ip{$name})) {
                   8926: 			$ip = $old_name_to_ip{$name};
                   8927: 			&logthis("Can't find $name defaulting to old $ip");
                   8928: 		    } else {
                   8929: 			&logthis("Name $name no IP found");
                   8930: 			next;
                   8931: 		    }
                   8932: 		} else {
                   8933: 		    $ip=inet_ntoa($ip);
1.847     albertel 8934: 		}
                   8935: 		$name_to_ip{$name} = $ip;
                   8936: 	    } else {
                   8937: 		$ip = $name_to_ip{$name};
1.653     albertel 8938: 	    }
1.888     albertel 8939: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8940: 		$lonid_to_ip{$id} = $ip;
                   8941: 	    }
                   8942: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8943: 	}
1.869     albertel 8944: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8945: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8946: 				      48*60*60);
1.869     albertel 8947: 
1.847     albertel 8948: 	return %iphost;
1.598     albertel 8949:     }
                   8950: }
                   8951: 
1.862     albertel 8952: BEGIN {
                   8953: 
                   8954: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8955:     unless ($readit) {
                   8956: {
                   8957:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8958:     %perlvar = (%perlvar,%{$configvars});
                   8959: }
                   8960: 
                   8961: 
1.1       albertel 8962: # ------------------------------------------------------ Read spare server file
                   8963: {
1.448     albertel 8964:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8965: 
                   8966:     while (my $configline=<$config>) {
                   8967:        chomp($configline);
1.284     matthew  8968:        if ($configline) {
1.784     albertel 8969: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8970: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8971: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8972:        }
                   8973:     }
1.448     albertel 8974:     close($config);
1.1       albertel 8975: }
1.11      www      8976: # ------------------------------------------------------------ Read permissions
                   8977: {
1.448     albertel 8978:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8979: 
                   8980:     while (my $configline=<$config>) {
1.448     albertel 8981: 	chomp($configline);
                   8982: 	if ($configline) {
                   8983: 	    my ($role,$perm)=split(/ /,$configline);
                   8984: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8985: 	}
1.11      www      8986:     }
1.448     albertel 8987:     close($config);
1.11      www      8988: }
                   8989: 
                   8990: # -------------------------------------------- Read plain texts for permissions
                   8991: {
1.448     albertel 8992:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8993: 
                   8994:     while (my $configline=<$config>) {
1.448     albertel 8995: 	chomp($configline);
                   8996: 	if ($configline) {
1.742     raeburn  8997: 	    my ($short,@plain)=split(/:/,$configline);
                   8998:             %{$prp{$short}} = ();
                   8999: 	    if (@plain > 0) {
                   9000:                 $prp{$short}{'std'} = $plain[0];
                   9001:                 for (my $i=1; $i<@plain; $i++) {
                   9002:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   9003:                 }
                   9004:             }
1.448     albertel 9005: 	}
1.135     www      9006:     }
1.448     albertel 9007:     close($config);
1.135     www      9008: }
                   9009: 
                   9010: # ---------------------------------------------------------- Read package table
                   9011: {
1.448     albertel 9012:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      9013: 
                   9014:     while (my $configline=<$config>) {
1.483     albertel 9015: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 9016: 	chomp($configline);
                   9017: 	my ($short,$plain)=split(/:/,$configline);
                   9018: 	my ($pack,$name)=split(/\&/,$short);
                   9019: 	if ($plain ne '') {
                   9020: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   9021: 	    $packagetab{$short}=$plain; 
                   9022: 	}
1.11      www      9023:     }
1.448     albertel 9024:     close($config);
1.329     matthew  9025: }
                   9026: 
                   9027: # ------------- set up temporary directory
                   9028: {
                   9029:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   9030: 
1.11      www      9031: }
                   9032: 
1.794     albertel 9033: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   9034: 				'compress_threshold'=> 20_000,
                   9035:  			        });
1.185     www      9036: 
1.281     www      9037: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      9038: $dumpcount=0;
1.958     www      9039: $locknum=0;
1.22      www      9040: 
1.163     harris41 9041: &logtouch();
1.672     albertel 9042: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      9043: $readit=1;
1.564     albertel 9044:     {
                   9045: 	use integer;
                   9046: 	my $test=(2**32)+1;
1.568     albertel 9047: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 9048: 	&logthis(" Detected 64bit platform ($_64bit)");
                   9049:     }
1.195     www      9050: }
1.1       albertel 9051: }
1.179     www      9052: 
1.1       albertel 9053: 1;
1.191     harris41 9054: __END__
                   9055: 
1.243     albertel 9056: =pod
                   9057: 
1.191     harris41 9058: =head1 NAME
                   9059: 
1.243     albertel 9060: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 9061: 
                   9062: =head1 SYNOPSIS
                   9063: 
1.243     albertel 9064: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 9065: 
                   9066:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   9067: 
1.243     albertel 9068: Common parameters:
                   9069: 
                   9070: =over 4
                   9071: 
                   9072: =item *
                   9073: 
                   9074: $uname : an internal username (if $cname expecting a course Id specifically)
                   9075: 
                   9076: =item *
                   9077: 
                   9078: $udom : a domain (if $cdom expecting a course's domain specifically)
                   9079: 
                   9080: =item *
                   9081: 
                   9082: $symb : a resource instance identifier
                   9083: 
                   9084: =item *
                   9085: 
                   9086: $namespace : the name of a .db file that contains the data needed or
                   9087: being set.
                   9088: 
                   9089: =back
                   9090: 
1.394     bowersj2 9091: =head1 OVERVIEW
1.191     harris41 9092: 
1.394     bowersj2 9093: lonnet provides subroutines which interact with the
                   9094: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   9095: about classes, users, and resources.
1.243     albertel 9096: 
                   9097: For many of these objects you can also use this to store data about
                   9098: them or modify them in various ways.
1.191     harris41 9099: 
1.394     bowersj2 9100: =head2 Symbs
1.191     harris41 9101: 
1.394     bowersj2 9102: To identify a specific instance of a resource, LON-CAPA uses symbols
                   9103: or "symbs"X<symb>. These identifiers are built from the URL of the
                   9104: map, the resource number of the resource in the map, and the URL of
                   9105: the resource itself. The latter is somewhat redundant, but might help
                   9106: if maps change.
                   9107: 
                   9108: An example is
                   9109: 
                   9110:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   9111: 
                   9112: The respective map entry is
                   9113: 
                   9114:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   9115:   title="Problem 2">
                   9116:  </resource>
                   9117: 
                   9118: Symbs are used by the random number generator, as well as to store and
                   9119: restore data specific to a certain instance of for example a problem.
                   9120: 
                   9121: =head2 Storing And Retrieving Data
                   9122: 
                   9123: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   9124: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   9125: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   9126: is is the non-critical message twin of cstore. These functions are for
                   9127: handlers to store a perl hash to a user's permanent data space in an
                   9128: easy manner, and to retrieve it again on another call. It is expected
                   9129: that a handler would use this once at the beginning to retrieve data,
                   9130: and then again once at the end to send only the new data back.
                   9131: 
                   9132: The data is stored in the user's data directory on the user's
                   9133: homeserver under the ID of the course.
                   9134: 
                   9135: The hash that is returned by restore will have all of the previous
                   9136: value for all of the elements of the hash.
                   9137: 
                   9138: Example:
                   9139: 
                   9140:  #creating a hash
                   9141:  my %hash;
                   9142:  $hash{'foo'}='bar';
                   9143: 
                   9144:  #storing it
                   9145:  &Apache::lonnet::cstore(\%hash);
                   9146: 
                   9147:  #changing a value
                   9148:  $hash{'foo'}='notbar';
                   9149: 
                   9150:  #adding a new value
                   9151:  $hash{'bar'}='foo';
                   9152:  &Apache::lonnet::cstore(\%hash);
                   9153: 
                   9154:  #retrieving the hash
                   9155:  my %history=&Apache::lonnet::restore();
                   9156: 
                   9157:  #print the hash
                   9158:  foreach my $key (sort(keys(%history))) {
                   9159:    print("\%history{$key} = $history{$key}");
                   9160:  }
                   9161: 
                   9162: Will print out:
1.191     harris41 9163: 
1.394     bowersj2 9164:  %history{1:foo} = bar
                   9165:  %history{1:keys} = foo:timestamp
                   9166:  %history{1:timestamp} = 990455579
                   9167:  %history{2:bar} = foo
                   9168:  %history{2:foo} = notbar
                   9169:  %history{2:keys} = foo:bar:timestamp
                   9170:  %history{2:timestamp} = 990455580
                   9171:  %history{bar} = foo
                   9172:  %history{foo} = notbar
                   9173:  %history{timestamp} = 990455580
                   9174:  %history{version} = 2
                   9175: 
                   9176: Note that the special hash entries C<keys>, C<version> and
                   9177: C<timestamp> were added to the hash. C<version> will be equal to the
                   9178: total number of versions of the data that have been stored. The
                   9179: C<timestamp> attribute will be the UNIX time the hash was
                   9180: stored. C<keys> is available in every historical section to list which
                   9181: keys were added or changed at a specific historical revision of a
                   9182: hash.
                   9183: 
                   9184: B<Warning>: do not store the hash that restore returns directly. This
                   9185: will cause a mess since it will restore the historical keys as if the
                   9186: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 9187: 
1.394     bowersj2 9188: Calling convention:
1.191     harris41 9189: 
1.394     bowersj2 9190:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   9191:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 9192: 
1.394     bowersj2 9193: For more detailed information, see lonnet specific documentation.
1.191     harris41 9194: 
1.394     bowersj2 9195: =head1 RETURN MESSAGES
1.191     harris41 9196: 
1.394     bowersj2 9197: =over 4
1.191     harris41 9198: 
1.394     bowersj2 9199: =item * B<con_lost>: unable to contact remote host
1.191     harris41 9200: 
1.394     bowersj2 9201: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   9202: when the connection is brought back up
1.191     harris41 9203: 
1.394     bowersj2 9204: =item * B<con_failed>: unable to contact remote host and unable to save message
                   9205: for later delivery
1.191     harris41 9206: 
1.967     bisitz   9207: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 9208: 
1.394     bowersj2 9209: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 9210: that was requested
1.191     harris41 9211: 
1.243     albertel 9212: =back
1.191     harris41 9213: 
1.243     albertel 9214: =head1 PUBLIC SUBROUTINES
1.191     harris41 9215: 
1.243     albertel 9216: =head2 Session Environment Functions
1.191     harris41 9217: 
1.243     albertel 9218: =over 4
1.191     harris41 9219: 
1.394     bowersj2 9220: =item * 
                   9221: X<appenv()>
1.949     raeburn  9222: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 9223: the user envirnoment file, and will be restored for each access this
1.620     albertel 9224: user makes during this session, also modifies the %env for the current
1.949     raeburn  9225: process. Optional rolesarrayref - if defined contains a reference to an array
                   9226: of roles which are exempt from the restriction on modifying user.role entries 
                   9227: in the user's environment.db and in %env.    
1.191     harris41 9228: 
                   9229: =item *
1.394     bowersj2 9230: X<delenv()>
                   9231: B<delenv($regexp)>: removes all items from the session
                   9232: environment file that matches the regular expression in $regexp. The
1.620     albertel 9233: values are also delted from the current processes %env.
1.191     harris41 9234: 
1.795     albertel 9235: =item * get_env_multiple($name) 
                   9236: 
                   9237: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   9238: values may be defined and end up as an array ref.
                   9239: 
                   9240: returns an array of values
                   9241: 
1.243     albertel 9242: =back
                   9243: 
                   9244: =head2 User Information
1.191     harris41 9245: 
1.243     albertel 9246: =over 4
1.191     harris41 9247: 
                   9248: =item *
1.394     bowersj2 9249: X<queryauthenticate()>
                   9250: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 9251: authentication scheme
                   9252: 
                   9253: =item *
1.394     bowersj2 9254: X<authenticate()>
                   9255: B<authenticate($uname,$upass,$udom)>: try to
                   9256: authenticate user from domain's lib servers (first use the current
                   9257: one). C<$upass> should be the users password.
1.191     harris41 9258: 
                   9259: =item *
1.394     bowersj2 9260: X<homeserver()>
                   9261: B<homeserver($uname,$udom)>: find the server which has
                   9262: the user's directory and files (there must be only one), this caches
                   9263: the answer, and also caches if there is a borken connection.
1.191     harris41 9264: 
                   9265: =item *
1.394     bowersj2 9266: X<idget()>
                   9267: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   9268: (IDs are a unique resource in a domain, there must be only 1 ID per
                   9269: username, and only 1 username per ID in a specific domain) (returns
                   9270: hash: id=>name,id=>name)
1.191     harris41 9271: 
                   9272: =item *
1.394     bowersj2 9273: X<idrget()>
                   9274: B<idrget($udom,@unames)>: find the IDs behind a list of
                   9275: usernames (returns hash: name=>id,name=>id)
1.191     harris41 9276: 
                   9277: =item *
1.394     bowersj2 9278: X<idput()>
                   9279: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 9280: 
                   9281: =item *
1.394     bowersj2 9282: X<rolesinit()>
                   9283: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 9284: 
                   9285: =item *
1.551     albertel 9286: X<getsection()>
                   9287: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 9288: course $cname, return section name/number or '' for "not in course"
                   9289: and '-1' for "no section"
                   9290: 
                   9291: =item *
1.394     bowersj2 9292: X<userenvironment()>
                   9293: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 9294: passed in @what from the requested user's environment, returns a hash
                   9295: 
1.858     raeburn  9296: =item * 
                   9297: X<userlog_query()>
1.859     albertel 9298: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   9299: activity.log file. %filters defines filters applied when parsing the
                   9300: log file. These can be start or end timestamps, or the type of action
                   9301: - log to look for Login or Logout events, check for Checkin or
                   9302: Checkout, role for role selection. The response is in the form
                   9303: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   9304: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  9305: 
1.243     albertel 9306: =back
                   9307: 
                   9308: =head2 User Roles
                   9309: 
                   9310: =over 4
                   9311: 
                   9312: =item *
                   9313: 
1.810     raeburn  9314: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 9315:  F: full access
                   9316:  U,I,K: authentication modes (cxx only)
                   9317:  '': forbidden
                   9318:  1: user needs to choose course
                   9319:  2: browse allowed
1.766     albertel 9320:  A: passphrase authentication needed
1.243     albertel 9321: 
                   9322: =item *
                   9323: 
                   9324: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   9325: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   9326: and course level
                   9327: 
                   9328: =item *
                   9329: 
                   9330: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   9331: explanation of a user role term
                   9332: 
1.832     raeburn  9333: =item *
                   9334: 
1.935     raeburn  9335: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  9336: All arguments are optional. Returns a hash of a roles, either for
                   9337: co-author/assistant author roles for a user's Construction Space
1.906     albertel 9338: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  9339: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   9340: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   9341: For each key, value is set to colon-separated start and end times for
                   9342: the role.  If no username and domain are specified, will default to
1.934     raeburn  9343: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  9344: of role statuses (active, future or previous), roles 
                   9345: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   9346: to restrict the list of roles reported. If no array ref is 
                   9347: provided for types, will default to return only active roles.
1.834     albertel 9348: 
1.243     albertel 9349: =back
                   9350: 
                   9351: =head2 User Modification
                   9352: 
                   9353: =over 4
                   9354: 
                   9355: =item *
                   9356: 
1.957     raeburn  9357: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 9358: user for the level given by URL.  Optional start and end dates (leave empty
                   9359: string or zero for "no date")
1.191     harris41 9360: 
                   9361: =item *
                   9362: 
1.243     albertel 9363: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   9364: change a users, password, possible return values are: ok,
                   9365: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   9366: refused
1.191     harris41 9367: 
                   9368: =item *
                   9369: 
1.243     albertel 9370: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9371: 
                   9372: =item *
                   9373: 
1.963     raeburn  9374: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
                   9375:            $forceid,$desiredhome,$email,$inststatus) : 
1.243     albertel 9376: modify user
1.191     harris41 9377: 
                   9378: =item *
                   9379: 
1.286     matthew  9380: modifystudent
                   9381: 
1.957     raeburn  9382: modify a student's enrollment and identification information.
1.286     matthew  9383: The course id is resolved based on the current users environment.  
                   9384: This means the envoking user must be a course coordinator or otherwise
                   9385: associated with a course.
                   9386: 
1.297     matthew  9387: This call is essentially a wrapper for lonnet::modifyuser and
                   9388: lonnet::modify_student_enrollment
1.286     matthew  9389: 
                   9390: Inputs: 
                   9391: 
                   9392: =over 4
                   9393: 
1.957     raeburn  9394: =item B<$udom> Student's loncapa domain
1.286     matthew  9395: 
1.957     raeburn  9396: =item B<$uname> Student's loncapa login name
1.286     matthew  9397: 
1.964     bisitz   9398: =item B<$uid> Student/Employee ID
1.286     matthew  9399: 
1.957     raeburn  9400: =item B<$umode> Student's authentication mode
1.286     matthew  9401: 
1.957     raeburn  9402: =item B<$upass> Student's password
1.286     matthew  9403: 
1.957     raeburn  9404: =item B<$first> Student's first name
1.286     matthew  9405: 
1.957     raeburn  9406: =item B<$middle> Student's middle name
1.286     matthew  9407: 
1.957     raeburn  9408: =item B<$last> Student's last name
1.286     matthew  9409: 
1.957     raeburn  9410: =item B<$gene> Student's generation
1.286     matthew  9411: 
1.957     raeburn  9412: =item B<$usec> Student's section in course
1.286     matthew  9413: 
                   9414: =item B<$end> Unix time of the roles expiration
                   9415: 
                   9416: =item B<$start> Unix time of the roles start date
                   9417: 
                   9418: =item B<$forceid> If defined, allow $uid to be changed
                   9419: 
                   9420: =item B<$desiredhome> server to use as home server for student
                   9421: 
1.957     raeburn  9422: =item B<$email> Student's permanent e-mail address
                   9423: 
                   9424: =item B<$type> Type of enrollment (auto or manual)
                   9425: 
1.963     raeburn  9426: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   9427: 
                   9428: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  9429: 
1.963     raeburn  9430: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  9431: 
1.963     raeburn  9432: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  9433: 
1.963     raeburn  9434: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  9435: 
1.286     matthew  9436: =back
1.297     matthew  9437: 
                   9438: =item *
                   9439: 
                   9440: modify_student_enrollment
                   9441: 
                   9442: Change a students enrollment status in a class.  The environment variable
                   9443: 'role.request.course' must be defined for this function to proceed.
                   9444: 
                   9445: Inputs:
                   9446: 
                   9447: =over 4
                   9448: 
                   9449: =item $udom, students domain
                   9450: 
                   9451: =item $uname, students name
                   9452: 
                   9453: =item $uid, students user id
                   9454: 
                   9455: =item $first, students first name
                   9456: 
                   9457: =item $middle
                   9458: 
                   9459: =item $last
                   9460: 
                   9461: =item $gene
                   9462: 
                   9463: =item $usec
                   9464: 
                   9465: =item $end
                   9466: 
                   9467: =item $start
                   9468: 
1.957     raeburn  9469: =item $type
                   9470: 
                   9471: =item $locktype
                   9472: 
                   9473: =item $cid
                   9474: 
                   9475: =item $selfenroll
                   9476: 
                   9477: =item $context
                   9478: 
1.297     matthew  9479: =back
                   9480: 
1.191     harris41 9481: 
                   9482: =item *
                   9483: 
1.243     albertel 9484: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9485: custom role; give a custom role to a user for the level given by URL.  Specify
                   9486: name and domain of role author, and role name
1.191     harris41 9487: 
                   9488: =item *
                   9489: 
1.243     albertel 9490: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9491: 
                   9492: =item *
                   9493: 
1.243     albertel 9494: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9495: 
                   9496: =back
                   9497: 
                   9498: =head2 Course Infomation
                   9499: 
                   9500: =over 4
1.191     harris41 9501: 
                   9502: =item *
                   9503: 
1.631     albertel 9504: coursedescription($courseid) : returns a hash of information about the
                   9505: specified course id, including all environment settings for the
                   9506: course, the description of the course will be in the hash under the
                   9507: key 'description'
1.191     harris41 9508: 
                   9509: =item *
                   9510: 
1.624     albertel 9511: resdata($name,$domain,$type,@which) : request for current parameter
                   9512: setting for a specific $type, where $type is either 'course' or 'user',
                   9513: @what should be a list of parameters to ask about. This routine caches
                   9514: answers for 5 minutes.
1.243     albertel 9515: 
1.877     foxr     9516: =item *
                   9517: 
                   9518: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9519: data base, returning a hash that is keyed by the resource name and has
                   9520: values that are the resource value.  I believe that the timestamps and
                   9521: versions are also returned.
                   9522: 
                   9523: 
1.243     albertel 9524: =back
                   9525: 
                   9526: =head2 Course Modification
                   9527: 
                   9528: =over 4
1.191     harris41 9529: 
                   9530: =item *
                   9531: 
1.243     albertel 9532: writecoursepref($courseid,%prefs) : write preferences (environment
                   9533: database) for a course
1.191     harris41 9534: 
                   9535: =item *
                   9536: 
1.243     albertel 9537: createcourse($udom,$description,$url) : make/modify course
                   9538: 
                   9539: =back
                   9540: 
                   9541: =head2 Resource Subroutines
                   9542: 
                   9543: =over 4
1.191     harris41 9544: 
                   9545: =item *
                   9546: 
1.243     albertel 9547: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9548: 
                   9549: =item *
                   9550: 
1.243     albertel 9551: repcopy($filename) : subscribes to the requested file, and attempts to
                   9552: replicate from the owning library server, Might return
1.607     raeburn  9553: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9554: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9555: resource. Expects the local filesystem pathname
                   9556: (/home/httpd/html/res/....)
                   9557: 
                   9558: =back
                   9559: 
                   9560: =head2 Resource Information
                   9561: 
                   9562: =over 4
1.191     harris41 9563: 
                   9564: =item *
                   9565: 
1.243     albertel 9566: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9567: a vairety of different possible values, $varname should be a request
                   9568: string, and the other parameters can be used to specify who and what
                   9569: one is asking about.
                   9570: 
                   9571: Possible values for $varname are environment.lastname (or other item
                   9572: from the envirnment hash), user.name (or someother aspect about the
                   9573: user), resource.0.maxtries (or some other part and parameter of a
                   9574: resource)
1.204     albertel 9575: 
                   9576: =item *
                   9577: 
1.243     albertel 9578: directcondval($number) : get current value of a condition; reads from a state
                   9579: string
1.204     albertel 9580: 
                   9581: =item *
                   9582: 
1.243     albertel 9583: condval($condidx) : value of condition index based on state
1.204     albertel 9584: 
                   9585: =item *
                   9586: 
1.243     albertel 9587: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9588: resource's metadata, $what should be either a specific key, or either
                   9589: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9590: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9591: 
                   9592: this function automatically caches all requests
1.191     harris41 9593: 
                   9594: =item *
                   9595: 
1.243     albertel 9596: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9597: network of library servers; returns file handle of where SQL and regex results
                   9598: will be stored for query
1.191     harris41 9599: 
                   9600: =item *
                   9601: 
1.243     albertel 9602: symbread($filename) : return symbolic list entry (filename argument optional);
                   9603: returns the data handle
1.191     harris41 9604: 
                   9605: =item *
                   9606: 
1.243     albertel 9607: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9608: a possible symb for the URL in $thisfn, and if is an encryypted
                   9609: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9610: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9611: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9612: 
1.191     harris41 9613: 
                   9614: =item *
                   9615: 
1.243     albertel 9616: symbclean($symb) : removes versions numbers from a symb, returns the
                   9617: cleaned symb
1.191     harris41 9618: 
                   9619: =item *
                   9620: 
1.243     albertel 9621: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9622: course map, user must be in a course for it to work.
1.191     harris41 9623: 
                   9624: =item *
                   9625: 
1.243     albertel 9626: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9627: 
                   9628: =item *
                   9629: 
1.243     albertel 9630: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9631: a random seed, all arguments are optional, if they aren't sent it uses the
                   9632: environment to derive them. Note: if symb isn't sent and it can't get one
                   9633: from &symbread it will use the current time as its return value
1.191     harris41 9634: 
                   9635: =item *
                   9636: 
1.243     albertel 9637: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9638: unfakeable, receipt
1.191     harris41 9639: 
                   9640: =item *
                   9641: 
1.620     albertel 9642: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9643: 
                   9644: =item *
                   9645: 
1.243     albertel 9646: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9647: 
                   9648: =item *
                   9649: 
1.243     albertel 9650: 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 9651: 
                   9652: =item *
                   9653: 
1.243     albertel 9654: 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 9655: 
                   9656: =item *
                   9657: 
1.243     albertel 9658: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9659: 
                   9660: =item *
                   9661: 
1.243     albertel 9662: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9663: forcing spreadsheet to reevaluate the resource scores next time.
                   9664: 
                   9665: =back
                   9666: 
                   9667: =head2 Storing/Retreiving Data
                   9668: 
                   9669: =over 4
1.191     harris41 9670: 
                   9671: =item *
                   9672: 
1.243     albertel 9673: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9674: for this url; hashref needs to be given and should be a \%hashname; the
                   9675: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9676: be derived from the env
1.191     harris41 9677: 
                   9678: =item *
                   9679: 
1.243     albertel 9680: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9681: uses critical subroutine
1.191     harris41 9682: 
                   9683: =item *
                   9684: 
1.243     albertel 9685: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9686: all args are optional
1.191     harris41 9687: 
                   9688: =item *
                   9689: 
1.717     albertel 9690: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9691: dumps the complete (or key matching regexp) namespace into a hash
                   9692: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9693: normally &store()ed into
                   9694: 
                   9695: $range should be either an integer '100' (give me the first 100
                   9696:                                            matching records)
                   9697:               or be  two integers sperated by a - with no spaces
                   9698:                  '30-50' (give me the 30th through the 50th matching
                   9699:                           records)
                   9700: 
                   9701: 
                   9702: =item *
                   9703: 
                   9704: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9705: replaces a &store() version of data with a replacement set of data
                   9706: for a particular resource in a namespace passed in the $storehash hash 
                   9707: reference
                   9708: 
                   9709: =item *
                   9710: 
1.243     albertel 9711: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9712: works very similar to store/cstore, but all data is stored in a
                   9713: temporary location and can be reset using tmpreset, $storehash should
                   9714: be a hash reference, returns nothing on success
1.191     harris41 9715: 
                   9716: =item *
                   9717: 
1.243     albertel 9718: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9719: similar to restore, but all data is stored in a temporary location and
                   9720: can be reset using tmpreset. Returns a hash of values on success,
                   9721: error string otherwise.
1.191     harris41 9722: 
                   9723: =item *
                   9724: 
1.243     albertel 9725: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9726: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9727: 
                   9728: =item *
                   9729: 
1.243     albertel 9730: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9731: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9732: 
                   9733: =item *
                   9734: 
1.243     albertel 9735: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9736: namesp ($udom and $uname are optional)
1.191     harris41 9737: 
                   9738: =item *
                   9739: 
1.702     albertel 9740: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9741: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9742: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9743: 
1.702     albertel 9744: $range should be either an integer '100' (give me the first 100
                   9745:                                            matching records)
                   9746:               or be  two integers sperated by a - with no spaces
                   9747:                  '30-50' (give me the 30th through the 50th matching
                   9748:                           records)
1.449     matthew  9749: =item *
                   9750: 
                   9751: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9752: $store can be a scalar, an array reference, or if the amount to be 
                   9753: incremented is > 1, a hash reference.
                   9754: 
                   9755: ($udom and $uname are optional)
1.191     harris41 9756: 
                   9757: =item *
                   9758: 
1.243     albertel 9759: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9760: ($udom and $uname are optional)
1.191     harris41 9761: 
                   9762: =item *
                   9763: 
1.243     albertel 9764: cput($namespace,$storehash,$udom,$uname) : critical put
                   9765: ($udom and $uname are optional)
1.191     harris41 9766: 
                   9767: =item *
                   9768: 
1.748     albertel 9769: newput($namespace,$storehash,$udom,$uname) :
                   9770: 
                   9771: Attempts to store the items in the $storehash, but only if they don't
                   9772: currently exist, if this succeeds you can be certain that you have 
                   9773: successfully created a new key value pair in the $namespace db.
                   9774: 
                   9775: 
                   9776: Args:
                   9777:  $namespace: name of database to store values to
                   9778:  $storehash: hashref to store to the db
                   9779:  $udom: (optional) domain of user containing the db
                   9780:  $uname: (optional) name of user caontaining the db
                   9781: 
                   9782: Returns:
                   9783:  'ok' -> succeeded in storing all keys of $storehash
                   9784:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9785:                         least <key> already existed in the db (other
                   9786:                         requested keys may also already exist)
1.967     bisitz   9787:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 9788:  'con_lost' -> unable to contact request server
                   9789:  'refused' -> action was not allowed by remote machine
                   9790: 
                   9791: 
                   9792: =item *
                   9793: 
1.243     albertel 9794: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9795: reference filled in from namesp (encrypts the return communication)
                   9796: ($udom and $uname are optional)
1.191     harris41 9797: 
                   9798: =item *
                   9799: 
1.243     albertel 9800: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9801: critical subroutine
                   9802: 
1.806     raeburn  9803: =item *
                   9804: 
1.860     raeburn  9805: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9806: array reference filled in from namespace found in domain level on either
                   9807: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9808: 
                   9809: =item *
                   9810: 
1.860     raeburn  9811: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9812: domain level either on specified domain server ($uhome) or primary domain 
                   9813: server ($udom and $uhome are optional)
1.806     raeburn  9814: 
1.943     raeburn  9815: =item * 
                   9816: 
                   9817: get_domain_defaults($target_domain) : returns hash with defaults for
                   9818: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   9819: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   9820: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   9821: Values are retrieved from cache (if current), or from domain's configuration.db
                   9822: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   9823: or lonTabs/domain.tab. 
                   9824: 
                   9825: %domdefaults = &get_auth_defaults($target_domain);
                   9826: 
1.243     albertel 9827: =back
                   9828: 
                   9829: =head2 Network Status Functions
                   9830: 
                   9831: =over 4
1.191     harris41 9832: 
                   9833: =item *
                   9834: 
                   9835: dirlist($uri) : return directory list based on URI
                   9836: 
                   9837: =item *
                   9838: 
1.243     albertel 9839: spareserver() : find server with least workload from spare.tab
                   9840: 
                   9841: =back
                   9842: 
                   9843: =head2 Apache Request
                   9844: 
                   9845: =over 4
1.191     harris41 9846: 
                   9847: =item *
                   9848: 
1.243     albertel 9849: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9850: localhost, posts hash
                   9851: 
                   9852: =back
                   9853: 
                   9854: =head2 Data to String to Data
                   9855: 
                   9856: =over 4
1.191     harris41 9857: 
                   9858: =item *
                   9859: 
1.243     albertel 9860: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9861: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9862: 
                   9863: =item *
                   9864: 
1.243     albertel 9865: hashref2str($hashref) : convert a hashref into a string complete with
                   9866: escaping and '=' and '&' separators, supports elements that are
                   9867: arrayrefs and hashrefs
1.191     harris41 9868: 
                   9869: =item *
                   9870: 
1.243     albertel 9871: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9872: with escaping and '&' separators, supports elements that are arrayrefs
                   9873: and hashrefs
1.191     harris41 9874: 
                   9875: =item *
                   9876: 
1.243     albertel 9877: str2hash($string) : convert string to hash using unescaping and
                   9878: splitting on '=' and '&', supports elements that are arrayrefs and
                   9879: hashrefs
1.191     harris41 9880: 
                   9881: =item *
                   9882: 
1.243     albertel 9883: str2array($string) : convert string to hash using unescaping and
                   9884: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9885: 
                   9886: =back
                   9887: 
                   9888: =head2 Logging Routines
                   9889: 
                   9890: =over 4
                   9891: 
                   9892: These routines allow one to make log messages in the lonnet.log and
                   9893: lonnet.perm logfiles.
1.191     harris41 9894: 
                   9895: =item *
                   9896: 
1.243     albertel 9897: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9898: 
                   9899: =item *
                   9900: 
1.243     albertel 9901: logthis() : append message to the normal lonnet.log file, it gets
                   9902: preiodically rolled over and deleted.
1.191     harris41 9903: 
                   9904: =item *
                   9905: 
1.243     albertel 9906: logperm() : append a permanent message to lonnet.perm.log, this log
                   9907: file never gets deleted by any automated portion of the system, only
                   9908: messages of critical importance should go in here.
                   9909: 
                   9910: =back
                   9911: 
                   9912: =head2 General File Helper Routines
                   9913: 
                   9914: =over 4
1.191     harris41 9915: 
                   9916: =item *
                   9917: 
1.481     raeburn  9918: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9919: (a) files in /uploaded
                   9920:   (i) If a local copy of the file exists - 
                   9921:       compares modification date of local copy with last-modified date for 
                   9922:       definitive version stored on home server for course. If local copy is 
                   9923:       stale, requests a new version from the home server and stores it. 
                   9924:       If the original has been removed from the home server, then local copy 
                   9925:       is unlinked.
                   9926:   (ii) If local copy does not exist -
                   9927:       requests the file from the home server and stores it. 
                   9928:   
                   9929:   If $caller is 'uploadrep':  
                   9930:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9931:     for request for files originally uploaded via DOCS. 
                   9932:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9933:   
                   9934:   Otherwise:
                   9935:      This indicates a call from the content generation phase of the request.
                   9936:      -  returns the entire contents of the file or -1.
                   9937:      
                   9938: (b) files in /res
                   9939:    - returns the entire contents of a file or -1; 
                   9940:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9941: 
1.712     albertel 9942: 
                   9943: =item *
                   9944: 
                   9945: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9946:                   reference
                   9947: 
                   9948: returns either a stat() list of data about the file or an empty list
                   9949: if the file doesn't exist or couldn't find out about it (connection
                   9950: problems or user unknown)
                   9951: 
1.191     harris41 9952: =item *
                   9953: 
1.243     albertel 9954: filelocation($dir,$file) : returns file system location of a file
                   9955: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9956: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9957: and a file of ../bob will become /a/bob)
1.191     harris41 9958: 
                   9959: =item *
                   9960: 
                   9961: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9962: filelocation except for hrefs
                   9963: 
                   9964: =item *
                   9965: 
                   9966: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9967: 
1.243     albertel 9968: =back
                   9969: 
1.608     albertel 9970: =head2 Usererfile file routines (/uploaded*)
                   9971: 
                   9972: =over 4
                   9973: 
                   9974: =item *
                   9975: 
                   9976: userfileupload(): main rotine for putting a file in a user or course's
                   9977:                   filespace, arguments are,
                   9978: 
1.620     albertel 9979:  formname - required - this is the name of the element in $env where the
1.608     albertel 9980:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9981:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9982:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9983:  coursedoc - if true, store the file in the course of the active role
                   9984:              of the current user
                   9985:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9986:          if undefined, it will be placed in "unknown"
                   9987: 
                   9988:  (This routine calls clean_filename() to remove any dangerous
                   9989:  characters from the filename, and then calls finuserfileupload() to
                   9990:  complete the transaction)
                   9991: 
                   9992:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9993:  and /adm/notfound.html if unsuccessful
                   9994: 
                   9995: =item *
                   9996: 
                   9997: clean_filename(): routine for cleaing a filename up for storage in
                   9998:                  userfile space, argument is:
                   9999: 
                   10000:  filename - proposed filename
                   10001: 
                   10002: returns: the new clean filename
                   10003: 
                   10004: =item *
                   10005: 
                   10006: finishuserfileupload(): routine that creaes and sends the file to
                   10007: userspace, probably shouldn't be called directly
                   10008: 
                   10009:   docuname: username or courseid of destination for the file
                   10010:   docudom: domain of user/course of destination for the file
                   10011:   formname: same as for userfileupload()
                   10012:   fname: filename (inculding subdirectories) for the file
                   10013: 
                   10014:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10015:  and /adm/notfound.html if unsuccessful
                   10016: 
                   10017: =item *
                   10018: 
                   10019: renameuserfile(): renames an existing userfile to a new name
                   10020: 
                   10021:   Args:
                   10022:    docuname: username or courseid of destination for the file
                   10023:    docudom: domain of user/course of destination for the file
                   10024:    old: current file name (including any subdirs under userfiles)
                   10025:    new: desired file name (including any subdirs under userfiles)
                   10026: 
                   10027: =item *
                   10028: 
                   10029: mkdiruserfile(): creates a directory is a userfiles dir
                   10030: 
                   10031:   Args:
                   10032:    docuname: username or courseid of destination for the file
                   10033:    docudom: domain of user/course of destination for the file
                   10034:    dir: dir to create (including any subdirs under userfiles)
                   10035: 
                   10036: =item *
                   10037: 
                   10038: removeuserfile(): removes a file that exists in userfiles
                   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:    fname: filname to delete (including any subdirs under userfiles)
                   10044: 
                   10045: =item *
                   10046: 
                   10047: removeuploadedurl(): convience function for removeuserfile()
                   10048: 
                   10049:   Args:
                   10050:    url:  a full /uploaded/... url to delete
                   10051: 
1.747     albertel 10052: =item * 
                   10053: 
                   10054: get_portfile_permissions():
                   10055:   Args:
                   10056:     domain: domain of user or course contain the portfolio files
                   10057:     user: name of user or num of course contain the portfolio files
                   10058:   Returns:
                   10059:     hashref of a dump of the proper file_permissions.db
                   10060:    
                   10061: 
                   10062: =item * 
                   10063: 
                   10064: get_access_controls():
                   10065: 
                   10066: Args:
                   10067:   current_permissions: the hash ref returned from get_portfile_permissions()
                   10068:   group: (optional) the group you want the files associated with
                   10069:   file: (optional) the file you want access info on
                   10070: 
                   10071: Returns:
1.749     raeburn  10072:     a hash (keys are file names) of hashes containing
                   10073:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   10074:         values are XML containing access control settings (see below) 
1.747     albertel 10075: 
                   10076: Internal notes:
                   10077: 
1.749     raeburn  10078:  access controls are stored in file_permissions.db as key=value pairs.
                   10079:     key -> path to file/file_name\0uniqueID:scope_end_start
                   10080:         where scope -> public,guest,course,group,domains or users.
                   10081:               end -> UNIX time for end of access (0 -> no end date)
                   10082:               start -> UNIX time for start of access
                   10083: 
                   10084:     value -> XML description of access control
                   10085:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   10086:             <start></start>
                   10087:             <end></end>
                   10088: 
                   10089:             <password></password>  for scope type = guest
                   10090: 
                   10091:             <domain></domain>     for scope type = course or group
                   10092:             <number></number>
                   10093:             <roles id="">
                   10094:              <role></role>
                   10095:              <access></access>
                   10096:              <section></section>
                   10097:              <group></group>
                   10098:             </roles>
                   10099: 
                   10100:             <dom></dom>         for scope type = domains
                   10101: 
                   10102:             <users>             for scope type = users
                   10103:              <user>
                   10104:               <uname></uname>
                   10105:               <udom></udom>
                   10106:              </user>
                   10107:             </users>
                   10108:            </scope> 
                   10109:               
                   10110:  Access data is also aggregated for each file in an additional key=value pair:
                   10111:  key -> path to file/file_name\0accesscontrol 
                   10112:  value -> reference to hash
                   10113:           hash contains key = value pairs
                   10114:           where key = uniqueID:scope_end_start
                   10115:                 value = UNIX time record was last updated
                   10116: 
                   10117:           Used to improve speed of look-ups of access controls for each file.  
                   10118:  
                   10119:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   10120: 
                   10121: modify_access_controls():
                   10122: 
                   10123: Modifies access controls for a portfolio file
                   10124: Args
                   10125: 1. file name
                   10126: 2. reference to hash of required changes,
                   10127: 3. domain
                   10128: 4. username
                   10129:   where domain,username are the domain of the portfolio owner 
                   10130:   (either a user or a course) 
                   10131: 
                   10132: Returns:
                   10133: 1. result of additions or updates ('ok' or 'error', with error message). 
                   10134: 2. result of deletions ('ok' or 'error', with error message).
                   10135: 3. reference to hash of any new or updated access controls.
                   10136: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   10137:    key = integer (inbound ID)
                   10138:    value = uniqueID  
1.747     albertel 10139: 
1.608     albertel 10140: =back
                   10141: 
1.243     albertel 10142: =head2 HTTP Helper Routines
                   10143: 
                   10144: =over 4
                   10145: 
1.191     harris41 10146: =item *
                   10147: 
                   10148: escape() : unpack non-word characters into CGI-compatible hex codes
                   10149: 
                   10150: =item *
                   10151: 
                   10152: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   10153: 
1.243     albertel 10154: =back
                   10155: 
                   10156: =head1 PRIVATE SUBROUTINES
                   10157: 
                   10158: =head2 Underlying communication routines (Shouldn't call)
                   10159: 
                   10160: =over 4
                   10161: 
                   10162: =item *
                   10163: 
                   10164: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   10165: 
                   10166: =item *
                   10167: 
                   10168: reply() : uses subreply to send a message to remote machine, logs all failures
                   10169: 
                   10170: =item *
                   10171: 
                   10172: critical() : passes a critical message to another server; if cannot
                   10173: get through then place message in connection buffer directory and
                   10174: returns con_delayed, if incapable of saving message, returns
                   10175: con_failed
                   10176: 
                   10177: =item *
                   10178: 
                   10179: reconlonc() : tries to reconnect lonc client processes.
                   10180: 
                   10181: =back
                   10182: 
                   10183: =head2 Resource Access Logging
                   10184: 
                   10185: =over 4
                   10186: 
                   10187: =item *
                   10188: 
                   10189: flushcourselogs() : flush (save) buffer logs and access logs
                   10190: 
                   10191: =item *
                   10192: 
                   10193: courselog($what) : save message for course in hash
                   10194: 
                   10195: =item *
                   10196: 
                   10197: courseacclog($what) : save message for course using &courselog().  Perform
                   10198: special processing for specific resource types (problems, exams, quizzes, etc).
                   10199: 
1.191     harris41 10200: =item *
                   10201: 
                   10202: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   10203: as a PerlChildExitHandler
1.243     albertel 10204: 
                   10205: =back
                   10206: 
                   10207: =head2 Other
                   10208: 
                   10209: =over 4
                   10210: 
                   10211: =item *
                   10212: 
                   10213: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 10214: 
                   10215: =back
                   10216: 
                   10217: =cut
1.877     foxr     10218: 

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