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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1009  ! raeburn     4: # $Id: lonnet.pm,v 1.1008 2009/07/31 02:20:17 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;
1.977     amueller   76: use Image::Magick;
                     77: 
1.871     albertel   78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.968     raeburn    79:             $_64bit %env %protocol);
1.871     albertel   80: 
                     81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     82:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     83:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        84:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        85: 
1.1       albertel   86: use IO::Socket;
1.31      www        87: use GDBM_File;
1.208     albertel   88: use HTML::LCParser;
1.88      www        89: use Fcntl qw(:flock);
1.870     albertel   90: use Storable qw(thaw nfreeze);
1.539     albertel   91: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   92: use Cache::Memcached;
1.676     albertel   93: use Digest::MD5;
1.790     albertel   94: use Math::Random;
1.807     albertel   95: use LONCAPA qw(:DEFAULT :match);
1.740     www        96: use LONCAPA::Configuration;
1.676     albertel   97: 
1.195     www        98: my $readit;
1.550     foxr       99: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  100: 
1.977     amueller  101: my $upload_photo_form = 0; #Variable to check  when user upload a photo 0=not 1=true
                    102: 
1.619     albertel  103: require Exporter;
                    104: 
                    105: our @ISA = qw (Exporter);
                    106: our @EXPORT = qw(%env);
                    107: 
1.449     matthew   108: 
1.1       albertel  109: # --------------------------------------------------------------------- Logging
1.729     www       110: {
                    111:     my $logid;
                    112:     sub instructor_log {
1.957     raeburn   113: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    114:         if (($cnum eq '') || ($cdom eq '')) {
                    115:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    116:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    117:         }
1.729     www       118: 	$logid++;
1.957     raeburn   119:         my $now = time();
                    120: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       121: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       122: 				    { $id => {
                    123: 					'exe_uname' => $env{'user.name'},
                    124: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   125: 					'exe_time'  => $now,
1.730     www       126: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    127: 					'delflag'   => $delflag,
                    128: 					'logentry'  => $storehash,
                    129: 					'uname'     => $uname,
                    130: 					'udom'      => $udom,
                    131: 				    }
1.957     raeburn   132: 				  },$cdom,$cnum);
1.729     www       133:     }
                    134: }
1.1       albertel  135: 
1.163     harris41  136: sub logtouch {
                    137:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  138:     unless (-e "$execdir/logs/lonnet.log") {	
                    139: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  140: 	close $fh;
                    141:     }
                    142:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    143:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    144: }
                    145: 
1.1       albertel  146: sub logthis {
                    147:     my $message=shift;
                    148:     my $execdir=$perlvar{'lonDaemons'};
                    149:     my $now=time;
                    150:     my $local=localtime($now);
1.448     albertel  151:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      152: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    153: 	print $fh $logstring;
1.448     albertel  154: 	close($fh);
                    155:     }
1.1       albertel  156:     return 1;
                    157: }
                    158: 
                    159: sub logperm {
                    160:     my $message=shift;
                    161:     my $execdir=$perlvar{'lonDaemons'};
                    162:     my $now=time;
                    163:     my $local=localtime($now);
1.448     albertel  164:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    165: 	print $fh "$now:$message:$local\n";
                    166: 	close($fh);
                    167:     }
1.1       albertel  168:     return 1;
                    169: }
                    170: 
1.850     albertel  171: sub create_connection {
1.853     albertel  172:     my ($hostname,$lonid) = @_;
1.851     albertel  173:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  174: 				     Type    => SOCK_STREAM,
                    175: 				     Timeout => 10);
                    176:     return 0 if (!$client);
1.890     albertel  177:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  178:     my $result = <$client>;
                    179:     chomp($result);
                    180:     return 1 if ($result eq 'done');
                    181:     return 0;
                    182: }
                    183: 
1.983     raeburn   184: sub get_server_timezone {
                    185:     my ($cnum,$cdom) = @_;
                    186:     my $home=&homeserver($cnum,$cdom);
                    187:     if ($home ne 'no_host') {
                    188:         my $cachetime = 24*3600;
                    189:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    190:         if (defined($cached)) {
                    191:             return $timezone;
                    192:         } else {
                    193:             my $timezone = &reply('servertimezone',$home);
                    194:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    195:         }
                    196:     }
                    197: }
1.850     albertel  198: 
1.993     raeburn   199: sub get_server_loncaparev {
                    200:     my ($dom,$lonhost) = @_;
                    201:     if (defined($lonhost)) {
                    202:         if (!defined(&hostname($lonhost))) {
                    203:             undef($lonhost);
                    204:         }
                    205:     }
                    206:     if (!defined($lonhost)) {
                    207:         if (defined(&domain($dom,'primary'))) {
                    208:             $lonhost=&domain($dom,'primary');
                    209:             if ($lonhost eq 'no_host') {
                    210:                 undef($lonhost);
                    211:             }
                    212:         }
                    213:     }
                    214:     if (defined($lonhost)) {
                    215:         my $cachetime = 24*3600;
                    216:         my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    217:         if (defined($cached)) {
                    218:             return $loncaparev;
                    219:         } else {
                    220:             my $loncaparev = &reply('serverloncaparev',$lonhost);
                    221:             return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
                    222:         }
                    223:     }
                    224: }
                    225: 
1.1       albertel  226: # -------------------------------------------------- Non-critical communication
                    227: sub subreply {
                    228:     my ($cmd,$server)=@_;
1.838     albertel  229:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      230:     #
                    231:     #  With loncnew process trimming, there's a timing hole between lonc server
                    232:     #  process exit and the master server picking up the listen on the AF_UNIX
                    233:     #  socket.  In that time interval, a lock file will exist:
                    234: 
                    235:     my $lockfile=$peerfile.".lock";
                    236:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    237: 	sleep(1);
                    238:     }
                    239:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      240:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      241:     #
1.550     foxr      242:     #   We'll give the connection a few tries before abandoning it.  If
                    243:     #   connection is not possible, we'll con_lost back to the client.
                    244:     #   
                    245:     my $client;
                    246:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    247: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    248: 				      Type    => SOCK_STREAM,
                    249: 				      Timeout => 10);
1.869     albertel  250: 	if ($client) {
1.550     foxr      251: 	    last;		# Connected!
1.850     albertel  252: 	} else {
1.853     albertel  253: 	    &create_connection(&hostname($server),$server);
1.550     foxr      254: 	}
1.850     albertel  255:         sleep(1);		# Try again later if failed connection.
1.550     foxr      256:     }
                    257:     my $answer;
                    258:     if ($client) {
1.704     albertel  259: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      260: 	$answer=<$client>;
                    261: 	if (!$answer) { $answer="con_lost"; }
                    262: 	chomp($answer);
                    263:     } else {
                    264: 	$answer = 'con_lost';	# Failed connection.
                    265:     }
1.1       albertel  266:     return $answer;
                    267: }
                    268: 
                    269: sub reply {
                    270:     my ($cmd,$server)=@_;
1.838     albertel  271:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  272:     my $answer=subreply($cmd,$server);
1.65      www       273:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  274:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       275:                 " $cmd to $server returned $answer</font>");
                    276:     }
1.1       albertel  277:     return $answer;
                    278: }
                    279: 
                    280: # ----------------------------------------------------------- Send USR1 to lonc
                    281: 
                    282: sub reconlonc {
1.891     albertel  283:     my ($lonid) = @_;
                    284:     my $hostname = &hostname($lonid);
                    285:     if ($lonid) {
                    286: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    287: 	if ($hostname && -e $peerfile) {
                    288: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    289: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    290: 					     Type    => SOCK_STREAM,
                    291: 					     Timeout => 10);
                    292: 	    if ($client) {
                    293: 		print $client ("reset_retries\n");
                    294: 		my $answer=<$client>;
                    295: 		#reset just this one.
                    296: 	    }
                    297: 	}
                    298: 	return;
                    299:     }
                    300: 
1.836     www       301:     &logthis("Trying to reconnect lonc");
1.1       albertel  302:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  303:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  304: 	my $loncpid=<$fh>;
                    305:         chomp($loncpid);
                    306:         if (kill 0 => $loncpid) {
                    307: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    308:             kill USR1 => $loncpid;
                    309:             sleep 1;
1.836     www       310:          } else {
1.12      www       311: 	    &logthis(
1.672     albertel  312:                "<font color=\"blue\">WARNING:".
1.12      www       313:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  314:         }
                    315:     } else {
1.836     www       316: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  317:     }
                    318: }
                    319: 
                    320: # ------------------------------------------------------ Critical communication
1.12      www       321: 
1.1       albertel  322: sub critical {
                    323:     my ($cmd,$server)=@_;
1.838     albertel  324:     unless (&hostname($server)) {
1.672     albertel  325:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       326:                " Critical message to unknown server ($server)</font>");
                    327:         return 'no_such_host';
                    328:     }
1.1       albertel  329:     my $answer=reply($cmd,$server);
                    330:     if ($answer eq 'con_lost') {
                    331: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  332: 	my $answer=reply($cmd,$server);
1.1       albertel  333:         if ($answer eq 'con_lost') {
                    334:             my $now=time;
                    335:             my $middlename=$cmd;
1.5       www       336:             $middlename=substr($middlename,0,16);
1.1       albertel  337:             $middlename=~s/\W//g;
                    338:             my $dfilename=
1.305     www       339:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    340:             $dumpcount++;
1.1       albertel  341:             {
1.448     albertel  342: 		my $dfh;
                    343: 		if (open($dfh,">$dfilename")) {
                    344: 		    print $dfh "$cmd\n"; 
                    345: 		    close($dfh);
                    346: 		}
1.1       albertel  347:             }
                    348:             sleep 2;
                    349:             my $wcmd='';
                    350:             {
1.448     albertel  351: 		my $dfh;
                    352: 		if (open($dfh,"<$dfilename")) {
                    353: 		    $wcmd=<$dfh>; 
                    354: 		    close($dfh);
                    355: 		}
1.1       albertel  356:             }
                    357:             chomp($wcmd);
1.7       www       358:             if ($wcmd eq $cmd) {
1.672     albertel  359: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       360:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  361:                 &logperm("D:$server:$cmd");
                    362: 	        return 'con_delayed';
                    363:             } else {
1.672     albertel  364:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       365:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  366:                 &logperm("F:$server:$cmd");
                    367:                 return 'con_failed';
                    368:             }
                    369:         }
                    370:     }
                    371:     return $answer;
1.405     albertel  372: }
                    373: 
1.755     albertel  374: # ------------------------------------------- check if return value is an error
                    375: 
                    376: sub error {
                    377:     my ($result) = @_;
1.756     albertel  378:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  379: 	if ($2 == 2) { return undef; }
                    380: 	return $1;
                    381:     }
                    382:     return undef;
                    383: }
                    384: 
1.783     albertel  385: sub convert_and_load_session_env {
                    386:     my ($lonidsdir,$handle)=@_;
                    387:     my @profile;
                    388:     {
1.917     albertel  389: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    390: 	if (!$opened) {
1.915     albertel  391: 	    return 0;
                    392: 	}
1.783     albertel  393: 	flock($idf,LOCK_SH);
                    394: 	@profile=<$idf>;
                    395: 	close($idf);
                    396:     }
                    397:     my %temp_env;
                    398:     foreach my $line (@profile) {
1.786     albertel  399: 	if ($line !~ m/=/) {
                    400: 	    return 0;
                    401: 	}
1.783     albertel  402: 	chomp($line);
                    403: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    404: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    405:     }
                    406:     unlink("$lonidsdir/$handle.id");
                    407:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    408: 	    0640)) {
                    409: 	%disk_env = %temp_env;
                    410: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    411: 	untie(%disk_env);
                    412:     }
1.786     albertel  413:     return 1;
1.783     albertel  414: }
                    415: 
1.374     www       416: # ------------------------------------------- Transfer profile into environment
1.780     albertel  417: my $env_loaded;
                    418: sub transfer_profile_to_env {
1.788     albertel  419:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    420:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       421: 
1.720     albertel  422:     if (!defined($lonidsdir)) {
                    423: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    424:     }
                    425:     if (!defined($handle)) {
                    426:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    427:     }
                    428: 
1.786     albertel  429:     my $convert;
                    430:     {
1.917     albertel  431:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    432: 	if (!$opened) {
1.915     albertel  433: 	    return;
                    434: 	}
1.786     albertel  435: 	flock($idf,LOCK_SH);
                    436: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    437: 		&GDBM_READER(),0640)) {
                    438: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    439: 	    untie(%disk_env);
                    440: 	} else {
                    441: 	    $convert = 1;
                    442: 	}
                    443:     }
                    444:     if ($convert) {
                    445: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    446: 	    &logthis("Failed to load session, or convert session.");
                    447: 	}
1.374     www       448:     }
1.783     albertel  449: 
1.786     albertel  450:     my %remove;
1.783     albertel  451:     while ( my $envname = each(%env) ) {
1.433     matthew   452:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    453:             if ($time < time-300) {
1.783     albertel  454:                 $remove{$key}++;
1.433     matthew   455:             }
                    456:         }
                    457:     }
1.783     albertel  458: 
1.619     albertel  459:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  460:     $env_loaded=1;
1.783     albertel  461:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   462:         &delenv($expired_key);
1.374     www       463:     }
1.1       albertel  464: }
                    465: 
1.916     albertel  466: # ---------------------------------------------------- Check for valid session 
                    467: sub check_for_valid_session {
                    468:     my ($r) = @_;
                    469:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    470:     my $lonid=$cookies{'lonID'};
                    471:     return undef if (!$lonid);
                    472: 
                    473:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    474:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    475:     return undef if (!-e "$lonidsdir/$handle.id");
                    476: 
1.917     albertel  477:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    478:     return undef if (!$opened);
1.916     albertel  479: 
                    480:     flock($idf,LOCK_SH);
                    481:     my %disk_env;
                    482:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    483: 	    &GDBM_READER(),0640)) {
                    484: 	return undef;	
                    485:     }
                    486: 
                    487:     if (!defined($disk_env{'user.name'})
                    488: 	|| !defined($disk_env{'user.domain'})) {
                    489: 	return undef;
                    490:     }
                    491:     return $handle;
                    492: }
                    493: 
1.830     albertel  494: sub timed_flock {
                    495:     my ($file,$lock_type) = @_;
                    496:     my $failed=0;
                    497:     eval {
                    498: 	local $SIG{__DIE__}='DEFAULT';
                    499: 	local $SIG{ALRM}=sub {
                    500: 	    $failed=1;
                    501: 	    die("failed lock");
                    502: 	};
                    503: 	alarm(13);
                    504: 	flock($file,$lock_type);
                    505: 	alarm(0);
                    506:     };
                    507:     if ($failed) {
                    508: 	return undef;
                    509:     } else {
                    510: 	return 1;
                    511:     }
                    512: }
                    513: 
1.5       www       514: # ---------------------------------------------------------- Append Environment
                    515: 
                    516: sub appenv {
1.949     raeburn   517:     my ($newenv,$roles) = @_;
                    518:     if (ref($newenv) eq 'HASH') {
                    519:         foreach my $key (keys(%{$newenv})) {
                    520:             my $refused = 0;
                    521: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    522:                 $refused = 1;
                    523:                 if (ref($roles) eq 'ARRAY') {
                    524:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    525:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    526:                         $refused = 0;
                    527:                     }
                    528:                 }
                    529:             }
                    530:             if ($refused) {
                    531:                 &logthis("<font color=\"blue\">WARNING: ".
                    532:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    533:                          .'</font>');
                    534: 	        delete($newenv->{$key});
                    535:             } else {
                    536:                 $env{$key}=$newenv->{$key};
                    537:             }
                    538:         }
                    539:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    540:         if ($opened
                    541: 	    && &timed_flock($env_file,LOCK_EX)
                    542: 	    &&
                    543: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    544: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    545: 	    while (my ($key,$value) = each(%{$newenv})) {
                    546: 	        $disk_env{$key} = $value;
                    547: 	    }
                    548: 	    untie(%disk_env);
1.35      www       549:         }
1.191     harris41  550:     }
1.56      www       551:     return 'ok';
                    552: }
                    553: # ----------------------------------------------------- Delete from Environment
                    554: 
                    555: sub delenv {
1.987     raeburn   556:     my ($delthis,$regexp) = @_;
1.56      www       557:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  558:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       559:                 "Attempt to delete from environment ".$delthis);
                    560:         return 'error';
                    561:     }
1.917     albertel  562:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    563:     if ($opened
1.915     albertel  564: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  565: 	&&
                    566: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    567: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  568: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   569: 	    if ($regexp) {
                    570:                 if ($key=~/^$delthis/) {
                    571:                     delete($env{$key});
                    572:                     delete($disk_env{$key});
                    573:                 } 
                    574:             } else {
                    575:                 if ($key=~/^\Q$delthis\E/) {
                    576: 		    delete($env{$key});
                    577: 		    delete($disk_env{$key});
                    578: 	        }
                    579:             }
1.448     albertel  580: 	}
1.783     albertel  581: 	untie(%disk_env);
1.5       www       582:     }
                    583:     return 'ok';
1.369     albertel  584: }
                    585: 
1.790     albertel  586: sub get_env_multiple {
                    587:     my ($name) = @_;
                    588:     my @values;
                    589:     if (defined($env{$name})) {
                    590:         # exists is it an array
                    591:         if (ref($env{$name})) {
                    592:             @values=@{ $env{$name} };
                    593:         } else {
                    594:             $values[0]=$env{$name};
                    595:         }
                    596:     }
                    597:     return(@values);
                    598: }
                    599: 
1.958     www       600: # ------------------------------------------------------------------- Locking
                    601: 
                    602: sub set_lock {
                    603:     my ($text)=@_;
                    604:     $locknum++;
                    605:     my $id=$$.'-'.$locknum;
                    606:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    607:              'session.lock.'.$id => $text});
                    608:     return $id;
                    609: }
                    610: 
                    611: sub get_locks {
                    612:     my $num=0;
                    613:     my %texts=();
                    614:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    615:        if ($lock=~/\w/) {
                    616:           $num++;
                    617:           $texts{$lock}=$env{'session.lock.'.$lock};
                    618:        }
                    619:    }
                    620:    return ($num,%texts);
                    621: }
                    622: 
                    623: sub remove_lock {
                    624:     my ($id)=@_;
                    625:     my $newlocks='';
                    626:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    627:        if (($lock=~/\w/) && ($lock ne $id)) {
                    628:           $newlocks.=','.$lock;
                    629:        }
                    630:     }
                    631:     &appenv({'session.locks' => $newlocks});
                    632:     &delenv('session.lock.'.$id);
                    633: }
                    634: 
                    635: sub remove_all_locks {
                    636:     my $activelocks=$env{'session.locks'};
                    637:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    638:        if ($lock=~/\w/) {
                    639:           &remove_lock($lock);
                    640:        }
                    641:     }
                    642: }
                    643: 
                    644: 
1.369     albertel  645: # ------------------------------------------ Find out current server userload
                    646: sub userload {
                    647:     my $numusers=0;
                    648:     {
                    649: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    650: 	my $filename;
                    651: 	my $curtime=time;
                    652: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  653: 	    next if ($filename eq '.' || $filename eq '..');
                    654: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  655: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  656: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  657: 	}
                    658: 	closedir(LONIDS);
                    659:     }
                    660:     my $userloadpercent=0;
                    661:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    662:     if ($maxuserload) {
1.371     albertel  663: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  664:     }
1.372     albertel  665:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  666:     return $userloadpercent;
1.283     www       667: }
                    668: 
                    669: # ------------------------------------------ Fight off request when overloaded
                    670: 
                    671: sub overloaderror {
                    672:     my ($r,$checkserver)=@_;
                    673:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    674:     my $loadavg;
                    675:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  676:        open(my $loadfile,'/proc/loadavg');
1.283     www       677:        $loadavg=<$loadfile>;
                    678:        $loadavg =~ s/\s.*//g;
1.285     matthew   679:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  680:        close($loadfile);
1.283     www       681:     } else {
                    682:        $loadavg=&reply('load',$checkserver);
                    683:     }
1.285     matthew   684:     my $overload=$loadavg-100;
1.283     www       685:     if ($overload>0) {
1.285     matthew   686: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       687:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       688:         return 413;
1.283     www       689:     }    
                    690:     return '';
1.5       www       691: }
1.1       albertel  692: 
                    693: # ------------------------------ Find server with least workload from spare.tab
1.11      www       694: 
1.1       albertel  695: sub spareserver {
1.670     albertel  696:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  697:     my $spare_server;
1.370     albertel  698:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  699:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    700:                                                      :  $userloadpercent;
                    701:     
                    702:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    703: 	($spare_server, $lowest_load) =
                    704: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    705:     }
                    706: 
                    707:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    708: 
                    709:     if (!$found_server) {
                    710: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    711: 	    ($spare_server, $lowest_load) =
                    712: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    713: 	}
                    714:     }
                    715: 
                    716:     if (!$want_server_name) {
1.968     raeburn   717:         my $protocol = 'http';
                    718:         if ($protocol{$spare_server} eq 'https') {
                    719:             $protocol = $protocol{$spare_server};
                    720:         }
1.1001    raeburn   721:         if (defined($spare_server)) {
                    722:             my $hostname = &hostname($spare_server);
                    723:             if (defined($hostname)) {  
                    724: 	        $spare_server = $protocol.'://'.$hostname;
                    725:             }
                    726:         }
1.784     albertel  727:     }
                    728:     return $spare_server;
                    729: }
                    730: 
                    731: sub compare_server_load {
                    732:     my ($try_server, $spare_server, $lowest_load) = @_;
                    733: 
                    734:     my $loadans     = &reply('load',    $try_server);
                    735:     my $userloadans = &reply('userload',$try_server);
                    736: 
                    737:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    738: 	next; #didn't get a number from the server
                    739:     }
                    740: 
                    741:     my $load;
                    742:     if ($loadans =~ /\d/) {
                    743: 	if ($userloadans =~ /\d/) {
                    744: 	    #both are numbers, pick the bigger one
                    745: 	    $load = ($loadans > $userloadans) ? $loadans 
                    746: 		                              : $userloadans;
1.411     albertel  747: 	} else {
1.784     albertel  748: 	    $load = $loadans;
1.411     albertel  749: 	}
1.784     albertel  750:     } else {
                    751: 	$load = $userloadans;
                    752:     }
                    753: 
                    754:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    755: 	$spare_server = $try_server;
                    756: 	$lowest_load  = $load;
1.370     albertel  757:     }
1.784     albertel  758:     return ($spare_server,$lowest_load);
1.202     matthew   759: }
1.914     albertel  760: 
                    761: # --------------------------- ask offload servers if user already has a session
                    762: sub find_existing_session {
                    763:     my ($udom,$uname) = @_;
                    764:     foreach my $try_server (@{ $spareid{'primary'} },
                    765: 			    @{ $spareid{'default'} }) {
                    766: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    767:     }
                    768:     return;
                    769: }
                    770: 
                    771: # -------------------------------- ask if server already has a session for user
                    772: sub has_user_session {
                    773:     my ($lonid,$udom,$uname) = @_;
                    774:     my $result = &reply(join(':','userhassession',
                    775: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    776:     return 1 if ($result eq 'ok');
                    777: 
                    778:     return 0;
                    779: }
                    780: 
1.202     matthew   781: # --------------------------------------------- Try to change a user's password
                    782: 
                    783: sub changepass {
1.799     raeburn   784:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   785:     $currentpass = &escape($currentpass);
                    786:     $newpass     = &escape($newpass);
1.799     raeburn   787:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   788: 		       $server);
                    789:     if (! $answer) {
                    790: 	&logthis("No reply on password change request to $server ".
                    791: 		 "by $uname in domain $udom.");
                    792:     } elsif ($answer =~ "^ok") {
                    793:         &logthis("$uname in $udom successfully changed their password ".
                    794: 		 "on $server.");
                    795:     } elsif ($answer =~ "^pwchange_failure") {
                    796: 	&logthis("$uname in $udom was unable to change their password ".
                    797: 		 "on $server.  The action was blocked by either lcpasswd ".
                    798: 		 "or pwchange");
                    799:     } elsif ($answer =~ "^non_authorized") {
                    800:         &logthis("$uname in $udom did not get their password correct when ".
                    801: 		 "attempting to change it on $server.");
                    802:     } elsif ($answer =~ "^auth_mode_error") {
                    803:         &logthis("$uname in $udom attempted to change their password despite ".
                    804: 		 "not being locally or internally authenticated on $server.");
                    805:     } elsif ($answer =~ "^unknown_user") {
                    806:         &logthis("$uname in $udom attempted to change their password ".
                    807: 		 "on $server but were unable to because $server is not ".
                    808: 		 "their home server.");
                    809:     } elsif ($answer =~ "^refused") {
                    810: 	&logthis("$server refused to change $uname in $udom password because ".
                    811: 		 "it was sent an unencrypted request to change the password.");
                    812:     }
                    813:     return $answer;
1.1       albertel  814: }
                    815: 
1.169     harris41  816: # ----------------------- Try to determine user's current authentication scheme
                    817: 
                    818: sub queryauthenticate {
                    819:     my ($uname,$udom)=@_;
1.456     albertel  820:     my $uhome=&homeserver($uname,$udom);
                    821:     if (!$uhome) {
                    822: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    823: 	return 'no_host';
                    824:     }
                    825:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    826:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    827: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  828:     }
1.456     albertel  829:     return $answer;
1.169     harris41  830: }
                    831: 
1.1       albertel  832: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       833: 
1.1       albertel  834: sub authenticate {
1.952     raeburn   835:     my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807     albertel  836:     $upass=&escape($upass);
                    837:     $uname= &LONCAPA::clean_username($uname);
1.836     www       838:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   839:     my $newhome;
1.836     www       840:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    841: # Maybe the machine was offline and only re-appeared again recently?
                    842:         &reconlonc();
                    843: # One more
1.952     raeburn   844: 	$uhome=&homeserver($uname,$udom,1);
                    845:         if (($uhome eq 'no_host') && $checkdefauth) {
                    846:             if (defined(&domain($udom,'primary'))) {
                    847:                 $newhome=&domain($udom,'primary');
                    848:             }
                    849:             if ($newhome ne '') {
                    850:                 $uhome = $newhome;
                    851:             }
                    852:         }
1.836     www       853: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    854: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   855: 	    return 'no_host';
                    856:         }
1.1       albertel  857:     }
1.952     raeburn   858:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471     albertel  859:     if ($answer eq 'authorized') {
1.952     raeburn   860:         if ($newhome) {
                    861:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    862:             return 'no_account_on_host'; 
                    863:         } else {
                    864:             &logthis("User $uname at $udom authorized by $uhome");
                    865:             return $uhome;
                    866:         }
1.471     albertel  867:     }
                    868:     if ($answer eq 'non_authorized') {
                    869: 	&logthis("User $uname at $udom rejected by $uhome");
                    870: 	return 'no_host'; 
1.9       www       871:     }
1.471     albertel  872:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  873:     return 'no_host';
                    874: }
                    875: 
                    876: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       877: 
1.599     albertel  878: my %homecache;
1.1       albertel  879: sub homeserver {
1.230     stredwic  880:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  881:     my $index="$uname:$udom";
1.426     albertel  882: 
1.599     albertel  883:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  884: 
                    885:     my %servers = &get_servers($udom,'library');
                    886:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  887:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  888: 		 exists($badServerCache{$tryserver}));
1.841     albertel  889: 
                    890: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    891: 	if ($answer eq 'found') {
                    892: 	    delete($badServerCache{$tryserver}); 
                    893: 	    return $homecache{$index}=$tryserver;
                    894: 	} elsif ($answer eq 'no_host') {
                    895: 	    $badServerCache{$tryserver}=1;
                    896: 	}
1.1       albertel  897:     }    
                    898:     return 'no_host';
1.70      www       899: }
                    900: 
                    901: # ------------------------------------- Find the usernames behind a list of IDs
                    902: 
                    903: sub idget {
                    904:     my ($udom,@ids)=@_;
                    905:     my %returnhash=();
                    906:     
1.841     albertel  907:     my %servers = &get_servers($udom,'library');
                    908:     foreach my $tryserver (keys(%servers)) {
                    909: 	my $idlist=join('&',@ids);
                    910: 	$idlist=~tr/A-Z/a-z/; 
                    911: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    912: 	my @answer=();
                    913: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    914: 	    @answer=split(/\&/,$reply);
                    915: 	}                    ;
                    916: 	my $i;
                    917: 	for ($i=0;$i<=$#ids;$i++) {
                    918: 	    if ($answer[$i]) {
                    919: 		$returnhash{$ids[$i]}=$answer[$i];
                    920: 	    } 
                    921: 	}
                    922:     } 
1.70      www       923:     return %returnhash;
                    924: }
                    925: 
                    926: # ------------------------------------- Find the IDs behind a list of usernames
                    927: 
                    928: sub idrget {
                    929:     my ($udom,@unames)=@_;
                    930:     my %returnhash=();
1.800     albertel  931:     foreach my $uname (@unames) {
                    932:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  933:     }
1.70      www       934:     return %returnhash;
                    935: }
                    936: 
                    937: # ------------------------------- Store away a list of names and associated IDs
                    938: 
                    939: sub idput {
                    940:     my ($udom,%ids)=@_;
                    941:     my %servers=();
1.800     albertel  942:     foreach my $uname (keys(%ids)) {
                    943: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    944:         my $uhom=&homeserver($uname,$udom);
1.70      www       945:         if ($uhom ne 'no_host') {
1.800     albertel  946:             my $id=&escape($ids{$uname});
1.70      www       947:             $id=~tr/A-Z/a-z/;
1.800     albertel  948:             my $esc_unam=&escape($uname);
1.70      www       949: 	    if ($servers{$uhom}) {
1.800     albertel  950: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       951:             } else {
1.800     albertel  952:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       953:             }
                    954:         }
1.191     harris41  955:     }
1.800     albertel  956:     foreach my $server (keys(%servers)) {
                    957:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  958:     }
1.344     www       959: }
                    960: 
1.806     raeburn   961: # ------------------------------------------- get items from domain db files   
                    962: 
                    963: sub get_dom {
1.860     raeburn   964:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   965:     my $items='';
                    966:     foreach my $item (@$storearr) {
                    967:         $items.=&escape($item).'&';
                    968:     }
                    969:     $items=~s/\&$//;
1.860     raeburn   970:     if (!$udom) {
                    971:         $udom=$env{'user.domain'};
                    972:         if (defined(&domain($udom,'primary'))) {
                    973:             $uhome=&domain($udom,'primary');
                    974:         } else {
1.874     albertel  975:             undef($uhome);
1.860     raeburn   976:         }
                    977:     } else {
                    978:         if (!$uhome) {
                    979:             if (defined(&domain($udom,'primary'))) {
                    980:                 $uhome=&domain($udom,'primary');
                    981:             }
                    982:         }
                    983:     }
                    984:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   985:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn   986:         my %returnhash;
1.875     albertel  987:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn   988:             return %returnhash;
                    989:         }
1.806     raeburn   990:         my @pairs=split(/\&/,$rep);
                    991:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    992:             return @pairs;
                    993:         }
                    994:         my $i=0;
                    995:         foreach my $item (@$storearr) {
                    996:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    997:             $i++;
                    998:         }
                    999:         return %returnhash;
                   1000:     } else {
1.880     banghart 1001:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1002:     }
                   1003: }
                   1004: 
                   1005: # -------------------------------------------- put items in domain db files 
                   1006: 
                   1007: sub put_dom {
1.860     raeburn  1008:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1009:     if (!$udom) {
                   1010:         $udom=$env{'user.domain'};
                   1011:         if (defined(&domain($udom,'primary'))) {
                   1012:             $uhome=&domain($udom,'primary');
                   1013:         } else {
1.874     albertel 1014:             undef($uhome);
1.860     raeburn  1015:         }
                   1016:     } else {
                   1017:         if (!$uhome) {
                   1018:             if (defined(&domain($udom,'primary'))) {
                   1019:                 $uhome=&domain($udom,'primary');
                   1020:             }
                   1021:         }
                   1022:     } 
                   1023:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1024:         my $items='';
                   1025:         foreach my $item (keys(%$storehash)) {
                   1026:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1027:         }
                   1028:         $items=~s/\&$//;
                   1029:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1030:     } else {
1.860     raeburn  1031:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1032:     }
                   1033: }
                   1034: 
1.837     raeburn  1035: sub retrieve_inst_usertypes {
                   1036:     my ($udom) = @_;
                   1037:     my (%returnhash,@order);
1.989     raeburn  1038:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1039:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1040:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1041:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1042:         @order = @{$domdefs{'inststatusorder'}};
                   1043:     } else {
                   1044:         if (defined(&domain($udom,'primary'))) {
                   1045:             my $uhome=&domain($udom,'primary');
                   1046:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1047:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1048:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1049:                 return (\%returnhash,\@order);
                   1050:             }
                   1051:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1052:             my @pairs=split(/\&/,$hashitems);
                   1053:             foreach my $item (@pairs) {
                   1054:                 my ($key,$value)=split(/=/,$item,2);
                   1055:                 $key = &unescape($key);
                   1056:                 next if ($key =~ /^error: 2 /);
                   1057:                 $returnhash{$key}=&thaw_unescape($value);
                   1058:             }
                   1059:             my @esc_order = split(/\&/,$orderitems);
                   1060:             foreach my $item (@esc_order) {
                   1061:                 push(@order,&unescape($item));
                   1062:             }
                   1063:         } else {
                   1064:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1065:         }
                   1066:     }
                   1067:     return (\%returnhash,\@order);
                   1068: }
                   1069: 
1.868     raeburn  1070: sub is_domainimage {
                   1071:     my ($url) = @_;
                   1072:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1073:         if (&domain($1) ne '') {
                   1074:             return '1';
                   1075:         }
                   1076:     }
                   1077:     return;
                   1078: }
                   1079: 
1.899     raeburn  1080: sub inst_directory_query {
                   1081:     my ($srch) = @_;
                   1082:     my $udom = $srch->{'srchdomain'};
                   1083:     my %results;
                   1084:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1085:     my $outcome;
1.899     raeburn  1086:     if ($homeserver ne '') {
1.904     albertel 1087: 	my $queryid=&reply("querysend:instdirsearch:".
                   1088: 			   &escape($srch->{'srchby'}).':'.
                   1089: 			   &escape($srch->{'srchterm'}).':'.
                   1090: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1091: 	my $host=&hostname($homeserver);
                   1092: 	if ($queryid !~/^\Q$host\E\_/) {
                   1093: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1094: 	    return;
                   1095: 	}
                   1096: 	my $response = &get_query_reply($queryid);
                   1097: 	my $maxtries = 5;
                   1098: 	my $tries = 1;
                   1099: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1100: 	    $response = &get_query_reply($queryid);
                   1101: 	    $tries ++;
                   1102: 	}
                   1103: 
                   1104:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1105:             if ($response eq 'unavailable') {
                   1106:                 $outcome = $response;
                   1107:             } else {
                   1108:                 $outcome = 'ok';
                   1109:                 my @matches = split(/\n/,$response);
                   1110:                 foreach my $match (@matches) {
                   1111:                     my ($key,$value) = split(/=/,$match);
                   1112:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1113:                 }
1.899     raeburn  1114:             }
                   1115:         }
                   1116:     }
1.909     raeburn  1117:     return ($outcome,%results);
1.899     raeburn  1118: }
                   1119: 
                   1120: sub usersearch {
                   1121:     my ($srch) = @_;
                   1122:     my $dom = $srch->{'srchdomain'};
                   1123:     my %results;
                   1124:     my %libserv = &all_library();
                   1125:     my $query = 'usersearch';
                   1126:     foreach my $tryserver (keys(%libserv)) {
                   1127:         if (&host_domain($tryserver) eq $dom) {
                   1128:             my $host=&hostname($tryserver);
                   1129:             my $queryid=
1.911     raeburn  1130:                 &reply("querysend:".&escape($query).':'.
                   1131:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1132:                        &escape($srch->{'srchtype'}).':'.
                   1133:                        &escape($srch->{'srchterm'}),$tryserver);
                   1134:             if ($queryid !~/^\Q$host\E\_/) {
                   1135:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1136:                 next;
1.899     raeburn  1137:             }
                   1138:             my $reply = &get_query_reply($queryid);
                   1139:             my $maxtries = 1;
                   1140:             my $tries = 1;
                   1141:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1142:                 $reply = &get_query_reply($queryid);
                   1143:                 $tries ++;
                   1144:             }
                   1145:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1146:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1147:             } else {
1.911     raeburn  1148:                 my @matches;
                   1149:                 if ($reply =~ /\n/) {
                   1150:                     @matches = split(/\n/,$reply);
                   1151:                 } else {
                   1152:                     @matches = split(/\&/,$reply);
                   1153:                 }
1.899     raeburn  1154:                 foreach my $match (@matches) {
                   1155:                     my ($uname,$udom,%userhash);
1.911     raeburn  1156:                     foreach my $entry (split(/:/,$match)) {
                   1157:                         my ($key,$value) =
                   1158:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1159:                         $userhash{$key} = $value;
                   1160:                         if ($key eq 'username') {
                   1161:                             $uname = $value;
                   1162:                         } elsif ($key eq 'domain') {
                   1163:                             $udom = $value;
1.911     raeburn  1164:                         }
1.899     raeburn  1165:                     }
                   1166:                     $results{$uname.':'.$udom} = \%userhash;
                   1167:                 }
                   1168:             }
                   1169:         }
                   1170:     }
                   1171:     return %results;
                   1172: }
                   1173: 
1.912     raeburn  1174: sub get_instuser {
                   1175:     my ($udom,$uname,$id) = @_;
                   1176:     my $homeserver = &domain($udom,'primary');
                   1177:     my ($outcome,%results);
                   1178:     if ($homeserver ne '') {
                   1179:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1180:                            &escape($id).':'.&escape($udom),$homeserver);
                   1181:         my $host=&hostname($homeserver);
                   1182:         if ($queryid !~/^\Q$host\E\_/) {
                   1183:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1184:             return;
                   1185:         }
                   1186:         my $response = &get_query_reply($queryid);
                   1187:         my $maxtries = 5;
                   1188:         my $tries = 1;
                   1189:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1190:             $response = &get_query_reply($queryid);
                   1191:             $tries ++;
                   1192:         }
                   1193:         if (!&error($response) && $response ne 'refused') {
                   1194:             if ($response eq 'unavailable') {
                   1195:                 $outcome = $response;
                   1196:             } else {
                   1197:                 $outcome = 'ok';
                   1198:                 my @matches = split(/\n/,$response);
                   1199:                 foreach my $match (@matches) {
                   1200:                     my ($key,$value) = split(/=/,$match);
                   1201:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1202:                 }
                   1203:             }
                   1204:         }
                   1205:     }
                   1206:     my %userinfo;
                   1207:     if (ref($results{$uname}) eq 'HASH') {
                   1208:         %userinfo = %{$results{$uname}};
                   1209:     } 
                   1210:     return ($outcome,%userinfo);
                   1211: }
                   1212: 
                   1213: sub inst_rulecheck {
1.923     raeburn  1214:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1215:     my %returnhash;
                   1216:     if ($udom ne '') {
                   1217:         if (ref($rules) eq 'ARRAY') {
                   1218:             @{$rules} = map {&escape($_);} (@{$rules});
                   1219:             my $rulestr = join(':',@{$rules});
                   1220:             my $homeserver=&domain($udom,'primary');
                   1221:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1222:                 my $response;
                   1223:                 if ($item eq 'username') {                
                   1224:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1225:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1226:                                               $homeserver));
1.923     raeburn  1227:                 } elsif ($item eq 'id') {
                   1228:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1229:                                               ':'.&escape($id).':'.$rulestr,
                   1230:                                               $homeserver));
1.945     raeburn  1231:                 } elsif ($item eq 'selfcreate') {
                   1232:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1233:                                                &escape($udom).':'.&escape($uname).
                   1234:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1235:                 }
1.912     raeburn  1236:                 if ($response ne 'refused') {
                   1237:                     my @pairs=split(/\&/,$response);
                   1238:                     foreach my $item (@pairs) {
                   1239:                         my ($key,$value)=split(/=/,$item,2);
                   1240:                         $key = &unescape($key);
                   1241:                         next if ($key =~ /^error: 2 /);
                   1242:                         $returnhash{$key}=&thaw_unescape($value);
                   1243:                     }
                   1244:                 }
                   1245:             }
                   1246:         }
                   1247:     }
                   1248:     return %returnhash;
                   1249: }
                   1250: 
                   1251: sub inst_userrules {
1.923     raeburn  1252:     my ($udom,$check) = @_;
1.912     raeburn  1253:     my (%ruleshash,@ruleorder);
                   1254:     if ($udom ne '') {
                   1255:         my $homeserver=&domain($udom,'primary');
                   1256:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1257:             my $response;
                   1258:             if ($check eq 'id') {
                   1259:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1260:                                  $homeserver);
1.943     raeburn  1261:             } elsif ($check eq 'email') {
                   1262:                 $response=&reply('instemailrules:'.&escape($udom),
                   1263:                                  $homeserver);
1.923     raeburn  1264:             } else {
                   1265:                 $response=&reply('instuserrules:'.&escape($udom),
                   1266:                                  $homeserver);
                   1267:             }
1.912     raeburn  1268:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1269:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1270:                 ($response ne 'no_such_host')) {
                   1271:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1272:                 my @pairs=split(/\&/,$hashitems);
                   1273:                 foreach my $item (@pairs) {
                   1274:                     my ($key,$value)=split(/=/,$item,2);
                   1275:                     $key = &unescape($key);
                   1276:                     next if ($key =~ /^error: 2 /);
                   1277:                     $ruleshash{$key}=&thaw_unescape($value);
                   1278:                 }
                   1279:                 my @esc_order = split(/\&/,$orderitems);
                   1280:                 foreach my $item (@esc_order) {
                   1281:                     push(@ruleorder,&unescape($item));
                   1282:                 }
                   1283:             }
                   1284:         }
                   1285:     }
                   1286:     return (\%ruleshash,\@ruleorder);
                   1287: }
                   1288: 
1.976     raeburn  1289: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1290: 
                   1291: sub get_domain_defaults {
                   1292:     my ($domain) = @_;
                   1293:     my $cachetime = 60*60*24;
                   1294:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1295:     if (defined($cached)) {
                   1296:         if (ref($result) eq 'HASH') {
                   1297:             return %{$result};
                   1298:         }
                   1299:     }
                   1300:     my %domdefaults;
                   1301:     my %domconfig =
1.989     raeburn  1302:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
                   1303:                                   'requestcourses','inststatus'],$domain);
1.943     raeburn  1304:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1305:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1306:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1307:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1308:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1309:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1310:     } else {
                   1311:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1312:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1313:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1314:     }
1.976     raeburn  1315:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1316:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1317:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1318:         } else {
                   1319:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1320:         } 
                   1321:         my @usertools = ('aboutme','blog','portfolio');
                   1322:         foreach my $item (@usertools) {
                   1323:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1324:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1325:             }
                   1326:         }
                   1327:     }
1.985     raeburn  1328:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1329:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1330:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1331:         }
                   1332:     }
1.989     raeburn  1333:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1334:         foreach my $item ('inststatustypes','inststatusorder') {
                   1335:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1336:         }
                   1337:     }
1.943     raeburn  1338:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1339:                                   $cachetime);
                   1340:     return %domdefaults;
                   1341: }
                   1342: 
1.344     www      1343: # --------------------------------------------------- Assign a key to a student
                   1344: 
                   1345: sub assign_access_key {
1.364     www      1346: #
                   1347: # a valid key looks like uname:udom#comments
                   1348: # comments are being appended
                   1349: #
1.498     www      1350:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1351:     $kdom=
1.620     albertel 1352:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1353:     $knum=
1.620     albertel 1354:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1355:     $cdom=
1.620     albertel 1356:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1357:     $cnum=
1.620     albertel 1358:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1359:     $udom=$env{'user.name'} unless (defined($udom));
                   1360:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1361:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1362:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1363:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1364:                                                   # assigned to this person
                   1365:                                                   # - this should not happen,
1.345     www      1366:                                                   # unless something went wrong
                   1367:                                                   # the first time around
                   1368: # ready to assign
1.364     www      1369:         $logentry=$1.'; '.$logentry;
1.496     www      1370:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1371:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1372: # key now belongs to user
1.346     www      1373: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1374:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1375:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1376:                 return 'ok';
                   1377:             } else {
                   1378:                 return 
                   1379:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1380: 	    }
                   1381:         } else {
                   1382:             return 'error: Could not assign key, try again later.';
                   1383:         }
1.364     www      1384:     } elsif (!$existing{$ckey}) {
1.345     www      1385: # the key does not exist
                   1386: 	return 'error: The key does not exist';
                   1387:     } else {
                   1388: # the key is somebody else's
                   1389: 	return 'error: The key is already in use';
                   1390:     }
1.344     www      1391: }
                   1392: 
1.364     www      1393: # ------------------------------------------ put an additional comment on a key
                   1394: 
                   1395: sub comment_access_key {
                   1396: #
                   1397: # a valid key looks like uname:udom#comments
                   1398: # comments are being appended
                   1399: #
                   1400:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1401:     $cdom=
1.620     albertel 1402:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1403:     $cnum=
1.620     albertel 1404:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1405:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1406:     if ($existing{$ckey}) {
                   1407:         $existing{$ckey}.='; '.$logentry;
                   1408: # ready to assign
1.367     www      1409:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1410:                                                  $cdom,$cnum) eq 'ok') {
                   1411: 	    return 'ok';
                   1412:         } else {
                   1413: 	    return 'error: Count not store comment.';
                   1414:         }
                   1415:     } else {
                   1416: # the key does not exist
                   1417: 	return 'error: The key does not exist';
                   1418:     }
                   1419: }
                   1420: 
1.344     www      1421: # ------------------------------------------------------ Generate a set of keys
                   1422: 
                   1423: sub generate_access_keys {
1.364     www      1424:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1425:     $cdom=
1.620     albertel 1426:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1427:     $cnum=
1.620     albertel 1428:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1429:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1430:     unless (($cdom) && ($cnum)) { return 0; }
                   1431:     if ($number>10000) { return 0; }
                   1432:     sleep(2); # make sure don't get same seed twice
                   1433:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1434:     my $total=0;
                   1435:     for (my $i=1;$i<=$number;$i++) {
                   1436:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1437:                   sprintf("%lx",int(100000*rand)).'-'.
                   1438:                   sprintf("%lx",int(100000*rand));
                   1439:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1440:        $newkey=~s/0/h/g; # and also 0 and O
                   1441:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1442:        if ($existing{$newkey}) {
                   1443:            $i--;
                   1444:        } else {
1.364     www      1445: 	  if (&put('accesskeys',
                   1446:               { $newkey => '# generated '.localtime().
1.620     albertel 1447:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1448:                            '; '.$logentry },
                   1449: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1450:               $total++;
                   1451: 	  }
                   1452:        }
                   1453:     }
1.620     albertel 1454:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1455:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1456:     return $total;
                   1457: }
                   1458: 
                   1459: # ------------------------------------------------------- Validate an accesskey
                   1460: 
                   1461: sub validate_access_key {
                   1462:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1463:     $cdom=
1.620     albertel 1464:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1465:     $cnum=
1.620     albertel 1466:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1467:     $udom=$env{'user.domain'} unless (defined($udom));
                   1468:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1469:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1470:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1471: }
                   1472: 
                   1473: # ------------------------------------- Find the section of student in a course
1.652     albertel 1474: sub devalidate_getsection_cache {
                   1475:     my ($udom,$unam,$courseid)=@_;
                   1476:     my $hashid="$udom:$unam:$courseid";
                   1477:     &devalidate_cache_new('getsection',$hashid);
                   1478: }
1.298     matthew  1479: 
1.815     albertel 1480: sub courseid_to_courseurl {
                   1481:     my ($courseid) = @_;
                   1482:     #already url style courseid
                   1483:     return $courseid if ($courseid =~ m{^/});
                   1484: 
                   1485:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1486: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1487: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1488: 	return "/$cdom/$cnum";
                   1489:     }
                   1490: 
                   1491:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1492:     if (exists($courseinfo{'num'})) {
                   1493: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1494:     }
                   1495: 
                   1496:     return undef;
                   1497: }
                   1498: 
1.298     matthew  1499: sub getsection {
                   1500:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1501:     my $cachetime=1800;
1.551     albertel 1502: 
                   1503:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1504:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1505:     if (defined($cached)) { return $result; }
                   1506: 
1.298     matthew  1507:     my %Pending; 
                   1508:     my %Expired;
                   1509:     #
                   1510:     # Each role can either have not started yet (pending), be active, 
                   1511:     #    or have expired.
                   1512:     #
                   1513:     # If there is an active role, we are done.
                   1514:     #
                   1515:     # If there is more than one role which has not started yet, 
                   1516:     #     choose the one which will start sooner
                   1517:     # If there is one role which has not started yet, return it.
                   1518:     #
                   1519:     # If there is more than one expired role, choose the one which ended last.
                   1520:     # If there is a role which has expired, return it.
                   1521:     #
1.815     albertel 1522:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1523:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1524:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1525:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1526:         my $section=$1;
                   1527:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1528:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1529:         my $now=time;
1.548     albertel 1530:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1531:             $Expired{$end}=$section;
                   1532:             next;
                   1533:         }
1.548     albertel 1534:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1535:             $Pending{$start}=$section;
                   1536:             next;
                   1537:         }
1.599     albertel 1538:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1539:     }
                   1540:     #
                   1541:     # Presumedly there will be few matching roles from the above
                   1542:     # loop and the sorting time will be negligible.
                   1543:     if (scalar(keys(%Pending))) {
                   1544:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1545:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1546:     } 
                   1547:     if (scalar(keys(%Expired))) {
                   1548:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1549:         my $time = pop(@sorted);
1.599     albertel 1550:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1551:     }
1.599     albertel 1552:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1553: }
1.70      www      1554: 
1.599     albertel 1555: sub save_cache {
                   1556:     &purge_remembered();
1.722     albertel 1557:     #&Apache::loncommon::validate_page();
1.620     albertel 1558:     undef(%env);
1.780     albertel 1559:     undef($env_loaded);
1.599     albertel 1560: }
1.452     albertel 1561: 
1.599     albertel 1562: my $to_remember=-1;
                   1563: my %remembered;
                   1564: my %accessed;
                   1565: my $kicks=0;
                   1566: my $hits=0;
1.849     albertel 1567: sub make_key {
                   1568:     my ($name,$id) = @_;
1.872     albertel 1569:     if (length($id) > 65 
                   1570: 	&& length(&escape($id)) > 200) {
                   1571: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1572:     }
1.849     albertel 1573:     return &escape($name.':'.$id);
                   1574: }
                   1575: 
1.599     albertel 1576: sub devalidate_cache_new {
                   1577:     my ($name,$id,$debug) = @_;
                   1578:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1579:     $id=&make_key($name,$id);
1.599     albertel 1580:     $memcache->delete($id);
                   1581:     delete($remembered{$id});
                   1582:     delete($accessed{$id});
                   1583: }
                   1584: 
                   1585: sub is_cached_new {
                   1586:     my ($name,$id,$debug) = @_;
1.849     albertel 1587:     $id=&make_key($name,$id);
1.599     albertel 1588:     if (exists($remembered{$id})) {
                   1589: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1590: 	$accessed{$id}=[&gettimeofday()];
                   1591: 	$hits++;
                   1592: 	return ($remembered{$id},1);
                   1593:     }
                   1594:     my $value = $memcache->get($id);
                   1595:     if (!(defined($value))) {
                   1596: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1597: 	return (undef,undef);
1.416     albertel 1598:     }
1.599     albertel 1599:     if ($value eq '__undef__') {
                   1600: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1601: 	$value=undef;
                   1602:     }
                   1603:     &make_room($id,$value,$debug);
                   1604:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1605:     return ($value,1);
                   1606: }
                   1607: 
                   1608: sub do_cache_new {
                   1609:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1610:     $id=&make_key($name,$id);
1.599     albertel 1611:     my $setvalue=$value;
                   1612:     if (!defined($setvalue)) {
                   1613: 	$setvalue='__undef__';
                   1614:     }
1.623     albertel 1615:     if (!defined($time) ) {
                   1616: 	$time=600;
                   1617:     }
1.599     albertel 1618:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1619:     my $result = $memcache->set($id,$setvalue,$time);
                   1620:     if (! $result) {
1.872     albertel 1621: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1622: 	$memcache->disconnect_all();
1.872     albertel 1623:     }
1.600     albertel 1624:     # need to make a copy of $value
1.919     albertel 1625:     &make_room($id,$value,$debug);
1.599     albertel 1626:     return $value;
                   1627: }
                   1628: 
                   1629: sub make_room {
                   1630:     my ($id,$value,$debug)=@_;
1.919     albertel 1631: 
                   1632:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1633:                                     : $value;
1.599     albertel 1634:     if ($to_remember<0) { return; }
                   1635:     $accessed{$id}=[&gettimeofday()];
                   1636:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1637:     my $to_kick;
                   1638:     my $max_time=0;
                   1639:     foreach my $other (keys(%accessed)) {
                   1640: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1641: 	    $to_kick=$other;
                   1642: 	    $max_time=&tv_interval($accessed{$other});
                   1643: 	}
                   1644:     }
                   1645:     delete($remembered{$to_kick});
                   1646:     delete($accessed{$to_kick});
                   1647:     $kicks++;
                   1648:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1649:     return;
                   1650: }
                   1651: 
1.599     albertel 1652: sub purge_remembered {
1.604     albertel 1653:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1654:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1655:     undef(%remembered);
                   1656:     undef(%accessed);
1.428     albertel 1657: }
1.70      www      1658: # ------------------------------------- Read an entry from a user's environment
                   1659: 
                   1660: sub userenvironment {
                   1661:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1662:     my $items;
                   1663:     foreach my $item (@what) {
                   1664:         $items.=&escape($item).'&';
                   1665:     }
                   1666:     $items=~s/\&$//;
1.70      www      1667:     my %returnhash=();
1.1009  ! raeburn  1668:     my $uhome = &homeserver($unam,$udom);
        !          1669:     unless ($uhome eq 'no_host') {
        !          1670:         my @answer=split(/\&/, 
        !          1671:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
        !          1672:         my $i;
        !          1673:         for ($i=0;$i<=$#what;$i++) {
        !          1674: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
        !          1675:         }
1.70      www      1676:     }
                   1677:     return %returnhash;
1.1       albertel 1678: }
                   1679: 
1.617     albertel 1680: # ---------------------------------------------------------- Get a studentphoto
                   1681: sub studentphoto {
                   1682:     my ($udom,$unam,$ext) = @_;
                   1683:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1684:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1685:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1686:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1687:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1688:             } else {
                   1689:                 my ($result,$perm_reqd)=
1.707     albertel 1690: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1691:                 if ($result eq 'ok') {
                   1692:                     if (!($perm_reqd eq 'yes')) {
                   1693:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1694:                     }
                   1695:                 }
                   1696:             }
                   1697:         }
                   1698:     } else {
                   1699:         my ($result,$perm_reqd) = 
1.707     albertel 1700: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1701:         if ($result eq 'ok') {
                   1702:             if (!($perm_reqd eq 'yes')) {
                   1703:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1704:             }
                   1705:         }
                   1706:     }
                   1707:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1708: }
                   1709: 
                   1710: sub retrievestudentphoto {
                   1711:     my ($udom,$unam,$ext,$type) = @_;
                   1712:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1713:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1714:     if ($ret eq 'ok') {
                   1715:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1716:         if ($type eq 'thumbnail') {
                   1717:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1718:         }
                   1719:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1720:         return $tokenurl;
                   1721:     } else {
                   1722:         if ($type eq 'thumbnail') {
                   1723:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1724:         } else { 
                   1725:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1726:         }
1.617     albertel 1727:     }
                   1728: }
                   1729: 
1.263     www      1730: # -------------------------------------------------------------------- New chat
                   1731: 
                   1732: sub chatsend {
1.724     raeburn  1733:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1734:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1735:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1736:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1737:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1738: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1739: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1740: }
                   1741: 
                   1742: # ------------------------------------------ Find current version of a resource
                   1743: 
                   1744: sub getversion {
                   1745:     my $fname=&clutter(shift);
                   1746:     unless ($fname=~/^\/res\//) { return -1; }
                   1747:     return &currentversion(&filelocation('',$fname));
                   1748: }
                   1749: 
                   1750: sub currentversion {
                   1751:     my $fname=shift;
1.599     albertel 1752:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1753:     if (defined($cached)) { return $result; }
1.292     www      1754:     my $author=$fname;
                   1755:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1756:     my ($udom,$uname)=split(/\//,$author);
                   1757:     my $home=homeserver($uname,$udom);
                   1758:     if ($home eq 'no_host') { 
                   1759:         return -1; 
                   1760:     }
                   1761:     my $answer=reply("currentversion:$fname",$home);
                   1762:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1763: 	return -1;
                   1764:     }
1.599     albertel 1765:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1766: }
                   1767: 
1.1       albertel 1768: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1769: 
1.1       albertel 1770: sub subscribe {
                   1771:     my $fname=shift;
1.761     raeburn  1772:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1773:     $fname=~s/[\n\r]//g;
1.1       albertel 1774:     my $author=$fname;
                   1775:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1776:     my ($udom,$uname)=split(/\//,$author);
                   1777:     my $home=homeserver($uname,$udom);
1.335     albertel 1778:     if ($home eq 'no_host') {
                   1779:         return 'not_found';
1.1       albertel 1780:     }
                   1781:     my $answer=reply("sub:$fname",$home);
1.64      www      1782:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1783: 	$answer.=' by '.$home;
                   1784:     }
1.1       albertel 1785:     return $answer;
                   1786: }
                   1787:     
1.8       www      1788: # -------------------------------------------------------------- Replicate file
                   1789: 
                   1790: sub repcopy {
                   1791:     my $filename=shift;
1.23      www      1792:     $filename=~s/\/+/\//g;
1.607     raeburn  1793:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1794:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1795:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1796: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1797: 	return &repcopy_userfile($filename);
                   1798:     }
1.532     albertel 1799:     $filename=~s/[\n\r]//g;
1.8       www      1800:     my $transname="$filename.in.transfer";
1.828     www      1801: # FIXME: this should flock
1.607     raeburn  1802:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1803:     my $remoteurl=subscribe($filename);
1.64      www      1804:     if ($remoteurl =~ /^con_lost by/) {
                   1805: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1806:            return 'unavailable';
1.8       www      1807:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1808: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1809: 	   return 'not_found';
1.64      www      1810:     } elsif ($remoteurl =~ /^rejected by/) {
                   1811: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1812:            return 'forbidden';
1.20      www      1813:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1814:            return 'ok';
1.8       www      1815:     } else {
1.290     www      1816:         my $author=$filename;
                   1817:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1818:         my ($udom,$uname)=split(/\//,$author);
                   1819:         my $home=homeserver($uname,$udom);
                   1820:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1821:            my @parts=split(/\//,$filename);
                   1822:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1823:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1824:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1825: 	       return 'bad_request';
1.8       www      1826:            }
                   1827:            my $count;
                   1828:            for ($count=5;$count<$#parts;$count++) {
                   1829:                $path.="/$parts[$count]";
                   1830:                if ((-e $path)!=1) {
                   1831: 		   mkdir($path,0777);
                   1832:                }
                   1833:            }
                   1834:            my $ua=new LWP::UserAgent;
                   1835:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1836:            my $response=$ua->request($request,$transname);
                   1837:            if ($response->is_error()) {
                   1838: 	       unlink($transname);
                   1839:                my $message=$response->status_line;
1.672     albertel 1840:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1841:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1842:                return 'unavailable';
1.8       www      1843:            } else {
1.16      www      1844: 	       if ($remoteurl!~/\.meta$/) {
                   1845:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1846:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1847:                   if ($mresponse->is_error()) {
                   1848: 		      unlink($filename.'.meta');
                   1849:                       &logthis(
1.672     albertel 1850:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1851:                   }
                   1852: 	       }
1.8       www      1853:                rename($transname,$filename);
1.607     raeburn  1854:                return 'ok';
1.8       www      1855:            }
1.290     www      1856:        }
1.8       www      1857:     }
1.330     www      1858: }
                   1859: 
                   1860: # ------------------------------------------------ Get server side include body
                   1861: sub ssi_body {
1.381     albertel 1862:     my ($filelink,%form)=@_;
1.606     matthew  1863:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1864:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1865:     }
1.953     www      1866:     my $output='';
                   1867:     my $response;
1.980     raeburn  1868:     if ($filelink=~/^https?\:/) {
1.954     raeburn  1869:        ($output,$response)=&externalssi($filelink);
1.953     www      1870:     } else {
1.1004    droeschl 1871:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   1872:        $filelink .= 'inhibitmenu=yes';
1.953     www      1873:        ($output,$response)=&ssi($filelink,%form);
                   1874:     }
1.778     albertel 1875:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1876:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 1877:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      1878:     if (wantarray) {
                   1879:         return ($output, $response);
                   1880:     } else {
                   1881:         return $output;
                   1882:     }
1.8       www      1883: }
                   1884: 
1.15      www      1885: # --------------------------------------------------------- Server Side Include
                   1886: 
1.782     albertel 1887: sub absolute_url {
                   1888:     my ($host_name) = @_;
                   1889:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1890:     if ($host_name eq '') {
                   1891: 	$host_name = $ENV{'SERVER_NAME'};
                   1892:     }
                   1893:     return $protocol.$host_name;
                   1894: }
                   1895: 
1.942     foxr     1896: #
                   1897: #   Server side include.
                   1898: # Parameters:
                   1899: #  fn     Possibly encrypted resource name/id.
                   1900: #  form   Hash that describes how the rendering should be done
                   1901: #         and other things.
1.944     foxr     1902: # Returns:
1.950     raeburn  1903: #   Scalar context: The content of the response.
                   1904: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     1905: #     
1.15      www      1906: sub ssi {
                   1907: 
1.944     foxr     1908:     my ($fn,%form)=@_;
1.15      www      1909:     my $ua=new LWP::UserAgent;
1.23      www      1910:     my $request;
1.711     albertel 1911: 
                   1912:     $form{'no_update_last_known'}=1;
1.895     albertel 1913:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1914:     if (%form) {
1.782     albertel 1915:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  1916:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      1917:     } else {
1.782     albertel 1918:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1919:     }
                   1920: 
1.15      www      1921:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1922:     my $response=$ua->request($request);
                   1923: 
1.944     foxr     1924:     if (wantarray) {
                   1925: 	return ($response->content, $response);
                   1926:     } else {
                   1927: 	return $response->content;
1.942     foxr     1928:     }
1.324     www      1929: }
                   1930: 
                   1931: sub externalssi {
                   1932:     my ($url)=@_;
                   1933:     my $ua=new LWP::UserAgent;
                   1934:     my $request=new HTTP::Request('GET',$url);
                   1935:     my $response=$ua->request($request);
1.954     raeburn  1936:     if (wantarray) {
                   1937:         return ($response->content, $response);
                   1938:     } else {
                   1939:         return $response->content;
                   1940:     }
1.15      www      1941: }
1.254     www      1942: 
1.492     albertel 1943: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1944: 
                   1945: sub allowuploaded {
                   1946:     my ($srcurl,$url)=@_;
                   1947:     $url=&clutter(&declutter($url));
                   1948:     my $dir=$url;
                   1949:     $dir=~s/\/[^\/]+$//;
                   1950:     my %httpref=();
                   1951:     my $httpurl=&hreflocation('',$url);
                   1952:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  1953:     &Apache::lonnet::appenv(\%httpref);
1.254     www      1954: }
1.477     raeburn  1955: 
1.478     albertel 1956: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1957: # input: action, courseID, current domain, intended
1.637     raeburn  1958: #        path to file, source of file, instruction to parse file for objects,
                   1959: #        ref to hash for embedded objects,
                   1960: #        ref to hash for codebase of java objects.
                   1961: #
1.485     raeburn  1962: # output: url to file (if action was uploaddoc), 
                   1963: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1964: #
1.478     albertel 1965: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1966: # course.
1.477     raeburn  1967: #
1.478     albertel 1968: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1969: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1970: #          course's home server.
1.477     raeburn  1971: #
1.478     albertel 1972: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1973: #          be copied from $source (current location) to 
                   1974: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1975: #         and will then be copied to
                   1976: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1977: #         course's home server.
1.485     raeburn  1978: #
1.481     raeburn  1979: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1980: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1981: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1982: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1983: #         in course's home server.
1.637     raeburn  1984: #
1.477     raeburn  1985: 
                   1986: sub process_coursefile {
1.638     albertel 1987:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1988:     my $fetchresult;
1.638     albertel 1989:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1990:     if ($action eq 'propagate') {
1.638     albertel 1991:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1992: 			     $home);
1.481     raeburn  1993:     } else {
1.477     raeburn  1994:         my $fpath = '';
                   1995:         my $fname = $file;
1.478     albertel 1996:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1997:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1998:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1999:         if ($action eq 'copy') {
                   2000:             if ($source eq '') {
                   2001:                 $fetchresult = 'no source file';
                   2002:                 return $fetchresult;
                   2003:             } else {
                   2004:                 my $destination = $filepath.'/'.$fname;
                   2005:                 rename($source,$destination);
                   2006:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2007:                                  $home);
1.481     raeburn  2008:             }
                   2009:         } elsif ($action eq 'uploaddoc') {
                   2010:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2011:             print $fh $env{'form.'.$source};
1.481     raeburn  2012:             close($fh);
1.637     raeburn  2013:             if ($parser eq 'parse') {
1.961     raeburn  2014:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
1.637     raeburn  2015:                 unless ($parse_result eq 'ok') {
                   2016:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2017:                 }
                   2018:             }
1.477     raeburn  2019:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2020:                                  $home);
1.481     raeburn  2021:             if ($fetchresult eq 'ok') {
                   2022:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2023:             } else {
                   2024:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2025:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2026:                 return '/adm/notfound.html';
                   2027:             }
1.477     raeburn  2028:         }
                   2029:     }
1.485     raeburn  2030:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2031:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2032:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2033:     }
                   2034:     return $fetchresult;
                   2035: }
                   2036: 
1.637     raeburn  2037: sub build_filepath {
                   2038:     my ($fpath) = @_;
                   2039:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2040:     unless ($fpath eq '') {
                   2041:         my @parts=split('/',$fpath);
                   2042:         foreach my $part (@parts) {
                   2043:             $filepath.= '/'.$part;
                   2044:             if ((-e $filepath)!=1) {
                   2045:                 mkdir($filepath,0777);
                   2046:             }
                   2047:         }
                   2048:     }
                   2049:     return $filepath;
                   2050: }
                   2051: 
                   2052: sub store_edited_file {
1.638     albertel 2053:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2054:     my $file = $primary_url;
                   2055:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2056:     my $fpath = '';
                   2057:     my $fname = $file;
                   2058:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2059:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2060:     my $filepath = &build_filepath($fpath);
                   2061:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2062:     print $fh $content;
                   2063:     close($fh);
1.638     albertel 2064:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2065:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2066: 			  $home);
1.637     raeburn  2067:     if ($$fetchresult eq 'ok') {
                   2068:         return '/uploaded/'.$fpath.'/'.$fname;
                   2069:     } else {
1.638     albertel 2070:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2071: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2072:         return '/adm/notfound.html';
                   2073:     }
                   2074: }
                   2075: 
1.531     albertel 2076: sub clean_filename {
1.831     albertel 2077:     my ($fname,$args)=@_;
1.315     www      2078: # Replace Windows backslashes by forward slashes
1.257     www      2079:     $fname=~s/\\/\//g;
1.831     albertel 2080:     if (!$args->{'keep_path'}) {
                   2081:         # Get rid of everything but the actual filename
                   2082: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2083:     }
1.315     www      2084: # Replace spaces by underscores
                   2085:     $fname=~s/\s+/\_/g;
                   2086: # Replace all other weird characters by nothing
1.831     albertel 2087:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2088: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2089: # numbers
                   2090:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2091:     return $fname;
                   2092: }
1.984     neumanie 2093: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
                   2094: sub resizeImage {
                   2095: 	my($img_url) = @_;	
                   2096: 	my $ima = Image::Magick->new;                       
                   2097:         $ima->Read($img_url);
                   2098: 	if($ima->Get('width') > 400)
                   2099: 	{
                   2100: 		my $factor = $ima->Get('width')/400;
                   2101:              	$ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
                   2102: 	}
                   2103: 	if($ima->Get('height') > 500)
                   2104:         {
                   2105:         	my $factor = $ima->Get('height')/500;
                   2106:                 $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
                   2107:         } 
                   2108: 		
                   2109: 	$ima->Write($img_url);
                   2110: }
1.531     albertel 2111: 
1.977     amueller 2112: #Wrapper function for userphotoupload
                   2113: sub userphotoupload
                   2114: {
                   2115: 	my($formname,$subdir) = @_;
                   2116: 	$upload_photo_form = 1;
                   2117: 	return &userfileupload($formname,undef,$subdir);
                   2118: }
                   2119: 
1.608     albertel 2120: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2121: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 2122: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 2123: #        $coursedoc - if true up to the current course
                   2124: #                     if false
                   2125: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2126: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2127: #        $allfiles - reference to hash for embedded objects
                   2128: #        $codebase - reference to hash for codebase of java objects
                   2129: #        $desuname - username for permanent storage of uploaded file
                   2130: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2131: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2132: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  2133: # 
1.686     albertel 2134: # output: url of file in userspace, or error: <message> 
                   2135: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2136: 
                   2137: 
1.531     albertel 2138: sub userfileupload {
1.860     raeburn  2139:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   2140:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 2141:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2142:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2143:     $fname=&clean_filename($fname);
1.315     www      2144: # See if there is anything left
1.257     www      2145:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2146:     chop($env{'form.'.$formname});
1.523     raeburn  2147:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2148:         my $now = time;
                   2149:         my $filepath = 'tmp/helprequests/'.$now;
                   2150:         my @parts=split(/\//,$filepath);
                   2151:         my $fullpath = $perlvar{'lonDaemons'};
                   2152:         for (my $i=0;$i<@parts;$i++) {
                   2153:             $fullpath .= '/'.$parts[$i];
                   2154:             if ((-e $fullpath)!=1) {
                   2155:                 mkdir($fullpath,0777);
                   2156:             }
                   2157:         }
                   2158:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2159:         print $fh $env{'form.'.$formname};
1.523     raeburn  2160:         close($fh);
1.741     raeburn  2161:         return $fullpath.'/'.$fname;
                   2162:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2163:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2164:                        '_'.$env{'user.domain'}.'/pending';
                   2165:         my @parts=split(/\//,$filepath);
                   2166:         my $fullpath = $perlvar{'lonDaemons'};
                   2167:         for (my $i=0;$i<@parts;$i++) {
                   2168:             $fullpath .= '/'.$parts[$i];
                   2169:             if ((-e $fullpath)!=1) {
                   2170:                 mkdir($fullpath,0777);
                   2171:             }
                   2172:         }
                   2173:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2174:         print $fh $env{'form.'.$formname};
                   2175:         close($fh);
                   2176:         return $fullpath.'/'.$fname;
1.523     raeburn  2177:     }
1.995     raeburn  2178:     if ($subdir eq 'scantron') {
                   2179:         $fname = 'scantron_orig_'.$fname;
                   2180:     } else {   
1.258     www      2181: # Create the directory if not present
1.995     raeburn  2182:         $fname="$subdir/$fname";
                   2183:     }
1.259     www      2184:     if ($coursedoc) {
1.638     albertel 2185: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2186: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2187:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2188:             return &finishuserfileupload($docuname,$docudom,
                   2189: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  2190: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  2191:         } else {
1.620     albertel 2192:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2193:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2194: 				       $fname,$formname,$parser,
                   2195: 				       $allfiles,$codebase);
1.481     raeburn  2196:         }
1.719     banghart 2197:     } elsif (defined($destuname)) {
                   2198:         my $docuname=$destuname;
                   2199:         my $docudom=$destudom;
1.860     raeburn  2200: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2201: 				     $parser,$allfiles,$codebase,
                   2202:                                      $thumbwidth,$thumbheight);
1.719     banghart 2203:         
1.259     www      2204:     } else {
1.638     albertel 2205:         my $docuname=$env{'user.name'};
                   2206:         my $docudom=$env{'user.domain'};
1.714     raeburn  2207:         if (exists($env{'form.group'})) {
                   2208:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2209:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2210:         }
1.860     raeburn  2211: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2212: 				     $parser,$allfiles,$codebase,
                   2213:                                      $thumbwidth,$thumbheight);
1.259     www      2214:     }
1.271     www      2215: }
                   2216: 
                   2217: sub finishuserfileupload {
1.860     raeburn  2218:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   2219:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  2220:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2221:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2222:   
1.860     raeburn  2223:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2224:     $file=$fname;
                   2225:     if ($fname=~m|/|) {
                   2226:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2227: 	$path.=$fnamepath.'/';
                   2228:     }
1.259     www      2229:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2230:     my $count;
                   2231:     for ($count=4;$count<=$#parts;$count++) {
                   2232:         $filepath.="/$parts[$count]";
                   2233:         if ((-e $filepath)!=1) {
                   2234: 	    mkdir($filepath,0777);
                   2235:         }
                   2236:     }
1.984     neumanie 2237: 
1.258     www      2238: # Save the file
                   2239:     {
1.701     albertel 2240: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2241: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2242: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2243: 	    return '/adm/notfound.html';
                   2244: 	}
                   2245: 	if (!print FH ($env{'form.'.$formname})) {
                   2246: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2247: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2248: 	    return '/adm/notfound.html';
                   2249: 	}
1.570     albertel 2250: 	close(FH);
1.977     amueller 2251: 	if($upload_photo_form==1)
                   2252: 	{
1.984     neumanie 2253: 		resizeImage($filepath.'/'.$file);		
1.977     amueller 2254: 		$upload_photo_form = 0;
                   2255: 	}
1.258     www      2256:     }
1.637     raeburn  2257:     if ($parser eq 'parse') {
1.961     raeburn  2258:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
1.638     albertel 2259: 						   $codebase);
1.637     raeburn  2260:         unless ($parse_result eq 'ok') {
1.638     albertel 2261:             &logthis('Failed to parse '.$filepath.$file.
                   2262: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  2263:         }
                   2264:     }
1.860     raeburn  2265:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2266:         my $input = $filepath.'/'.$file;
                   2267:         my $output = $filepath.'/'.'tn-'.$file;
                   2268:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2269:         system("convert -sample $thumbsize $input $output");
                   2270:         if (-e $filepath.'/'.'tn-'.$file) {
                   2271:             $fetchthumb  = 1; 
                   2272:         }
                   2273:     }
1.858     raeburn  2274:  
1.259     www      2275: # Notify homeserver to grep it
                   2276: #
1.984     neumanie 2277:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2278:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2279:     if ($fetchresult eq 'ok') {
1.860     raeburn  2280:         if ($fetchthumb) {
                   2281:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2282:             if ($thumbresult ne 'ok') {
                   2283:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2284:                          $docuhome.': '.$thumbresult);
                   2285:             }
                   2286:         }
1.259     www      2287: #
1.258     www      2288: # Return the URL to it
1.494     albertel 2289:         return '/uploaded/'.$path.$file;
1.263     www      2290:     } else {
1.494     albertel 2291:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2292: 		 ': '.$fetchresult);
1.263     www      2293:         return '/adm/notfound.html';
1.858     raeburn  2294:     }
1.493     albertel 2295: }
                   2296: 
1.637     raeburn  2297: sub extract_embedded_items {
1.961     raeburn  2298:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2299:     my @state = ();
                   2300:     my %javafiles = (
                   2301:                       codebase => '',
                   2302:                       code => '',
                   2303:                       archive => ''
                   2304:                     );
                   2305:     my %mediafiles = (
                   2306:                       src => '',
                   2307:                       movie => '',
                   2308:                      );
1.648     raeburn  2309:     my $p;
                   2310:     if ($content) {
                   2311:         $p = HTML::LCParser->new($content);
                   2312:     } else {
1.961     raeburn  2313:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2314:     }
1.641     albertel 2315:     while (my $t=$p->get_token()) {
1.640     albertel 2316: 	if ($t->[0] eq 'S') {
                   2317: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2318: 	    push(@state, $tagname);
1.648     raeburn  2319:             if (lc($tagname) eq 'allow') {
                   2320:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2321:             }
1.640     albertel 2322: 	    if (lc($tagname) eq 'img') {
                   2323: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2324: 	    }
1.886     albertel 2325: 	    if (lc($tagname) eq 'a') {
                   2326: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2327: 	    }
1.645     raeburn  2328:             if (lc($tagname) eq 'script') {
                   2329:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2330:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2331:                 } else {
                   2332:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2333:                 }
                   2334:             }
                   2335:             if (lc($tagname) eq 'link') {
                   2336:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2337:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2338:                 }
                   2339:             }
1.640     albertel 2340: 	    if (lc($tagname) eq 'object' ||
                   2341: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2342: 		foreach my $item (keys(%javafiles)) {
                   2343: 		    $javafiles{$item} = '';
                   2344: 		}
                   2345: 	    }
                   2346: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2347: 		my $name = lc($attr->{'name'});
                   2348: 		foreach my $item (keys(%javafiles)) {
                   2349: 		    if ($name eq $item) {
                   2350: 			$javafiles{$item} = $attr->{'value'};
                   2351: 			last;
                   2352: 		    }
                   2353: 		}
                   2354: 		foreach my $item (keys(%mediafiles)) {
                   2355: 		    if ($name eq $item) {
                   2356: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2357: 			last;
                   2358: 		    }
                   2359: 		}
                   2360: 	    }
                   2361: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2362: 		foreach my $item (keys(%javafiles)) {
                   2363: 		    if ($attr->{$item}) {
                   2364: 			$javafiles{$item} = $attr->{$item};
                   2365: 			last;
                   2366: 		    }
                   2367: 		}
                   2368: 		foreach my $item (keys(%mediafiles)) {
                   2369: 		    if ($attr->{$item}) {
                   2370: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2371: 			last;
                   2372: 		    }
                   2373: 		}
                   2374: 	    }
                   2375: 	} elsif ($t->[0] eq 'E') {
                   2376: 	    my ($tagname) = ($t->[1]);
                   2377: 	    if ($javafiles{'codebase'} ne '') {
                   2378: 		$javafiles{'codebase'} .= '/';
                   2379: 	    }  
                   2380: 	    if (lc($tagname) eq 'applet' ||
                   2381: 		lc($tagname) eq 'object' ||
                   2382: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2383: 		) {
                   2384: 		foreach my $item (keys(%javafiles)) {
                   2385: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2386: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2387: 			&add_filetype($allfiles,$file,$item);
                   2388: 		    }
                   2389: 		}
                   2390: 	    } 
                   2391: 	    pop @state;
                   2392: 	}
                   2393:     }
1.637     raeburn  2394:     return 'ok';
                   2395: }
                   2396: 
1.639     albertel 2397: sub add_filetype {
                   2398:     my ($allfiles,$file,$type)=@_;
                   2399:     if (exists($allfiles->{$file})) {
                   2400: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2401: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2402: 	}
                   2403:     } else {
                   2404: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2405:     }
                   2406: }
                   2407: 
1.493     albertel 2408: sub removeuploadedurl {
1.984     neumanie 2409:     my ($url)=@_;	
                   2410:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2411:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2412: }
                   2413: 
                   2414: sub removeuserfile {
                   2415:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2416:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2417:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2418:     if ($result eq 'ok') {	
1.798     raeburn  2419:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2420:             my $metafile = $fname.'.meta';
                   2421:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2422: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2423:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2424:             my $sqlresult = 
1.823     albertel 2425:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2426:                                         'portfolio_metadata',$group,
                   2427:                                         'delete');
1.798     raeburn  2428:         }
                   2429:     }
                   2430:     return $result;
1.257     www      2431: }
1.15      www      2432: 
1.530     albertel 2433: sub mkdiruserfile {
                   2434:     my ($docuname,$docudom,$dir)=@_;
                   2435:     my $home=&homeserver($docuname,$docudom);
                   2436:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2437: }
                   2438: 
1.531     albertel 2439: sub renameuserfile {
                   2440:     my ($docuname,$docudom,$old,$new)=@_;
                   2441:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2442:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2443:                         &escape("$old").':'.&escape("$new"),$home);
                   2444:     if ($result eq 'ok') {
                   2445:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2446:             my $oldmeta = $old.'.meta';
                   2447:             my $newmeta = $new.'.meta';
                   2448:             my $metaresult = 
                   2449:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2450: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2451:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2452:             my $sqlresult = 
1.823     albertel 2453:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2454:                                         'portfolio_metadata',$group,
                   2455:                                         'delete');
1.798     raeburn  2456:         }
                   2457:     }
                   2458:     return $result;
1.531     albertel 2459: }
                   2460: 
1.14      www      2461: # ------------------------------------------------------------------------- Log
                   2462: 
                   2463: sub log {
                   2464:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2465:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2466: }
                   2467: 
                   2468: # ------------------------------------------------------------------ Course Log
1.352     www      2469: #
                   2470: # This routine flushes several buffers of non-mission-critical nature
                   2471: #
1.157     www      2472: 
                   2473: sub flushcourselogs {
1.352     www      2474:     &logthis('Flushing log buffers');
                   2475: #
                   2476: # course logs
                   2477: # This is a log of all transactions in a course, which can be used
                   2478: # for data mining purposes
                   2479: #
                   2480: # It also collects the courseid database, which lists last transaction
                   2481: # times and course titles for all courseids
                   2482: #
                   2483:     my %courseidbuffer=();
1.921     raeburn  2484:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2485:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2486: 		          &escape($courselogs{$crsid}),
                   2487: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2488: 	    delete $courselogs{$crsid};
                   2489:         } else {
                   2490:             &logthis('Failed to flush log buffer for '.$crsid);
                   2491:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2492:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2493:                         " exceeded maximum size, deleting.</font>");
                   2494:                delete $courselogs{$crsid};
                   2495:             }
1.352     www      2496:         }
1.920     raeburn  2497:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2498:             'description' => $coursedescrbuf{$crsid},
                   2499:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2500:             'type'        => $coursetypebuf{$crsid},
                   2501:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2502:         };
1.191     harris41 2503:     }
1.352     www      2504: #
                   2505: # Write course id database (reverse lookup) to homeserver of courses 
                   2506: # Is used in pickcourse
                   2507: #
1.840     albertel 2508:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2509:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2510:                                     $courseidbuffer{$crs_home},
                   2511:                                     $crs_home,'timeonly');
1.352     www      2512:     }
                   2513: #
                   2514: # File accesses
                   2515: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2516: #
1.449     matthew  2517:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2518:         if ($entry =~ /___count$/) {
                   2519:             my ($dom,$name);
1.807     albertel 2520:             ($dom,$name,undef)=
1.811     albertel 2521: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2522:             if (! defined($dom) || $dom eq '' || 
                   2523:                 ! defined($name) || $name eq '') {
1.620     albertel 2524:                 my $cid = $env{'request.course.id'};
                   2525:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2526:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2527:             }
1.450     matthew  2528:             my $value = $accesshash{$entry};
                   2529:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2530:             my %temphash=($url => $value);
1.449     matthew  2531:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2532:             if ($result eq 'ok') {
                   2533:                 delete $accesshash{$entry};
                   2534:             } elsif ($result eq 'unknown_cmd') {
                   2535:                 # Target server has old code running on it.
1.450     matthew  2536:                 my %temphash=($entry => $value);
1.449     matthew  2537:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2538:                     delete $accesshash{$entry};
                   2539:                 }
                   2540:             }
                   2541:         } else {
1.811     albertel 2542:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2543:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2544:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2545:                 delete $accesshash{$entry};
                   2546:             }
1.185     www      2547:         }
1.191     harris41 2548:     }
1.352     www      2549: #
                   2550: # Roles
                   2551: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2552: #
1.800     albertel 2553:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2554:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2555: 	    split(/\:/,$entry);
                   2556:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2557:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2558:                 $rudom,$runame) eq 'ok') {
                   2559: 	    delete $userrolehash{$entry};
                   2560:         }
                   2561:     }
1.662     raeburn  2562: #
                   2563: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2564: #
                   2565:     my %domrolebuffer = ();
1.1000    raeburn  2566:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 2567:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2568:         if ($domrolebuffer{$rudom}) {
                   2569:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2570:                       '='.&escape($domainrolehash{$entry});
                   2571:         } else {
                   2572:             $domrolebuffer{$rudom}.=&escape($entry).
                   2573:                       '='.&escape($domainrolehash{$entry});
                   2574:         }
                   2575:         delete $domainrolehash{$entry};
                   2576:     }
                   2577:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2578: 	my %servers = &get_servers($dom,'library');
                   2579: 	foreach my $tryserver (keys(%servers)) {
                   2580: 	    unless (&reply('domroleput:'.$dom.':'.
                   2581: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2582: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2583: 	    }
1.662     raeburn  2584:         }
                   2585:     }
1.186     www      2586:     $dumpcount++;
1.157     www      2587: }
                   2588: 
                   2589: sub courselog {
                   2590:     my $what=shift;
1.158     www      2591:     $what=time.':'.$what;
1.620     albertel 2592:     unless ($env{'request.course.id'}) { return ''; }
                   2593:     $coursedombuf{$env{'request.course.id'}}=
                   2594:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2595:     $coursenumbuf{$env{'request.course.id'}}=
                   2596:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2597:     $coursehombuf{$env{'request.course.id'}}=
                   2598:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2599:     $coursedescrbuf{$env{'request.course.id'}}=
                   2600:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2601:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2602:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2603:     $courseownerbuf{$env{'request.course.id'}}=
                   2604:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2605:     $coursetypebuf{$env{'request.course.id'}}=
                   2606:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2607:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2608: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2609:     } else {
1.620     albertel 2610: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2611:     }
1.620     albertel 2612:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2613: 	&flushcourselogs();
                   2614:     }
1.158     www      2615: }
                   2616: 
                   2617: sub courseacclog {
                   2618:     my $fnsymb=shift;
1.620     albertel 2619:     unless ($env{'request.course.id'}) { return ''; }
                   2620:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2621:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2622:         $what.=':POST';
1.583     matthew  2623:         # FIXME: Probably ought to escape things....
1.800     albertel 2624: 	foreach my $key (keys(%env)) {
                   2625:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2626:                 my $formitem = $1;
                   2627:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2628:                     $what.=':'.$formitem.'='.$env{$key};
                   2629:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2630:                     $what.=':'.$formitem.'='.$env{$key};
                   2631:                 }
1.158     www      2632:             }
1.191     harris41 2633:         }
1.583     matthew  2634:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2635:         # FIXME: We should not be depending on a form parameter that someone
                   2636:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2637:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2638:             $what.= ':POST';
                   2639:             # FIXME: Probably ought to escape things....
                   2640:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2641:                                  'crsdiscuss') {
1.620     albertel 2642:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2643:             }
                   2644:         }
1.158     www      2645:     }
                   2646:     &courselog($what);
1.149     www      2647: }
                   2648: 
1.185     www      2649: sub countacc {
                   2650:     my $url=&declutter(shift);
1.458     matthew  2651:     return if (! defined($url) || $url eq '');
1.620     albertel 2652:     unless ($env{'request.course.id'}) { return ''; }
                   2653:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2654:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2655:     $accesshash{$key}++;
1.185     www      2656: }
1.349     www      2657: 
1.361     www      2658: sub linklog {
                   2659:     my ($from,$to)=@_;
                   2660:     $from=&declutter($from);
                   2661:     $to=&declutter($to);
                   2662:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2663:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2664: }
                   2665:   
1.349     www      2666: sub userrolelog {
                   2667:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2668:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2669:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2670:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2671:         ($trole=~/^ta/)) {
1.350     www      2672:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2673:        $userrolehash
                   2674:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2675:                     =$tend.':'.$tstart;
1.662     raeburn  2676:     }
1.898     albertel 2677:     if (($env{'request.role'} =~ /dc\./) &&
                   2678: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2679: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2680: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2681:        $userrolehash
                   2682:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2683:                     =$tend.':'.$tstart;
                   2684:     }
1.662     raeburn  2685:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2686:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2687:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2688:         ($trole=~/^sc/)) {
                   2689:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2690:        $domainrolehash
                   2691:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2692:                     = $tend.':'.$tstart;
                   2693:     }
1.351     www      2694: }
                   2695: 
1.957     raeburn  2696: sub courserolelog {
                   2697:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2698:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2699:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2700:         ($trole eq 'ta') || ($trole eq 'st') ||
                   2701:         ($trole=~/^cr/) || ($trole eq 'gr')) {
                   2702:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2703:             my $cdom = $1;
                   2704:             my $cnum = $2;
                   2705:             my $sec = $3;
                   2706:             my $namespace = 'rolelog';
                   2707:             my %storehash = (
                   2708:                                role    => $trole,
                   2709:                                start   => $tstart,
                   2710:                                end     => $tend,
                   2711:                                selfenroll => $selfenroll,
                   2712:                                context    => $context,
                   2713:                             );
                   2714:             if ($trole eq 'gr') {
                   2715:                 $namespace = 'groupslog';
                   2716:                 $storehash{'group'} = $sec;
                   2717:             } else {
                   2718:                 $storehash{'section'} = $sec;
                   2719:             }
                   2720:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  2721:             if (($trole ne 'st') || ($sec ne '')) {
                   2722:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   2723:             }
1.957     raeburn  2724:         }
                   2725:     }
                   2726:     return;
                   2727: }
                   2728: 
1.351     www      2729: sub get_course_adv_roles {
1.948     raeburn  2730:     my ($cid,$codes) = @_;
1.620     albertel 2731:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2732:     my %coursehash=&coursedescription($cid);
1.988     raeburn  2733:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      2734:     my %nothide=();
1.800     albertel 2735:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2736:         if ($user !~ /:/) {
                   2737: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2738:         } else {
                   2739:             $nothide{$user}=1;
                   2740:         }
1.470     www      2741:     }
1.351     www      2742:     my %returnhash=();
                   2743:     my %dumphash=
                   2744:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2745:     my $now=time;
1.997     raeburn  2746:     my %privileged;
1.1000    raeburn  2747:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 2748: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2749:         if (($tstart) && ($tstart<0)) { next; }
                   2750:         if (($tend) && ($tend<$now)) { next; }
                   2751:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2752:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2753: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  2754:         unless (ref($privileged{$domain}) eq 'HASH') {
                   2755:             my %dompersonnel =
1.998     raeburn  2756:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  2757:             $privileged{$domain} = {};
                   2758:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  2759:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  2760:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   2761:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   2762:                         $privileged{$udom}{$uname} = 1;
                   2763:                     }
                   2764:                 }
                   2765:             }
                   2766:         }
                   2767:         if ((exists($privileged{$domain}{$username})) && 
                   2768:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2769: 	if ($role eq 'cr') { next; }
1.948     raeburn  2770:         if ($codes) {
                   2771:             if ($section) { $role .= ':'.$section; }
                   2772:             if ($returnhash{$role}) {
                   2773:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2774:             } else {
                   2775:                 $returnhash{$role}=$username.':'.$domain;
                   2776:             }
1.351     www      2777:         } else {
1.988     raeburn  2778:             my $key=&plaintext($role,$crstype);
1.973     bisitz   2779:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  2780:             if ($returnhash{$key}) {
                   2781: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2782:             } else {
                   2783:                 $returnhash{$key}=$username.':'.$domain;
                   2784:             }
1.351     www      2785:         }
1.948     raeburn  2786:     }
1.400     www      2787:     return %returnhash;
                   2788: }
                   2789: 
                   2790: sub get_my_roles {
1.937     raeburn  2791:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2792:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2793:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2794:     my (%dumphash,%nothide);
1.858     raeburn  2795:     if ($context eq 'userroles') { 
                   2796:         %dumphash = &dump('roles',$udom,$uname);
                   2797:     } else {
                   2798:         %dumphash=
1.400     www      2799:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2800:         if ($hidepriv) {
                   2801:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2802:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2803:                 if ($user !~ /:/) {
                   2804:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2805:                 } else {
                   2806:                     $nothide{$user} = 1;
                   2807:                 }
                   2808:             }
                   2809:         }
1.858     raeburn  2810:     }
1.400     www      2811:     my %returnhash=();
                   2812:     my $now=time;
1.999     raeburn  2813:     my %privileged;
1.800     albertel 2814:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2815:         my ($role,$tend,$tstart);
                   2816:         if ($context eq 'userroles') {
                   2817: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2818:         } else {
                   2819:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2820:         }
1.400     www      2821:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2822:         my $status = 'active';
1.939     raeburn  2823:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2824:             $status = 'previous';
                   2825:         } 
                   2826:         if (($tstart) && ($now<$tstart)) {
                   2827:             $status = 'future';
                   2828:         }
                   2829:         if (ref($types) eq 'ARRAY') {
                   2830:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2831:                 next;
                   2832:             } 
                   2833:         } else {
                   2834:             if ($status ne 'active') {
                   2835:                 next;
                   2836:             }
                   2837:         }
1.867     raeburn  2838:         my ($rolecode,$username,$domain,$section,$area);
                   2839:         if ($context eq 'userroles') {
                   2840:             ($area,$rolecode) = split(/_/,$entry);
                   2841:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2842:         } else {
                   2843:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2844:         }
1.832     raeburn  2845:         if (ref($roledoms) eq 'ARRAY') {
                   2846:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2847:                 next;
                   2848:             }
                   2849:         }
                   2850:         if (ref($roles) eq 'ARRAY') {
                   2851:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2852:                 if ($role =~ /^cr\//) {
                   2853:                     if (!grep(/^cr$/,@{$roles})) {
                   2854:                         next;
                   2855:                     }
                   2856:                 } else {
                   2857:                     next;
                   2858:                 }
1.832     raeburn  2859:             }
1.867     raeburn  2860:         }
1.937     raeburn  2861:         if ($hidepriv) {
1.999     raeburn  2862:             if ($context eq 'userroles') {
                   2863:                 if ((&privileged($username,$domain)) &&
                   2864:                     (!$nothide{$username.':'.$domain})) {
                   2865:                     next;
                   2866:                 }
                   2867:             } else {
                   2868:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   2869:                     my %dompersonnel =
                   2870:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   2871:                     $privileged{$domain} = {};
                   2872:                     if (keys(%dompersonnel)) {
                   2873:                         foreach my $server (keys(%dompersonnel)) {
                   2874:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   2875:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   2876:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   2877:                                     $privileged{$udom}{$uname} = $trole;
                   2878:                                 }
                   2879:                             }
                   2880:                         }
                   2881:                     }
                   2882:                 }
                   2883:                 if (exists($privileged{$domain}{$username})) {
                   2884:                     if (!$nothide{$username.':'.$domain}) {
                   2885:                         next;
                   2886:                     }
                   2887:                 }
1.937     raeburn  2888:             }
                   2889:         }
1.933     raeburn  2890:         if ($withsec) {
                   2891:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2892:                 $tstart.':'.$tend;
                   2893:         } else {
                   2894:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2895:         }
1.832     raeburn  2896:     }
1.373     www      2897:     return %returnhash;
1.399     www      2898: }
                   2899: 
                   2900: # ----------------------------------------------------- Frontpage Announcements
                   2901: #
                   2902: #
                   2903: 
                   2904: sub postannounce {
                   2905:     my ($server,$text)=@_;
1.844     albertel 2906:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2907:     unless ($text=~/\w/) { $text=''; }
                   2908:     return &reply('setannounce:'.&escape($text),$server);
                   2909: }
                   2910: 
                   2911: sub getannounce {
1.448     albertel 2912: 
                   2913:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2914: 	my $announcement='';
1.800     albertel 2915: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2916: 	close($fh);
1.399     www      2917: 	if ($announcement=~/\w/) { 
                   2918: 	    return 
                   2919:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2920:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2921: 	} else {
                   2922: 	    return '';
                   2923: 	}
                   2924:     } else {
                   2925: 	return '';
                   2926:     }
1.351     www      2927: }
1.353     www      2928: 
                   2929: # ---------------------------------------------------------- Course ID routines
                   2930: # Deal with domain's nohist_courseid.db files
                   2931: #
                   2932: 
                   2933: sub courseidput {
1.921     raeburn  2934:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2935:     my $outcome;
                   2936:     if ($caller eq 'timeonly') {
                   2937:         my $cids = '';
                   2938:         foreach my $item (keys(%$storehash)) {
                   2939:             $cids.=&escape($item).'&';
                   2940:         }
                   2941:         $cids=~s/\&$//;
                   2942:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2943:                           $coursehome);       
                   2944:     } else {
                   2945:         my $items = '';
                   2946:         foreach my $item (keys(%$storehash)) {
                   2947:             $items.= &escape($item).'='.
                   2948:                      &freeze_escape($$storehash{$item}).'&';
                   2949:         }
                   2950:         $items=~s/\&$//;
                   2951:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2952:                           $coursehome);
1.918     raeburn  2953:     }
                   2954:     if ($outcome eq 'unknown_cmd') {
                   2955:         my $what;
                   2956:         foreach my $cid (keys(%$storehash)) {
                   2957:             $what .= &escape($cid).'=';
1.921     raeburn  2958:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2959:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2960:             }
                   2961:             $what =~ s/\:$/&/;
                   2962:         }
                   2963:         $what =~ s/\&$//;  
                   2964:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2965:     } else {
                   2966:         return $outcome;
                   2967:     }
1.353     www      2968: }
                   2969: 
                   2970: sub courseiddump {
1.921     raeburn  2971:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  2972:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1008    raeburn  2973:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,$cloneonly)=@_;
1.918     raeburn  2974:     my $as_hash = 1;
                   2975:     my %returnhash;
                   2976:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2977:     my %libserv = &all_library();
                   2978:     foreach my $tryserver (keys(%libserv)) {
                   2979:         if ( (  $hostidflag == 1 
                   2980: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2981: 	     || (!defined($hostidflag)) ) {
                   2982: 
1.918     raeburn  2983: 	    if (($domfilter eq '') ||
                   2984: 		(&host_domain($tryserver) eq $domfilter)) {
                   2985:                 my $rep = 
                   2986:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2987:                          $sincefilter.':'.&escape($descfilter).':'.
                   2988:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2989:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  2990:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  2991:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  2992:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   2993:                          &escape($cc_clone).':'.$cloneonly,$tryserver);
1.918     raeburn  2994:                 my @pairs=split(/\&/,$rep);
                   2995:                 foreach my $item (@pairs) {
                   2996:                     my ($key,$value)=split(/\=/,$item,2);
                   2997:                     $key = &unescape($key);
                   2998:                     next if ($key =~ /^error: 2 /);
                   2999:                     my $result = &thaw_unescape($value);
                   3000:                     if (ref($result) eq 'HASH') {
                   3001:                         $returnhash{$key}=$result;
                   3002:                     } else {
1.921     raeburn  3003:                         my @responses = split(/:/,$value);
                   3004:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3005:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3006:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3007:                         }
1.1008    raeburn  3008:                     }
1.353     www      3009:                 }
                   3010:             }
                   3011:         }
                   3012:     }
                   3013:     return %returnhash;
                   3014: }
                   3015: 
1.658     raeburn  3016: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3017: 
                   3018: sub dcmailput {
1.685     raeburn  3019:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3020:     my $status = &Apache::lonnet::critical(
1.740     www      3021:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3022:        &escape($message),$server);
1.662     raeburn  3023:     return $status;
                   3024: }
                   3025: 
1.658     raeburn  3026: sub dcmaildump {
                   3027:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3028:     my %returnhash=();
1.846     albertel 3029: 
                   3030:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3031:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3032:                                                          &escape($enddate).':';
                   3033: 	my @esc_senders=map { &escape($_)} @$senders;
                   3034: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3035: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3036:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3037:             if (($key) && ($value)) {
                   3038:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3039:             }
                   3040:         }
                   3041:     }
                   3042:     return %returnhash;
                   3043: }
1.662     raeburn  3044: # ---------------------------------------------------------- Domain roles
                   3045: 
                   3046: sub get_domain_roles {
                   3047:     my ($dom,$roles,$startdate,$enddate)=@_;
                   3048:     if (undef($startdate) || $startdate eq '') {
                   3049:         $startdate = '.';
                   3050:     }
                   3051:     if (undef($enddate) || $enddate eq '') {
                   3052:         $enddate = '.';
                   3053:     }
1.922     raeburn  3054:     my $rolelist;
                   3055:     if (ref($roles) eq 'ARRAY') {
                   3056:         $rolelist = join(':',@{$roles});
                   3057:     }
1.662     raeburn  3058:     my %personnel = ();
1.841     albertel 3059: 
                   3060:     my %servers = &get_servers($dom,'library');
                   3061:     foreach my $tryserver (keys(%servers)) {
                   3062: 	%{$personnel{$tryserver}}=();
                   3063: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3064: 					    &escape($startdate).':'.
                   3065: 					    &escape($enddate).':'.
                   3066: 					    &escape($rolelist), $tryserver))) {
                   3067: 	    my ($key,$value) = split(/\=/,$line,2);
                   3068: 	    if (($key) && ($value)) {
                   3069: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3070: 	    }
                   3071: 	}
1.662     raeburn  3072:     }
                   3073:     return %personnel;
                   3074: }
1.658     raeburn  3075: 
1.149     www      3076: # ----------------------------------------------------------- Check out an item
                   3077: 
1.504     albertel 3078: sub get_first_access {
                   3079:     my ($type,$argsymb)=@_;
1.790     albertel 3080:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3081:     if ($argsymb) { $symb=$argsymb; }
                   3082:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3083:     if ($type eq 'course') {
                   3084: 	$res='course';
                   3085:     } elsif ($type eq 'map') {
1.588     albertel 3086: 	$res=&symbread($map);
                   3087:     } else {
                   3088: 	$res=$symb;
                   3089:     }
                   3090:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3091:     return $times{"$courseid\0$res"};
1.504     albertel 3092: }
                   3093: 
                   3094: sub set_first_access {
                   3095:     my ($type)=@_;
1.790     albertel 3096:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3097:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3098:     if ($type eq 'course') {
                   3099: 	$res='course';
                   3100:     } elsif ($type eq 'map') {
1.588     albertel 3101: 	$res=&symbread($map);
                   3102:     } else {
                   3103: 	$res=$symb;
                   3104:     }
                   3105:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3106:     if (!$firstaccess) {
1.588     albertel 3107: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3108:     }
                   3109:     return 'already_set';
1.504     albertel 3110: }
                   3111: 
1.149     www      3112: sub checkout {
                   3113:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   3114:     my $now=time;
                   3115:     my $lonhost=$perlvar{'lonHostID'};
                   3116:     my $infostr=&escape(
1.234     www      3117:                  'CHECKOUTTOKEN&'.
1.149     www      3118:                  $tuname.'&'.
                   3119:                  $tudom.'&'.
                   3120:                  $tcrsid.'&'.
                   3121:                  $symb.'&'.
                   3122: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   3123:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      3124:     if ($token=~/^error\:/) { 
1.672     albertel 3125:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3126:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3127:                  "</font>");
                   3128:         return ''; 
                   3129:     }
                   3130: 
1.149     www      3131:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   3132:     $token=~tr/a-z/A-Z/;
                   3133: 
1.153     www      3134:     my %infohash=('resource.0.outtoken' => $token,
                   3135:                   'resource.0.checkouttime' => $now,
                   3136:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      3137: 
                   3138:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3139:        return '';
1.151     www      3140:     } else {
1.672     albertel 3141:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3142:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3143:                  "</font>");
1.149     www      3144:     }    
                   3145: 
                   3146:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3147:                          &escape('Checkout '.$infostr.' - '.
                   3148:                                                  $token)) ne 'ok') {
                   3149: 	return '';
1.151     www      3150:     } else {
1.672     albertel 3151:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3152:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3153:                  "</font>");
1.149     www      3154:     }
1.151     www      3155:     return $token;
1.149     www      3156: }
                   3157: 
                   3158: # ------------------------------------------------------------ Check in an item
                   3159: 
                   3160: sub checkin {
                   3161:     my $token=shift;
1.150     www      3162:     my $now=time;
                   3163:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3164:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3165:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3166:     $dtoken=~s/\W/\_/g;
1.234     www      3167:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3168:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3169: 
1.154     www      3170:     unless (($tuname) && ($tudom)) {
                   3171:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3172:         return '';
                   3173:     }
                   3174:     
                   3175:     unless (&allowed('mgr',$tcrsid)) {
                   3176:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3177:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3178:         return '';
                   3179:     }
                   3180: 
1.153     www      3181:     my %infohash=('resource.0.intoken' => $token,
                   3182:                   'resource.0.checkintime' => $now,
                   3183:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3184: 
                   3185:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3186:        return '';
                   3187:     }    
                   3188: 
                   3189:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3190:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3191: 	return '';
                   3192:     }
                   3193: 
                   3194:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3195: }
                   3196: 
                   3197: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3198: 
                   3199: sub expirespread {
                   3200:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3201:     my $cid=$env{'request.course.id'}; 
1.110     www      3202:     if ($cid) {
                   3203:        my $now=time;
                   3204:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3205:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3206:                             $env{'course.'.$cid.'.num'}.
1.110     www      3207: 	        	    ':nohist_expirationdates:'.
                   3208:                             &escape($key).'='.$now,
1.620     albertel 3209:                             $env{'course.'.$cid.'.home'})
1.110     www      3210:     }
                   3211:     return 'ok';
1.14      www      3212: }
                   3213: 
1.109     www      3214: # ----------------------------------------------------- Devalidate Spreadsheets
                   3215: 
                   3216: sub devalidate {
1.325     www      3217:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3218:     my $cid=$env{'request.course.id'}; 
1.109     www      3219:     if ($cid) {
1.391     matthew  3220:         # delete the stored spreadsheets for
                   3221:         # - the student level sheet of this user in course's homespace
                   3222:         # - the assessment level sheet for this resource 
                   3223:         #   for this user in user's homespace
1.553     albertel 3224: 	# - current conditional state info
1.325     www      3225: 	my $key=$uname.':'.$udom.':';
1.109     www      3226:         my $status=
1.299     matthew  3227: 	    &del('nohist_calculatedsheets',
1.391     matthew  3228: 		 [$key.'studentcalc:'],
1.620     albertel 3229: 		 $env{'course.'.$cid.'.domain'},
                   3230: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3231: 		.' '.
                   3232: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3233: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3234:         unless ($status eq 'ok ok') {
                   3235:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3236:                     $uname.' at '.$udom.' for '.
1.109     www      3237: 		    $symb.': '.$status);
1.133     albertel 3238:         }
1.553     albertel 3239: 	&delenv('user.state.'.$cid);
1.109     www      3240:     }
                   3241: }
                   3242: 
1.265     albertel 3243: sub get_scalar {
                   3244:     my ($string,$end) = @_;
                   3245:     my $value;
                   3246:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3247: 	$value = $1;
                   3248:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3249: 	$value = $1;
                   3250:     }
                   3251:     return &unescape($value);
                   3252: }
                   3253: 
                   3254: sub array2str {
                   3255:   my (@array) = @_;
                   3256:   my $result=&arrayref2str(\@array);
                   3257:   $result=~s/^__ARRAY_REF__//;
                   3258:   $result=~s/__END_ARRAY_REF__$//;
                   3259:   return $result;
                   3260: }
                   3261: 
1.204     albertel 3262: sub arrayref2str {
                   3263:   my ($arrayref) = @_;
1.265     albertel 3264:   my $result='__ARRAY_REF__';
1.204     albertel 3265:   foreach my $elem (@$arrayref) {
1.265     albertel 3266:     if(ref($elem) eq 'ARRAY') {
                   3267:       $result.=&arrayref2str($elem).'&';
                   3268:     } elsif(ref($elem) eq 'HASH') {
                   3269:       $result.=&hashref2str($elem).'&';
                   3270:     } elsif(ref($elem)) {
                   3271:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3272:     } else {
                   3273:       $result.=&escape($elem).'&';
                   3274:     }
                   3275:   }
                   3276:   $result=~s/\&$//;
1.265     albertel 3277:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3278:   return $result;
                   3279: }
                   3280: 
1.168     albertel 3281: sub hash2str {
1.204     albertel 3282:   my (%hash) = @_;
                   3283:   my $result=&hashref2str(\%hash);
1.265     albertel 3284:   $result=~s/^__HASH_REF__//;
                   3285:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3286:   return $result;
                   3287: }
                   3288: 
                   3289: sub hashref2str {
                   3290:   my ($hashref)=@_;
1.265     albertel 3291:   my $result='__HASH_REF__';
1.800     albertel 3292:   foreach my $key (sort(keys(%$hashref))) {
                   3293:     if (ref($key) eq 'ARRAY') {
                   3294:       $result.=&arrayref2str($key).'=';
                   3295:     } elsif (ref($key) eq 'HASH') {
                   3296:       $result.=&hashref2str($key).'=';
                   3297:     } elsif (ref($key)) {
1.265     albertel 3298:       $result.='=';
1.800     albertel 3299:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3300:     } else {
1.800     albertel 3301: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3302:     }
                   3303: 
1.800     albertel 3304:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3305:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3306:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3307:       $result.=&hashref2str($hashref->{$key}).'&';
                   3308:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3309:        $result.='&';
1.800     albertel 3310:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3311:     } else {
1.800     albertel 3312:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3313:     }
                   3314:   }
1.168     albertel 3315:   $result=~s/\&$//;
1.265     albertel 3316:   $result .= '__END_HASH_REF__';
1.168     albertel 3317:   return $result;
                   3318: }
                   3319: 
                   3320: sub str2hash {
1.265     albertel 3321:     my ($string)=@_;
                   3322:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3323:     return %$hash;
                   3324: }
                   3325: 
                   3326: sub str2hashref {
1.168     albertel 3327:   my ($string) = @_;
1.265     albertel 3328: 
                   3329:   my %hash;
                   3330: 
                   3331:   if($string !~ /^__HASH_REF__/) {
                   3332:       if (! ($string eq '' || !defined($string))) {
                   3333: 	  $hash{'error'}='Not hash reference';
                   3334:       }
                   3335:       return (\%hash, $string);
                   3336:   }
                   3337: 
                   3338:   $string =~ s/^__HASH_REF__//;
                   3339: 
                   3340:   while($string !~ /^__END_HASH_REF__/) {
                   3341:       #key
                   3342:       my $key='';
                   3343:       if($string =~ /^__HASH_REF__/) {
                   3344:           ($key, $string)=&str2hashref($string);
                   3345:           if(defined($key->{'error'})) {
                   3346:               $hash{'error'}='Bad data';
                   3347:               return (\%hash, $string);
                   3348:           }
                   3349:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3350:           ($key, $string)=&str2arrayref($string);
                   3351:           if($key->[0] eq 'Array reference error') {
                   3352:               $hash{'error'}='Bad data';
                   3353:               return (\%hash, $string);
                   3354:           }
                   3355:       } else {
                   3356:           $string =~ s/^(.*?)=//;
1.267     albertel 3357: 	  $key=&unescape($1);
1.265     albertel 3358:       }
                   3359:       $string =~ s/^=//;
                   3360: 
                   3361:       #value
                   3362:       my $value='';
                   3363:       if($string =~ /^__HASH_REF__/) {
                   3364:           ($value, $string)=&str2hashref($string);
                   3365:           if(defined($value->{'error'})) {
                   3366:               $hash{'error'}='Bad data';
                   3367:               return (\%hash, $string);
                   3368:           }
                   3369:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3370:           ($value, $string)=&str2arrayref($string);
                   3371:           if($value->[0] eq 'Array reference error') {
                   3372:               $hash{'error'}='Bad data';
                   3373:               return (\%hash, $string);
                   3374:           }
                   3375:       } else {
                   3376: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3377:       }
                   3378:       $string =~ s/^&//;
                   3379: 
                   3380:       $hash{$key}=$value;
1.204     albertel 3381:   }
1.265     albertel 3382: 
                   3383:   $string =~ s/^__END_HASH_REF__//;
                   3384: 
                   3385:   return (\%hash, $string);
1.204     albertel 3386: }
                   3387: 
                   3388: sub str2array {
1.265     albertel 3389:     my ($string)=@_;
                   3390:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3391:     return @$array;
                   3392: }
                   3393: 
                   3394: sub str2arrayref {
1.204     albertel 3395:   my ($string) = @_;
1.265     albertel 3396:   my @array;
                   3397: 
                   3398:   if($string !~ /^__ARRAY_REF__/) {
                   3399:       if (! ($string eq '' || !defined($string))) {
                   3400: 	  $array[0]='Array reference error';
                   3401:       }
                   3402:       return (\@array, $string);
                   3403:   }
                   3404: 
                   3405:   $string =~ s/^__ARRAY_REF__//;
                   3406: 
                   3407:   while($string !~ /^__END_ARRAY_REF__/) {
                   3408:       my $value='';
                   3409:       if($string =~ /^__HASH_REF__/) {
                   3410:           ($value, $string)=&str2hashref($string);
                   3411:           if(defined($value->{'error'})) {
                   3412:               $array[0] ='Array reference error';
                   3413:               return (\@array, $string);
                   3414:           }
                   3415:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3416:           ($value, $string)=&str2arrayref($string);
                   3417:           if($value->[0] eq 'Array reference error') {
                   3418:               $array[0] ='Array reference error';
                   3419:               return (\@array, $string);
                   3420:           }
                   3421:       } else {
                   3422: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3423:       }
                   3424:       $string =~ s/^&//;
                   3425: 
                   3426:       push(@array, $value);
1.191     harris41 3427:   }
1.265     albertel 3428: 
                   3429:   $string =~ s/^__END_ARRAY_REF__//;
                   3430: 
                   3431:   return (\@array, $string);
1.168     albertel 3432: }
                   3433: 
1.167     albertel 3434: # -------------------------------------------------------------------Temp Store
                   3435: 
1.168     albertel 3436: sub tmpreset {
                   3437:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3438:   if (!$symb) {
                   3439:     $symb=&symbread();
1.620     albertel 3440:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3441:   }
                   3442:   $symb=escape($symb);
                   3443: 
1.620     albertel 3444:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3445:   $namespace=~s/\//\_/g;
                   3446:   $namespace=~s/\W//g;
                   3447: 
1.620     albertel 3448:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3449:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3450:   if ($domain eq 'public' && $stuname eq 'public') {
                   3451:       $stuname=$ENV{'REMOTE_ADDR'};
                   3452:   }
1.168     albertel 3453:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3454:   my %hash;
                   3455:   if (tie(%hash,'GDBM_File',
                   3456: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3457: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3458:     foreach my $key (keys(%hash)) {
1.180     albertel 3459:       if ($key=~ /:$symb/) {
1.168     albertel 3460: 	delete($hash{$key});
                   3461:       }
                   3462:     }
                   3463:   }
                   3464: }
                   3465: 
1.167     albertel 3466: sub tmpstore {
1.168     albertel 3467:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3468: 
                   3469:   if (!$symb) {
                   3470:     $symb=&symbread();
1.620     albertel 3471:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3472:   }
                   3473:   $symb=escape($symb);
                   3474: 
                   3475:   if (!$namespace) {
                   3476:     # I don't think we would ever want to store this for a course.
                   3477:     # it seems this will only be used if we don't have a course.
1.620     albertel 3478:     #$namespace=$env{'request.course.id'};
1.168     albertel 3479:     #if (!$namespace) {
1.620     albertel 3480:       $namespace=$env{'request.state'};
1.168     albertel 3481:     #}
                   3482:   }
                   3483:   $namespace=~s/\//\_/g;
                   3484:   $namespace=~s/\W//g;
1.620     albertel 3485:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3486:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3487:   if ($domain eq 'public' && $stuname eq 'public') {
                   3488:       $stuname=$ENV{'REMOTE_ADDR'};
                   3489:   }
1.168     albertel 3490:   my $now=time;
                   3491:   my %hash;
                   3492:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3493:   if (tie(%hash,'GDBM_File',
                   3494: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3495: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3496:     $hash{"version:$symb"}++;
                   3497:     my $version=$hash{"version:$symb"};
                   3498:     my $allkeys=''; 
                   3499:     foreach my $key (keys(%$storehash)) {
                   3500:       $allkeys.=$key.':';
1.591     albertel 3501:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3502:     }
                   3503:     $hash{"$version:$symb:timestamp"}=$now;
                   3504:     $allkeys.='timestamp';
                   3505:     $hash{"$version:keys:$symb"}=$allkeys;
                   3506:     if (untie(%hash)) {
                   3507:       return 'ok';
                   3508:     } else {
                   3509:       return "error:$!";
                   3510:     }
                   3511:   } else {
                   3512:     return "error:$!";
                   3513:   }
                   3514: }
1.167     albertel 3515: 
1.168     albertel 3516: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3517: 
1.168     albertel 3518: sub tmprestore {
                   3519:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3520: 
1.168     albertel 3521:   if (!$symb) {
                   3522:     $symb=&symbread();
1.620     albertel 3523:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3524:   }
                   3525:   $symb=escape($symb);
                   3526: 
1.620     albertel 3527:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3528: 
1.620     albertel 3529:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3530:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3531:   if ($domain eq 'public' && $stuname eq 'public') {
                   3532:       $stuname=$ENV{'REMOTE_ADDR'};
                   3533:   }
1.168     albertel 3534:   my %returnhash;
                   3535:   $namespace=~s/\//\_/g;
                   3536:   $namespace=~s/\W//g;
                   3537:   my %hash;
                   3538:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3539:   if (tie(%hash,'GDBM_File',
                   3540: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3541: 	  &GDBM_READER(),0640)) {
1.168     albertel 3542:     my $version=$hash{"version:$symb"};
                   3543:     $returnhash{'version'}=$version;
                   3544:     my $scope;
                   3545:     for ($scope=1;$scope<=$version;$scope++) {
                   3546:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3547:       my @keys=split(/:/,$vkeys);
                   3548:       my $key;
                   3549:       $returnhash{"$scope:keys"}=$vkeys;
                   3550:       foreach $key (@keys) {
1.591     albertel 3551: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3552: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3553:       }
                   3554:     }
1.168     albertel 3555:     if (!(untie(%hash))) {
                   3556:       return "error:$!";
                   3557:     }
                   3558:   } else {
                   3559:     return "error:$!";
                   3560:   }
                   3561:   return %returnhash;
1.167     albertel 3562: }
                   3563: 
1.9       www      3564: # ----------------------------------------------------------------------- Store
                   3565: 
                   3566: sub store {
1.124     www      3567:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3568:     my $home='';
                   3569: 
1.168     albertel 3570:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3571: 
1.213     www      3572:     $symb=&symbclean($symb);
1.122     albertel 3573:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3574: 
1.620     albertel 3575:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3576:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3577: 
                   3578:     &devalidate($symb,$stuname,$domain);
1.109     www      3579: 
                   3580:     $symb=escape($symb);
1.187     www      3581:     if (!$namespace) { 
1.620     albertel 3582:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3583:           return ''; 
                   3584:        } 
                   3585:     }
1.620     albertel 3586:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3587: 
                   3588:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3589:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3590: 
1.12      www      3591:     my $namevalue='';
1.800     albertel 3592:     foreach my $key (keys(%$storehash)) {
                   3593:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3594:     }
1.12      www      3595:     $namevalue=~s/\&$//;
1.187     www      3596:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3597:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3598: }
                   3599: 
1.47      www      3600: # -------------------------------------------------------------- Critical Store
                   3601: 
                   3602: sub cstore {
1.124     www      3603:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3604:     my $home='';
                   3605: 
1.168     albertel 3606:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3607: 
1.213     www      3608:     $symb=&symbclean($symb);
1.122     albertel 3609:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3610: 
1.620     albertel 3611:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3612:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3613: 
                   3614:     &devalidate($symb,$stuname,$domain);
1.109     www      3615: 
                   3616:     $symb=escape($symb);
1.187     www      3617:     if (!$namespace) { 
1.620     albertel 3618:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3619:           return ''; 
                   3620:        } 
                   3621:     }
1.620     albertel 3622:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3623: 
                   3624:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3625:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3626: 
1.47      www      3627:     my $namevalue='';
1.800     albertel 3628:     foreach my $key (keys(%$storehash)) {
                   3629:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3630:     }
1.47      www      3631:     $namevalue=~s/\&$//;
1.187     www      3632:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3633:     return critical
                   3634:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3635: }
                   3636: 
1.9       www      3637: # --------------------------------------------------------------------- Restore
                   3638: 
                   3639: sub restore {
1.124     www      3640:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3641:     my $home='';
                   3642: 
1.168     albertel 3643:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3644: 
1.122     albertel 3645:     if (!$symb) {
                   3646:       unless ($symb=escape(&symbread())) { return ''; }
                   3647:     } else {
1.213     www      3648:       $symb=&escape(&symbclean($symb));
1.122     albertel 3649:     }
1.188     www      3650:     if (!$namespace) { 
1.620     albertel 3651:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3652:           return ''; 
                   3653:        } 
                   3654:     }
1.620     albertel 3655:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3656:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3657:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3658:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3659: 
1.12      www      3660:     my %returnhash=();
1.800     albertel 3661:     foreach my $line (split(/\&/,$answer)) {
                   3662: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3663:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3664:     }
1.75      www      3665:     my $version;
                   3666:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3667:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3668:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3669:        }
1.75      www      3670:     }
1.13      www      3671:     return %returnhash;
1.34      www      3672: }
                   3673: 
                   3674: # ---------------------------------------------------------- Course Description
                   3675: 
                   3676: sub coursedescription {
1.731     albertel 3677:     my ($courseid,$args)=@_;
1.34      www      3678:     $courseid=~s/^\///;
1.49      www      3679:     $courseid=~s/\_/\//g;
1.34      www      3680:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3681:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3682:     my $normalid=$cdomain.'_'.$cnum;
                   3683:     # need to always cache even if we get errors otherwise we keep 
                   3684:     # trying and trying and trying to get the course description.
                   3685:     my %envhash=();
                   3686:     my %returnhash=();
1.731     albertel 3687:     
                   3688:     my $expiretime=600;
                   3689:     if ($env{'request.course.id'} eq $normalid) {
                   3690: 	$expiretime=120;
                   3691:     }
                   3692: 
                   3693:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3694:     if (!$args->{'freshen_cache'}
                   3695: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3696: 	foreach my $key (keys(%env)) {
                   3697: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3698: 	    my ($setting) = $1;
                   3699: 	    $returnhash{$setting} = $env{$key};
                   3700: 	}
                   3701: 	return %returnhash;
                   3702:     }
                   3703: 
                   3704:     # get the data agin
                   3705:     if (!$args->{'one_time'}) {
                   3706: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3707:     }
1.811     albertel 3708: 
1.34      www      3709:     if ($chome ne 'no_host') {
1.302     albertel 3710:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3711:        if (!exists($returnhash{'con_lost'})) {
                   3712:            $returnhash{'home'}= $chome;
                   3713: 	   $returnhash{'domain'} = $cdomain;
                   3714: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3715:            if (!defined($returnhash{'type'})) {
                   3716:                $returnhash{'type'} = 'Course';
                   3717:            }
1.130     albertel 3718:            while (my ($name,$value) = each %returnhash) {
1.53      www      3719:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3720:            }
1.270     www      3721:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3722:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3723: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3724:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3725:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3726:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3727:        }
                   3728:     }
1.731     albertel 3729:     if (!$args->{'one_time'}) {
1.949     raeburn  3730: 	&appenv(\%envhash);
1.731     albertel 3731:     }
1.302     albertel 3732:     return %returnhash;
1.461     www      3733: }
                   3734: 
                   3735: # -------------------------------------------------See if a user is privileged
                   3736: 
                   3737: sub privileged {
                   3738:     my ($username,$domain)=@_;
                   3739:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3740: 			&homeserver($username,$domain));
                   3741:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3742:     my $now=time;
                   3743:     if ($rolesdump ne '') {
1.800     albertel 3744:         foreach my $entry (split(/&/,$rolesdump)) {
                   3745: 	    if ($entry!~/^rolesdef_/) {
                   3746: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3747: 		$area=~s/\_\w\w$//;
                   3748: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3749: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3750: 		    my $active=1;
                   3751: 		    if ($tend) {
                   3752: 			if ($tend<$now) { $active=0; }
                   3753: 		    }
                   3754: 		    if ($tstart) {
                   3755: 			if ($tstart>$now) { $active=0; }
                   3756: 		    }
                   3757: 		    if ($active) { return 1; }
                   3758: 		}
                   3759: 	    }
                   3760: 	}
                   3761:     }
                   3762:     return 0;
1.9       www      3763: }
1.1       albertel 3764: 
1.103     harris41 3765: # -------------------------------------------------------- Get user privileges
1.11      www      3766: 
                   3767: sub rolesinit {
                   3768:     my ($domain,$username,$authhost)=@_;
1.966     raeburn  3769:     my %userroles;
1.11      www      3770:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.966     raeburn  3771:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
1.11      www      3772:     my %allroles=();
1.678     raeburn  3773:     my %allgroups=();   
1.11      www      3774:     my $now=time;
1.966     raeburn  3775:     %userroles = ('user.login.time' => $now);
1.678     raeburn  3776:     my $group_privs;
1.11      www      3777: 
                   3778:     if ($rolesdump ne '') {
1.800     albertel 3779:         foreach my $entry (split(/&/,$rolesdump)) {
                   3780: 	  if ($entry!~/^rolesdef_/) {
                   3781:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3782: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3783:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3784: 	    if ($role=~/^cr/) { 
1.807     albertel 3785: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3786: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3787: 		    ($tend,$tstart)=split('_',$trest);
                   3788: 		} else {
                   3789: 		    $trole=$role;
                   3790: 		}
1.678     raeburn  3791:             } elsif ($role =~ m|^gr/|) {
                   3792:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3793:                 ($trole,$group_privs) = split(/\//,$trole);
                   3794:                 $group_privs = &unescape($group_privs);
1.587     albertel 3795: 	    } else {
                   3796: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3797: 	    }
1.743     albertel 3798: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3799: 					 $username);
                   3800: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3801:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3802:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3803:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3804: 		my $spec=$trole.'.'.$area;
                   3805: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3806: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3807:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3808:                 } elsif ($trole eq 'gr') {
                   3809:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3810: 		} else {
1.567     raeburn  3811:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3812: 		}
1.12      www      3813:             }
1.662     raeburn  3814:           }
1.191     harris41 3815:         }
1.743     albertel 3816:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3817:         $userroles{'user.adv'}    = $adv;
                   3818: 	$userroles{'user.author'} = $author;
1.620     albertel 3819:         $env{'user.adv'}=$adv;
1.11      www      3820:     }
1.743     albertel 3821:     return \%userroles;  
1.11      www      3822: }
                   3823: 
1.567     raeburn  3824: sub set_arearole {
                   3825:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3826: # log the associated role with the area
                   3827:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3828:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3829: }
                   3830: 
                   3831: sub custom_roleprivs {
                   3832:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3833:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3834:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3835:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3836:         my ($rdummy,$roledef)=
                   3837:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3838:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3839:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3840:             if (defined($syspriv)) {
                   3841:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3842:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3843:             }
                   3844:             if ($tdomain ne '') {
                   3845:                 if (defined($dompriv)) {
                   3846:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3847:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3848:                 }
                   3849:                 if (($trest ne '') && (defined($coursepriv))) {
                   3850:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3851:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3852:                 }
                   3853:             }
                   3854:         }
                   3855:     }
                   3856: }
                   3857: 
1.678     raeburn  3858: sub group_roleprivs {
                   3859:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3860:     my $access = 1;
                   3861:     my $now = time;
                   3862:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3863:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3864:     if ($access) {
1.811     albertel 3865:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3866:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3867:     }
                   3868: }
1.567     raeburn  3869: 
                   3870: sub standard_roleprivs {
                   3871:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3872:     if (defined($pr{$trole.':s'})) {
                   3873:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3874:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3875:     }
                   3876:     if ($tdomain ne '') {
                   3877:         if (defined($pr{$trole.':d'})) {
                   3878:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3879:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3880:         }
                   3881:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3882:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3883:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3884:         }
                   3885:     }
                   3886: }
                   3887: 
                   3888: sub set_userprivs {
1.678     raeburn  3889:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3890:     my $author=0;
                   3891:     my $adv=0;
1.678     raeburn  3892:     my %grouproles = ();
                   3893:     if (keys(%{$allgroups}) > 0) {
1.1000    raeburn  3894:         foreach my $role (keys(%{$allroles})) {
1.681     raeburn  3895:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3896:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3897:                 $trole = $1;
                   3898:                 $area = $2;
1.681     raeburn  3899:                 $sec = $3;
                   3900:                 $extendedarea = $area.$sec;
                   3901:                 if (exists($$allgroups{$area})) {
                   3902:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3903:                         my $spec = $trole.'.'.$extendedarea;
                   3904:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3905:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3906:                     }
                   3907:                 }
                   3908:             }
                   3909:         }
                   3910:     }
1.800     albertel 3911:     foreach my $group (keys(%grouproles)) {
                   3912:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3913:     }
1.800     albertel 3914:     foreach my $role (keys(%{$allroles})) {
                   3915:         my %thesepriv;
1.941     raeburn  3916:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3917:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3918:             if ($item ne '') {
                   3919:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3920:                 if ($restrictions eq '') {
                   3921:                     $thesepriv{$privilege}='F';
                   3922:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3923:                     $thesepriv{$privilege}.=$restrictions;
                   3924:                 }
                   3925:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3926:             }
                   3927:         }
                   3928:         my $thesestr='';
1.800     albertel 3929:         foreach my $priv (keys(%thesepriv)) {
                   3930: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3931: 	}
                   3932:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3933:     }
                   3934:     return ($author,$adv);
                   3935: }
                   3936: 
1.994     raeburn  3937: sub role_status {
1.1002    raeburn  3938:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  3939:     my @pwhere = ();
                   3940:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   3941:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   3942:         unless (!defined($$role) || $$role eq '') {
                   3943:             $$where=join('.',@pwhere);
                   3944:             $$trolecode=$$role.'.'.$$where;
                   3945:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   3946:             $$tstatus='is';
                   3947:             if ($$tstart && $$tstart>$then) {
                   3948:                 $$tstatus='future';
1.1002    raeburn  3949:                 if ($$tstart && $$tstart>$refresh) {
                   3950:                     if ($$tstart<$now) {
                   3951:                         if (($$where ne '') && ($$role ne '')) {
                   3952:                             my (%allroles,%allgroups,$group_privs);
                   3953:                             my %userroles = (
                   3954:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   3955:                             );
                   3956:                             my $spec=$$role.'.'.$$where;
                   3957:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   3958:                             if ($$role eq 'gr') {
                   3959:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   3960:                                                     $env{'user.name'})=@_;
                   3961:                                 my ($trole) = split('_',$role,1);
                   3962:                                 (undef,my $group_privs) = split(/\//,$trole);
                   3963:                                 $group_privs = &unescape($group_privs);
                   3964:                             }
                   3965:                             if ($$role =~ /^cr\//) {
                   3966:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
                   3967:                             } elsif ($$role eq 'gr') {
                   3968:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   3969:                                                     $env{'user.name'});
                   3970:                                 my $trole = split('_',$rolehash{$$where.'_'.$$role},1);
                   3971:                                 (undef,my $group_privs) = split(/\//,$trole);
                   3972:                                 $group_privs = &unescape($group_privs);
                   3973:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
                   3974:                             } else {
                   3975:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   3976:                             }
                   3977:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3978:                             &appenv(\%userroles,[$$role,'cm']);
                   3979:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   3980:                             $$tstatus = 'is';
                   3981:                         }
                   3982:                     }
                   3983:                 }
1.994     raeburn  3984:             }
                   3985:             if ($$tend) {
                   3986:                 if ($$tend<$then) {
                   3987:                     $$tstatus='expired';
                   3988:                 } elsif ($$tend<$now) {
                   3989:                     $$tstatus='will_not';
                   3990:                 }
                   3991:             }
                   3992:         }
                   3993:     }
                   3994: }
                   3995: 
                   3996: sub check_adhoc_privs {
1.1002    raeburn  3997:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
1.994     raeburn  3998:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   3999:     if ($env{$cckey}) {
                   4000:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002    raeburn  4001:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4002:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
                   4003:             &set_adhoc_privileges($cdom,$cnum,$checkrole);
                   4004:         }
                   4005:     } else {
                   4006:         &set_adhoc_privileges($cdom,$cnum,$checkrole);
                   4007:     }
                   4008: }
                   4009: 
                   4010: sub set_adhoc_privileges {
                   4011: # role can be cc or ca
                   4012:     my ($dcdom,$pickedcourse,$role) = @_;
                   4013:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4014:     my $spec = $role.'.'.$area;
                   4015:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4016:                                   $env{'user.name'});
                   4017:     my %ccrole = ();
                   4018:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4019:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4020:     &appenv(\%userroles,[$role,'cm']);
                   4021:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4022:     &appenv( {'request.role'        => $spec,
                   4023:               'request.role.domain' => $dcdom,
                   4024:               'request.course.sec'  => ''
                   4025:              }
                   4026:            );
                   4027:     my $tadv=0;
                   4028:     if (&allowed('adv') eq 'F') { $tadv=1; }
                   4029:     &appenv({'request.role.adv'    => $tadv});
                   4030: }
                   4031: 
1.12      www      4032: # --------------------------------------------------------------- get interface
                   4033: 
                   4034: sub get {
1.131     albertel 4035:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4036:    my $items='';
1.800     albertel 4037:    foreach my $item (@$storearr) {
                   4038:        $items.=&escape($item).'&';
1.191     harris41 4039:    }
1.12      www      4040:    $items=~s/\&$//;
1.620     albertel 4041:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4042:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4043:    my $uhome=&homeserver($uname,$udomain);
                   4044: 
1.133     albertel 4045:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4046:    my @pairs=split(/\&/,$rep);
1.273     albertel 4047:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4048:      return @pairs;
                   4049:    }
1.15      www      4050:    my %returnhash=();
1.42      www      4051:    my $i=0;
1.800     albertel 4052:    foreach my $item (@$storearr) {
                   4053:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4054:       $i++;
1.191     harris41 4055:    }
1.15      www      4056:    return %returnhash;
1.27      www      4057: }
                   4058: 
                   4059: # --------------------------------------------------------------- del interface
                   4060: 
                   4061: sub del {
1.133     albertel 4062:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4063:    my $items='';
1.800     albertel 4064:    foreach my $item (@$storearr) {
                   4065:        $items.=&escape($item).'&';
1.191     harris41 4066:    }
1.984     neumanie 4067: 
1.27      www      4068:    $items=~s/\&$//;
1.620     albertel 4069:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4070:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4071:    my $uhome=&homeserver($uname,$udomain);
                   4072:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4073: }
                   4074: 
                   4075: # -------------------------------------------------------------- dump interface
                   4076: 
                   4077: sub dump {
1.755     albertel 4078:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   4079:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4080:     if (!$uname) { $uname=$env{'user.name'}; }
                   4081:     my $uhome=&homeserver($uname,$udomain);
                   4082:     if ($regexp) {
                   4083: 	$regexp=&escape($regexp);
                   4084:     } else {
                   4085: 	$regexp='.';
                   4086:     }
                   4087:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4088:     my @pairs=split(/\&/,$rep);
                   4089:     my %returnhash=();
                   4090:     foreach my $item (@pairs) {
                   4091: 	my ($key,$value)=split(/=/,$item,2);
                   4092: 	$key = &unescape($key);
                   4093: 	next if ($key =~ /^error: 2 /);
                   4094: 	$returnhash{$key}=&thaw_unescape($value);
                   4095:     }
                   4096:     return %returnhash;
1.407     www      4097: }
                   4098: 
1.717     albertel 4099: # --------------------------------------------------------- dumpstore interface
                   4100: 
                   4101: sub dumpstore {
                   4102:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4103:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4104:    if (!$uname) { $uname=$env{'user.name'}; }
                   4105:    my $uhome=&homeserver($uname,$udomain);
                   4106:    if ($regexp) {
                   4107:        $regexp=&escape($regexp);
                   4108:    } else {
                   4109:        $regexp='.';
                   4110:    }
                   4111:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4112:    my @pairs=split(/\&/,$rep);
                   4113:    my %returnhash=();
                   4114:    foreach my $item (@pairs) {
                   4115:        my ($key,$value)=split(/=/,$item,2);
                   4116:        next if ($key =~ /^error: 2 /);
                   4117:        $returnhash{$key}=&thaw_unescape($value);
                   4118:    }
                   4119:    return %returnhash;
1.717     albertel 4120: }
                   4121: 
1.407     www      4122: # -------------------------------------------------------------- keys interface
                   4123: 
                   4124: sub getkeys {
                   4125:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4126:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4127:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4128:    my $uhome=&homeserver($uname,$udomain);
                   4129:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4130:    my @keyarray=();
1.800     albertel 4131:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4132:       next if ($key =~ /^error: 2 /);
1.800     albertel 4133:       push(@keyarray,&unescape($key));
1.407     www      4134:    }
                   4135:    return @keyarray;
1.318     matthew  4136: }
                   4137: 
1.319     matthew  4138: # --------------------------------------------------------------- currentdump
                   4139: sub currentdump {
1.328     matthew  4140:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4141:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4142:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4143:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4144:    my $uhome = &homeserver($sname,$sdom);
                   4145:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4146:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4147:    #
1.318     matthew  4148:    my %returnhash=();
1.319     matthew  4149:    #
                   4150:    if ($rep eq "unknown_cmd") { 
                   4151:        # an old lond will not know currentdump
                   4152:        # Do a dump and make it look like a currentdump
1.822     albertel 4153:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4154:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4155:        my %hash = @tmp;
                   4156:        @tmp=();
1.424     matthew  4157:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4158:    } else {
                   4159:        my @pairs=split(/\&/,$rep);
1.800     albertel 4160:        foreach my $pair (@pairs) {
                   4161:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4162:            my ($symb,$param) = split(/:/,$key);
                   4163:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4164:                                                         &thaw_unescape($value);
1.319     matthew  4165:        }
1.191     harris41 4166:    }
1.12      www      4167:    return %returnhash;
1.424     matthew  4168: }
                   4169: 
                   4170: sub convert_dump_to_currentdump{
                   4171:     my %hash = %{shift()};
                   4172:     my %returnhash;
                   4173:     # Code ripped from lond, essentially.  The only difference
                   4174:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4175:     # we might run in to problems with parameter names =~ /^v\./
                   4176:     while (my ($key,$value) = each(%hash)) {
                   4177:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4178: 	$symb  = &unescape($symb);
                   4179: 	$param = &unescape($param);
1.424     matthew  4180:         next if ($v eq 'version' || $symb eq 'keys');
                   4181:         next if (exists($returnhash{$symb}) &&
                   4182:                  exists($returnhash{$symb}->{$param}) &&
                   4183:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4184:         $returnhash{$symb}->{$param}=$value;
                   4185:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4186:     }
                   4187:     #
                   4188:     # Remove all of the keys in the hashes which keep track of
                   4189:     # the version of the parameter.
                   4190:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4191:         # use a foreach because we are going to delete from the hash.
                   4192:         foreach my $key (keys(%$param_hash)) {
                   4193:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4194:         }
                   4195:     }
                   4196:     return \%returnhash;
1.12      www      4197: }
                   4198: 
1.627     albertel 4199: # ------------------------------------------------------ critical inc interface
                   4200: 
                   4201: sub cinc {
                   4202:     return &inc(@_,'critical');
                   4203: }
                   4204: 
1.449     matthew  4205: # --------------------------------------------------------------- inc interface
                   4206: 
                   4207: sub inc {
1.627     albertel 4208:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4209:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4210:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4211:     my $uhome=&homeserver($uname,$udomain);
                   4212:     my $items='';
                   4213:     if (! ref($store)) {
                   4214:         # got a single value, so use that instead
                   4215:         $items = &escape($store).'=&';
                   4216:     } elsif (ref($store) eq 'SCALAR') {
                   4217:         $items = &escape($$store).'=&';        
                   4218:     } elsif (ref($store) eq 'ARRAY') {
                   4219:         $items = join('=&',map {&escape($_);} @{$store});
                   4220:     } elsif (ref($store) eq 'HASH') {
                   4221:         while (my($key,$value) = each(%{$store})) {
                   4222:             $items.= &escape($key).'='.&escape($value).'&';
                   4223:         }
                   4224:     }
                   4225:     $items=~s/\&$//;
1.627     albertel 4226:     if ($critical) {
                   4227: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4228:     } else {
                   4229: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4230:     }
1.449     matthew  4231: }
                   4232: 
1.12      www      4233: # --------------------------------------------------------------- put interface
                   4234: 
                   4235: sub put {
1.134     albertel 4236:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4237:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4238:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4239:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4240:    my $items='';
1.800     albertel 4241:    foreach my $item (keys(%$storehash)) {
                   4242:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4243:    }
1.12      www      4244:    $items=~s/\&$//;
1.134     albertel 4245:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4246: }
                   4247: 
1.631     albertel 4248: # ------------------------------------------------------------ newput interface
                   4249: 
                   4250: sub newput {
                   4251:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4252:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4253:    if (!$uname) { $uname=$env{'user.name'}; }
                   4254:    my $uhome=&homeserver($uname,$udomain);
                   4255:    my $items='';
                   4256:    foreach my $key (keys(%$storehash)) {
                   4257:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4258:    }
                   4259:    $items=~s/\&$//;
                   4260:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4261: }
                   4262: 
                   4263: # ---------------------------------------------------------  putstore interface
                   4264: 
1.524     raeburn  4265: sub putstore {
1.715     albertel 4266:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4267:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4268:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4269:    my $uhome=&homeserver($uname,$udomain);
                   4270:    my $items='';
1.715     albertel 4271:    foreach my $key (keys(%$storehash)) {
                   4272:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4273:    }
1.715     albertel 4274:    $items=~s/\&$//;
1.716     albertel 4275:    my $esc_symb=&escape($symb);
                   4276:    my $esc_v=&escape($version);
1.715     albertel 4277:    my $reply =
1.716     albertel 4278:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4279: 	      $uhome);
                   4280:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4281:        # gfall back to way things use to be done
1.715     albertel 4282:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4283: 			    $uname);
1.524     raeburn  4284:    }
1.715     albertel 4285:    return $reply;
                   4286: }
                   4287: 
                   4288: sub old_putstore {
1.716     albertel 4289:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4290:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4291:     if (!$uname) { $uname=$env{'user.name'}; }
                   4292:     my $uhome=&homeserver($uname,$udomain);
                   4293:     my %newstorehash;
1.800     albertel 4294:     foreach my $item (keys(%$storehash)) {
                   4295: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4296: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4297:     }
                   4298:     my $items='';
                   4299:     my %allitems = ();
1.800     albertel 4300:     foreach my $item (keys(%newstorehash)) {
                   4301: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4302: 	    my $key = $1.':keys:'.$2;
                   4303: 	    $allitems{$key} .= $3.':';
                   4304: 	}
1.800     albertel 4305: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4306:     }
1.800     albertel 4307:     foreach my $item (keys(%allitems)) {
                   4308: 	$allitems{$item} =~ s/\:$//;
                   4309: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4310:     }
                   4311:     $items=~s/\&$//;
                   4312:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4313: }
                   4314: 
1.47      www      4315: # ------------------------------------------------------ critical put interface
                   4316: 
                   4317: sub cput {
1.134     albertel 4318:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4319:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4320:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4321:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4322:    my $items='';
1.800     albertel 4323:    foreach my $item (keys(%$storehash)) {
                   4324:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4325:    }
1.47      www      4326:    $items=~s/\&$//;
1.134     albertel 4327:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4328: }
                   4329: 
                   4330: # -------------------------------------------------------------- eget interface
                   4331: 
                   4332: sub eget {
1.133     albertel 4333:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4334:    my $items='';
1.800     albertel 4335:    foreach my $item (@$storearr) {
                   4336:        $items.=&escape($item).'&';
1.191     harris41 4337:    }
1.12      www      4338:    $items=~s/\&$//;
1.620     albertel 4339:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4340:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4341:    my $uhome=&homeserver($uname,$udomain);
                   4342:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4343:    my @pairs=split(/\&/,$rep);
                   4344:    my %returnhash=();
1.42      www      4345:    my $i=0;
1.800     albertel 4346:    foreach my $item (@$storearr) {
                   4347:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4348:       $i++;
1.191     harris41 4349:    }
1.12      www      4350:    return %returnhash;
                   4351: }
                   4352: 
1.667     albertel 4353: # ------------------------------------------------------------ tmpput interface
                   4354: sub tmpput {
1.802     raeburn  4355:     my ($storehash,$server,$context)=@_;
1.667     albertel 4356:     my $items='';
1.800     albertel 4357:     foreach my $item (keys(%$storehash)) {
                   4358: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4359:     }
                   4360:     $items=~s/\&$//;
1.802     raeburn  4361:     if (defined($context)) {
                   4362:         $items .= ':'.&escape($context);
                   4363:     }
1.667     albertel 4364:     return &reply("tmpput:$items",$server);
                   4365: }
                   4366: 
                   4367: # ------------------------------------------------------------ tmpget interface
                   4368: sub tmpget {
1.688     albertel 4369:     my ($token,$server)=@_;
                   4370:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4371:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4372:     my %returnhash;
                   4373:     foreach my $item (split(/\&/,$rep)) {
                   4374: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4375:         next if ($key =~ /^error: 2 /);
1.667     albertel 4376: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4377:     }
                   4378:     return %returnhash;
                   4379: }
                   4380: 
1.688     albertel 4381: # ------------------------------------------------------------ tmpget interface
                   4382: sub tmpdel {
                   4383:     my ($token,$server)=@_;
                   4384:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4385:     return &reply("tmpdel:$token",$server);
                   4386: }
                   4387: 
1.765     albertel 4388: # -------------------------------------------------- portfolio access checking
                   4389: 
                   4390: sub portfolio_access {
1.766     albertel 4391:     my ($requrl) = @_;
1.765     albertel 4392:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4393:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4394:     if ($result) {
                   4395:         my %setters;
                   4396:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4397:             my ($startblock,$endblock) =
                   4398:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4399:             if ($startblock && $endblock) {
                   4400:                 return 'B';
                   4401:             }
                   4402:         } else {
                   4403:             my ($startblock,$endblock) =
                   4404:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4405:             if ($startblock && $endblock) {
                   4406:                 return 'B';
                   4407:             }
                   4408:         }
                   4409:     }
1.765     albertel 4410:     if ($result eq 'ok') {
1.766     albertel 4411:        return 'F';
1.765     albertel 4412:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4413:        return 'A';
1.765     albertel 4414:     }
1.766     albertel 4415:     return '';
1.765     albertel 4416: }
                   4417: 
                   4418: sub get_portfolio_access {
1.767     albertel 4419:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4420: 
                   4421:     if (!ref($access_hash)) {
                   4422: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4423: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4424: 						   $file_name);
                   4425: 	$access_hash = $access_controls{$file_name};
                   4426:     }
                   4427: 
1.765     albertel 4428:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4429:     my $now = time;
                   4430:     if (ref($access_hash) eq 'HASH') {
                   4431:         foreach my $key (keys(%{$access_hash})) {
                   4432:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4433:             if ($start > $now) {
                   4434:                 next;
                   4435:             }
                   4436:             if ($end && $end<$now) {
                   4437:                 next;
                   4438:             }
                   4439:             if ($scope eq 'public') {
                   4440:                 $public = $key;
                   4441:                 last;
                   4442:             } elsif ($scope eq 'guest') {
                   4443:                 $guest = $key;
                   4444:             } elsif ($scope eq 'domains') {
                   4445:                 push(@domains,$key);
                   4446:             } elsif ($scope eq 'users') {
                   4447:                 push(@users,$key);
                   4448:             } elsif ($scope eq 'course') {
                   4449:                 push(@courses,$key);
                   4450:             } elsif ($scope eq 'group') {
                   4451:                 push(@groups,$key);
                   4452:             }
                   4453:         }
                   4454:         if ($public) {
                   4455:             return 'ok';
                   4456:         }
                   4457:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4458:             if ($guest) {
                   4459:                 return $guest;
                   4460:             }
                   4461:         } else {
                   4462:             if (@domains > 0) {
                   4463:                 foreach my $domkey (@domains) {
                   4464:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4465:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4466:                             return 'ok';
                   4467:                         }
                   4468:                     }
                   4469:                 }
                   4470:             }
                   4471:             if (@users > 0) {
                   4472:                 foreach my $userkey (@users) {
1.865     raeburn  4473:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4474:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4475:                             if (ref($item) eq 'HASH') {
                   4476:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4477:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4478:                                     return 'ok';
                   4479:                                 }
                   4480:                             }
                   4481:                         }
                   4482:                     } 
1.765     albertel 4483:                 }
                   4484:             }
                   4485:             my %roleshash;
                   4486:             my @courses_and_groups = @courses;
                   4487:             push(@courses_and_groups,@groups); 
                   4488:             if (@courses_and_groups > 0) {
                   4489:                 my (%allgroups,%allroles); 
                   4490:                 my ($start,$end,$role,$sec,$group);
                   4491:                 foreach my $envkey (%env) {
1.811     albertel 4492:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4493:                         my $cid = $2.'_'.$3; 
                   4494:                         if ($1 eq 'gr') {
                   4495:                             $group = $4;
                   4496:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4497:                         } else {
                   4498:                             if ($4 eq '') {
                   4499:                                 $sec = 'none';
                   4500:                             } else {
                   4501:                                 $sec = $4;
                   4502:                             }
                   4503:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4504:                         }
1.811     albertel 4505:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4506:                         my $cid = $2.'_'.$3;
                   4507:                         if ($4 eq '') {
                   4508:                             $sec = 'none';
                   4509:                         } else {
                   4510:                             $sec = $4;
                   4511:                         }
                   4512:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4513:                     }
                   4514:                 }
                   4515:                 if (keys(%allroles) == 0) {
                   4516:                     return;
                   4517:                 }
                   4518:                 foreach my $key (@courses_and_groups) {
                   4519:                     my %content = %{$$access_hash{$key}};
                   4520:                     my $cnum = $content{'number'};
                   4521:                     my $cdom = $content{'domain'};
                   4522:                     my $cid = $cdom.'_'.$cnum;
                   4523:                     if (!exists($allroles{$cid})) {
                   4524:                         next;
                   4525:                     }    
                   4526:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4527:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4528:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4529:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4530:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4531:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4532:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4533:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4534:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4535:                                         if (grep/^all$/,@sections) {
                   4536:                                             return 'ok';
                   4537:                                         } else {
                   4538:                                             if (grep/^$sec$/,@sections) {
                   4539:                                                 return 'ok';
                   4540:                                             }
                   4541:                                         }
                   4542:                                     }
                   4543:                                 }
                   4544:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4545:                                     if (grep/^none$/,@groups) {
                   4546:                                         return 'ok';
                   4547:                                     }
                   4548:                                 } else {
                   4549:                                     if (grep/^all$/,@groups) {
                   4550:                                         return 'ok';
                   4551:                                     } 
                   4552:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4553:                                         if (grep/^$group$/,@groups) {
                   4554:                                             return 'ok';
                   4555:                                         }
                   4556:                                     }
                   4557:                                 } 
                   4558:                             }
                   4559:                         }
                   4560:                     }
                   4561:                 }
                   4562:             }
                   4563:             if ($guest) {
                   4564:                 return $guest;
                   4565:             }
                   4566:         }
                   4567:     }
                   4568:     return;
                   4569: }
                   4570: 
                   4571: sub course_group_datechecker {
                   4572:     my ($dates,$now,$status) = @_;
                   4573:     my ($start,$end) = split(/\./,$dates);
                   4574:     if (!$start && !$end) {
                   4575:         return 'ok';
                   4576:     }
                   4577:     if (grep/^active$/,@{$status}) {
                   4578:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4579:             return 'ok';
                   4580:         }
                   4581:     }
                   4582:     if (grep/^previous$/,@{$status}) {
                   4583:         if ($end > $now ) {
                   4584:             return 'ok';
                   4585:         }
                   4586:     }
                   4587:     if (grep/^future$/,@{$status}) {
                   4588:         if ($start > $now) {
                   4589:             return 'ok';
                   4590:         }
                   4591:     }
                   4592:     return; 
                   4593: }
                   4594: 
                   4595: sub parse_portfolio_url {
                   4596:     my ($url) = @_;
                   4597: 
                   4598:     my ($type,$udom,$unum,$group,$file_name);
                   4599:     
1.823     albertel 4600:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4601: 	$type = 1;
                   4602:         $udom = $1;
                   4603:         $unum = $2;
                   4604:         $file_name = $3;
1.823     albertel 4605:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4606: 	$type = 2;
                   4607:         $udom = $1;
                   4608:         $unum = $2;
                   4609:         $group = $3;
                   4610:         $file_name = $3.'/'.$4;
                   4611:     }
                   4612:     if (wantarray) {
                   4613: 	return ($type,$udom,$unum,$file_name,$group);
                   4614:     }
                   4615:     return $type;
                   4616: }
                   4617: 
                   4618: sub is_portfolio_url {
                   4619:     my ($url) = @_;
                   4620:     return scalar(&parse_portfolio_url($url));
                   4621: }
                   4622: 
1.798     raeburn  4623: sub is_portfolio_file {
                   4624:     my ($file) = @_;
1.820     raeburn  4625:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4626:         return 1;
                   4627:     }
                   4628:     return;
                   4629: }
                   4630: 
1.976     raeburn  4631: sub usertools_access {
1.985     raeburn  4632:     my ($uname,$udom,$tool,$action,$context) = @_;
                   4633:     my ($access,%tools);
                   4634:     if ($context eq '') {
                   4635:         $context = 'tools';
                   4636:     }
                   4637:     if ($context eq 'requestcourses') {
                   4638:         %tools = (
                   4639:                       official   => 1,
                   4640:                       unofficial => 1,
1.1006    raeburn  4641:                       community  => 1,
1.985     raeburn  4642:                  );
                   4643:     } else {
                   4644:         %tools = (
                   4645:                       aboutme   => 1,
                   4646:                       blog      => 1,
                   4647:                       portfolio => 1,
                   4648:                  );
                   4649:     }
1.976     raeburn  4650:     return if (!defined($tools{$tool}));
                   4651: 
                   4652:     if ((!defined($udom)) || (!defined($uname))) {
                   4653:         $udom = $env{'user.domain'};
                   4654:         $uname = $env{'user.name'};
                   4655:     }
                   4656: 
1.978     raeburn  4657:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4658:         if ($action ne 'reload') {
1.985     raeburn  4659:             if ($context eq 'requestcourses') {
                   4660:                 return $env{'environment.canrequest.'.$tool};
                   4661:             } else {
                   4662:                 return $env{'environment.availabletools.'.$tool};
                   4663:             }
                   4664:         }
1.976     raeburn  4665:     }
                   4666: 
                   4667:     my ($toolstatus,$inststatus);
                   4668: 
1.985     raeburn  4669:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   4670:          ($action ne 'reload')) {
                   4671:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  4672:         $inststatus = $env{'environment.inststatus'};
                   4673:     } else {
1.985     raeburn  4674:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool);
                   4675:         $toolstatus = $userenv{$context.'.'.$tool};
1.976     raeburn  4676:         $inststatus = $userenv{'inststatus'};
                   4677:     }
                   4678: 
                   4679:     if ($toolstatus ne '') {
                   4680:         if ($toolstatus) {
                   4681:             $access = 1;
                   4682:         } else {
                   4683:             $access = 0;
                   4684:         }
                   4685:         return $access;
                   4686:     }
                   4687: 
                   4688:     my $is_adv = &is_advanced_user($udom,$uname);
                   4689:     my %domdef = &get_domain_defaults($udom);
                   4690:     if (ref($domdef{$tool}) eq 'HASH') {
                   4691:         if ($is_adv) {
                   4692:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   4693:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   4694:                     $access = 1;
                   4695:                 } else {
                   4696:                     $access = 0;
                   4697:                 }
                   4698:                 return $access;
                   4699:             }
                   4700:         }
                   4701:         if ($inststatus ne '') {
                   4702:             my ($hasaccess,$hasnoaccess);
                   4703:             foreach my $affiliation (split(/:/,$inststatus)) {
                   4704:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   4705:                     if ($domdef{$tool}{$affiliation}) {
                   4706:                         $hasaccess = 1;
                   4707:                     } else {
                   4708:                         $hasnoaccess = 1;
                   4709:                     }
                   4710:                 }
                   4711:             }
                   4712:             if ($hasaccess || $hasnoaccess) {
                   4713:                 if ($hasaccess) {
                   4714:                     $access = 1;
                   4715:                 } elsif ($hasnoaccess) {
                   4716:                     $access = 0; 
                   4717:                 }
                   4718:                 return $access;
                   4719:             }
                   4720:         } else {
                   4721:             if ($domdef{$tool}{'default'} ne '') {
                   4722:                 if ($domdef{$tool}{'default'}) {
                   4723:                     $access = 1;
                   4724:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   4725:                     $access = 0;
                   4726:                 }
                   4727:                 return $access;
                   4728:             }
                   4729:         }
                   4730:     } else {
1.985     raeburn  4731:         if ($context eq 'tools') {
                   4732:             $access = 1;
                   4733:         } else {
                   4734:             $access = 0;
                   4735:         }
1.976     raeburn  4736:         return $access;
                   4737:     }
                   4738: }
                   4739: 
                   4740: sub is_advanced_user {
                   4741:     my ($udom,$uname) = @_;
                   4742:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   4743:     my %allroles;
                   4744:     my $is_adv;
                   4745:     foreach my $role (keys(%roleshash)) {
                   4746:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   4747:         my $area = '/'.$tdomain.'/'.$trest;
                   4748:         if ($sec ne '') {
                   4749:             $area .= '/'.$sec;
                   4750:         }
                   4751:         if (($area ne '') && ($trole ne '')) {
                   4752:             my $spec=$trole.'.'.$area;
                   4753:             if ($trole =~ /^cr\//) {
                   4754:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4755:             } elsif ($trole ne 'gr') {
                   4756:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4757:             }
                   4758:         }
                   4759:     }
                   4760:     foreach my $role (keys(%allroles)) {
                   4761:         last if ($is_adv);
                   4762:         foreach my $item (split(/:/,$allroles{$role})) {
                   4763:             if ($item ne '') {
                   4764:                 my ($privilege,$restrictions)=split(/&/,$item);
                   4765:                 if ($privilege eq 'adv') {
                   4766:                     $is_adv = 1;
                   4767:                     last;
                   4768:                 }
                   4769:             }
                   4770:         }
                   4771:     }
                   4772:     return $is_adv;
                   4773: }
1.798     raeburn  4774: 
1.341     www      4775: # ---------------------------------------------- Custom access rule evaluation
                   4776: 
                   4777: sub customaccess {
                   4778:     my ($priv,$uri)=@_;
1.807     albertel 4779:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4780:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4781:     $udom = &LONCAPA::clean_domain($udom);
                   4782:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4783:     my $access=0;
1.800     albertel 4784:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4785: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4786: 	if ($type eq 'user') {
                   4787: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4788: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4789: 		if ($tdom) {
                   4790: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4791: 		}
1.896     albertel 4792: 		if ($tuname) {
                   4793: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4794: 		}
                   4795: 		$access=($effect eq 'allow');
                   4796: 		last;
                   4797: 	    }
                   4798: 	} else {
                   4799: 	    if ($role) {
                   4800: 		if ($role ne $urole) { next; }
                   4801: 	    }
                   4802: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4803: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4804: 		if ($tdom) {
                   4805: 		    if ($tdom ne $udom) { next; }
                   4806: 		}
                   4807: 		if ($tcrs) {
                   4808: 		    if ($tcrs ne $ucrs) { next; }
                   4809: 		}
                   4810: 		if ($tsec) {
                   4811: 		    if ($tsec ne $usec) { next; }
                   4812: 		}
                   4813: 		$access=($effect eq 'allow');
                   4814: 		last;
                   4815: 	    }
                   4816: 	    if ($realm eq '' && $role eq '') {
                   4817: 		$access=($effect eq 'allow');
                   4818: 	    }
1.402     bowersj2 4819: 	}
1.341     www      4820:     }
                   4821:     return $access;
                   4822: }
                   4823: 
1.103     harris41 4824: # ------------------------------------------------- Check for a user privilege
1.12      www      4825: 
                   4826: sub allowed {
1.810     raeburn  4827:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4828:     my $ver_orguri=$uri;
1.439     www      4829:     $uri=&deversion($uri);
1.152     www      4830:     my $orguri=$uri;
1.52      www      4831:     $uri=&declutter($uri);
1.809     raeburn  4832: 
1.810     raeburn  4833:     if ($priv eq 'evb') {
                   4834: # Evade communication block restrictions for specified role in a course
                   4835:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4836:             return $1;
                   4837:         } else {
                   4838:             return;
                   4839:         }
                   4840:     }
                   4841: 
1.620     albertel 4842:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4843: # Free bre access to adm and meta resources
1.775     albertel 4844:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4845: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4846: 	&& ($priv eq 'bre')) {
1.14      www      4847: 	return 'F';
1.159     www      4848:     }
                   4849: 
1.545     banghart 4850: # Free bre access to user's own portfolio contents
1.714     raeburn  4851:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4852:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4853: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4854:         my %setters;
                   4855:         my ($startblock,$endblock) = 
                   4856:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4857:         if ($startblock && $endblock) {
                   4858:             return 'B';
                   4859:         } else {
                   4860:             return 'F';
                   4861:         }
1.545     banghart 4862:     }
                   4863: 
1.762     raeburn  4864: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4865:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4866:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4867:         if (exists($env{'request.course.id'})) {
                   4868:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4869:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4870:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4871:                 my $courseprivid=$env{'request.course.id'};
                   4872:                 $courseprivid=~s/\_/\//;
                   4873:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4874:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4875:                     return $1; 
1.762     raeburn  4876:                 } else {
                   4877:                     if ($env{'request.course.sec'}) {
                   4878:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4879:                     }
                   4880:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4881:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4882:                         return $2;
                   4883:                     }
1.714     raeburn  4884:                 }
                   4885:             }
                   4886:         }
                   4887:     }
                   4888: 
1.159     www      4889: # Free bre to public access
                   4890: 
                   4891:     if ($priv eq 'bre') {
1.238     www      4892:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4893: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4894:            return 'F'; 
                   4895:         }
1.238     www      4896:         if ($copyright eq 'priv') {
                   4897:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4898: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4899: 		return '';
                   4900:             }
                   4901:         }
                   4902:         if ($copyright eq 'domain') {
                   4903:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4904: 	    unless (($env{'user.domain'} eq $1) ||
                   4905:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4906: 		return '';
                   4907:             }
1.262     matthew  4908:         }
1.620     albertel 4909:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4910:             # Library role, so allow browsing of resources in this domain.
                   4911:             return 'F';
1.238     www      4912:         }
1.341     www      4913:         if ($copyright eq 'custom') {
                   4914: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4915:         }
1.14      www      4916:     }
1.264     matthew  4917:     # Domain coordinator is trying to create a course
1.620     albertel 4918:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4919:         # uri is the requested domain in this case.
                   4920:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4921:         # a role of dc for the domain in question.
1.620     albertel 4922:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4923:     }
1.29      www      4924: 
1.52      www      4925:     my $thisallowed='';
                   4926:     my $statecond=0;
                   4927:     my $courseprivid='';
                   4928: 
                   4929: # Course
                   4930: 
1.620     albertel 4931:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4932:        $thisallowed.=$1;
                   4933:     }
1.29      www      4934: 
1.52      www      4935: # Domain
                   4936: 
1.620     albertel 4937:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4938:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4939:        $thisallowed.=$1;
                   4940:     }
1.52      www      4941: 
                   4942: # Course: uri itself is a course
1.66      www      4943:     my $courseuri=$uri;
                   4944:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4945:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4946: 
1.620     albertel 4947:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4948:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4949:        $thisallowed.=$1;
                   4950:     }
1.29      www      4951: 
1.665     albertel 4952: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4953: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4954:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4955: 	$thisallowed='';
1.671     raeburn  4956:         my ($match)=&is_on_map($uri);
                   4957:         if ($match) {
                   4958:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4959:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4960:                 $thisallowed.=$1;
                   4961:             }
                   4962:         } else {
1.705     albertel 4963:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4964:             if ($refuri) {
                   4965:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4966:                     $thisallowed='F';
1.671     raeburn  4967:                 } else {
                   4968:                     $refuri=&declutter($refuri);
                   4969:                     my ($match) = &is_on_map($refuri);
                   4970:                     if ($match) {
                   4971:                         $thisallowed='F';
                   4972:                     }
1.669     raeburn  4973:                 }
1.671     raeburn  4974:             }
                   4975:         }
1.314     www      4976:     }
1.492     albertel 4977: 
1.766     albertel 4978:     if ($priv eq 'bre'
                   4979: 	&& $thisallowed ne 'F' 
                   4980: 	&& $thisallowed ne '2'
                   4981: 	&& &is_portfolio_url($uri)) {
                   4982: 	$thisallowed = &portfolio_access($uri);
                   4983:     }
                   4984:     
1.52      www      4985: # Full access at system, domain or course-wide level? Exit.
1.29      www      4986:     if ($thisallowed=~/F/) {
                   4987: 	return 'F';
                   4988:     }
                   4989: 
1.52      www      4990: # If this is generating or modifying users, exit with special codes
1.29      www      4991: 
1.643     www      4992:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4993: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4994: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4995: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4996: 	    unless ($auname) { return $thisallowed; }
                   4997: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4998: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4999: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5000: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5001: 	}
1.52      www      5002: 	return $thisallowed;
                   5003:     }
                   5004: #
1.103     harris41 5005: # Gathered so far: system, domain and course wide privileges
1.52      www      5006: #
                   5007: # Course: See if uri or referer is an individual resource that is part of 
                   5008: # the course
                   5009: 
1.620     albertel 5010:     if ($env{'request.course.id'}) {
1.232     www      5011: 
1.620     albertel 5012:        $courseprivid=$env{'request.course.id'};
                   5013:        if ($env{'request.course.sec'}) {
                   5014:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5015:        }
                   5016:        $courseprivid=~s/\_/\//;
                   5017:        my $checkreferer=1;
1.232     www      5018:        my ($match,$cond)=&is_on_map($uri);
                   5019:        if ($match) {
                   5020:            $statecond=$cond;
1.620     albertel 5021:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5022:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5023:                $thisallowed.=$1;
                   5024:                $checkreferer=0;
                   5025:            }
1.29      www      5026:        }
1.83      www      5027:        
1.148     www      5028:        if ($checkreferer) {
1.620     albertel 5029: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5030:             unless ($refuri) {
1.800     albertel 5031:                 foreach my $key (keys(%env)) {
                   5032: 		    if ($key=~/^httpref\..*\*/) {
                   5033: 			my $pattern=$key;
1.156     www      5034:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5035:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5036:                         $pattern=~s/\//\\\//g;
1.152     www      5037:                         if ($orguri=~/$pattern/) {
1.800     albertel 5038: 			    $refuri=$env{$key};
1.148     www      5039:                         }
                   5040:                     }
1.191     harris41 5041:                 }
1.148     www      5042:             }
1.232     www      5043: 
1.148     www      5044:          if ($refuri) { 
1.152     www      5045: 	  $refuri=&declutter($refuri);
1.232     www      5046:           my ($match,$cond)=&is_on_map($refuri);
                   5047:             if ($match) {
                   5048:               my $refstatecond=$cond;
1.620     albertel 5049:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5050:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5051:                   $thisallowed.=$1;
1.53      www      5052:                   $uri=$refuri;
                   5053:                   $statecond=$refstatecond;
1.52      www      5054:               }
                   5055:           }
1.148     www      5056:         }
1.29      www      5057:        }
1.52      www      5058:    }
1.29      www      5059: 
1.52      www      5060: #
1.103     harris41 5061: # Gathered now: all privileges that could apply, and condition number
1.52      www      5062: # 
                   5063: #
                   5064: # Full or no access?
                   5065: #
1.29      www      5066: 
1.52      www      5067:     if ($thisallowed=~/F/) {
                   5068: 	return 'F';
                   5069:     }
1.29      www      5070: 
1.52      www      5071:     unless ($thisallowed) {
                   5072:         return '';
                   5073:     }
1.29      www      5074: 
1.52      www      5075: # Restrictions exist, deal with them
                   5076: #
                   5077: #   C:according to course preferences
                   5078: #   R:according to resource settings
                   5079: #   L:unless locked
                   5080: #   X:according to user session state
                   5081: #
                   5082: 
                   5083: # Possibly locked functionality, check all courses
1.54      www      5084: # Locks might take effect only after 10 minutes cache expiration for other
                   5085: # courses, and 2 minutes for current course
1.52      www      5086: 
                   5087:     my $envkey;
                   5088:     if ($thisallowed=~/L/) {
1.1000    raeburn  5089:         foreach $envkey (keys(%env)) {
1.54      www      5090:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5091:                my $courseid=$2;
                   5092:                my $roleid=$1.'.'.$2;
1.92      www      5093:                $courseid=~s/^\///;
1.54      www      5094:                my $expiretime=600;
1.620     albertel 5095:                if ($env{'request.role'} eq $roleid) {
1.54      www      5096: 		  $expiretime=120;
                   5097:                }
                   5098: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5099:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5100:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5101: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5102:                }
1.620     albertel 5103:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5104:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5105: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5106:                        &log($env{'user.domain'},$env{'user.name'},
                   5107:                             $env{'user.home'},
1.57      www      5108:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5109:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5110:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5111: 		       return '';
                   5112:                    }
                   5113:                }
1.620     albertel 5114:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5115:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5116: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5117:                        &log($env{'user.domain'},$env{'user.name'},
                   5118:                             $env{'user.home'},
1.57      www      5119:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5120:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5121:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5122: 		       return '';
                   5123:                    }
                   5124:                }
                   5125: 	   }
1.29      www      5126:        }
1.52      www      5127:     }
                   5128:    
                   5129: #
                   5130: # Rest of the restrictions depend on selected course
                   5131: #
                   5132: 
1.620     albertel 5133:     unless ($env{'request.course.id'}) {
1.766     albertel 5134: 	if ($thisallowed eq 'A') {
                   5135: 	    return 'A';
1.814     raeburn  5136:         } elsif ($thisallowed eq 'B') {
                   5137:             return 'B';
1.766     albertel 5138: 	} else {
                   5139: 	    return '1';
                   5140: 	}
1.52      www      5141:     }
1.29      www      5142: 
1.52      www      5143: #
                   5144: # Now user is definitely in a course
                   5145: #
1.53      www      5146: 
                   5147: 
                   5148: # Course preferences
                   5149: 
                   5150:    if ($thisallowed=~/C/) {
1.620     albertel 5151:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5152:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5153:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5154: 	   =~/\Q$rolecode\E/) {
1.689     albertel 5155: 	   if ($priv ne 'pch') { 
                   5156: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5157: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5158: 			$env{'request.course.id'});
                   5159: 	   }
1.237     www      5160:            return '';
                   5161:        }
                   5162: 
1.620     albertel 5163:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5164: 	   =~/\Q$unamedom\E/) {
1.689     albertel 5165: 	   if ($priv ne 'pch') { 
                   5166: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5167: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5168: 			$env{'request.course.id'});
                   5169: 	   }
1.54      www      5170:            return '';
                   5171:        }
1.53      www      5172:    }
                   5173: 
                   5174: # Resource preferences
                   5175: 
                   5176:    if ($thisallowed=~/R/) {
1.620     albertel 5177:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5178:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 5179: 	   if ($priv ne 'pch') { 
                   5180: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5181: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5182: 	   }
                   5183: 	   return '';
1.54      www      5184:        }
1.53      www      5185:    }
1.30      www      5186: 
1.246     www      5187: # Restricted by state or randomout?
1.30      www      5188: 
1.52      www      5189:    if ($thisallowed=~/X/) {
1.620     albertel 5190:       if ($env{'acc.randomout'}) {
1.579     albertel 5191: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5192:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5193:             return ''; 
                   5194:          }
1.247     www      5195:       }
                   5196:       if (&condval($statecond)) {
1.52      www      5197: 	 return '2';
                   5198:       } else {
                   5199:          return '';
                   5200:       }
                   5201:    }
1.30      www      5202: 
1.766     albertel 5203:     if ($thisallowed eq 'A') {
                   5204: 	return 'A';
1.814     raeburn  5205:     } elsif ($thisallowed eq 'B') {
                   5206:         return 'B';
1.766     albertel 5207:     }
1.52      www      5208:    return 'F';
1.232     www      5209: }
                   5210: 
1.710     albertel 5211: sub split_uri_for_cond {
                   5212:     my $uri=&deversion(&declutter(shift));
                   5213:     my @uriparts=split(/\//,$uri);
                   5214:     my $filename=pop(@uriparts);
                   5215:     my $pathname=join('/',@uriparts);
                   5216:     return ($pathname,$filename);
                   5217: }
1.232     www      5218: # --------------------------------------------------- Is a resource on the map?
                   5219: 
                   5220: sub is_on_map {
1.710     albertel 5221:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5222:     #Trying to find the conditional for the file
1.620     albertel 5223:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5224: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5225:     if ($match) {
1.289     bowersj2 5226: 	return (1,$1);
                   5227:     } else {
1.434     www      5228: 	return (0,0);
1.289     bowersj2 5229:     }
1.12      www      5230: }
                   5231: 
1.427     www      5232: # --------------------------------------------------------- Get symb from alias
                   5233: 
                   5234: sub get_symb_from_alias {
                   5235:     my $symb=shift;
                   5236:     my ($map,$resid,$url)=&decode_symb($symb);
                   5237: # Already is a symb
                   5238:     if ($url) { return $symb; }
                   5239: # Must be an alias
                   5240:     my $aliassymb='';
                   5241:     my %bighash;
1.620     albertel 5242:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5243:                             &GDBM_READER(),0640)) {
                   5244:         my $rid=$bighash{'mapalias_'.$symb};
                   5245: 	if ($rid) {
                   5246: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5247: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5248: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5249: 	}
                   5250:         untie %bighash;
                   5251:     }
                   5252:     return $aliassymb;
                   5253: }
                   5254: 
1.12      www      5255: # ----------------------------------------------------------------- Define Role
                   5256: 
                   5257: sub definerole {
                   5258:   if (allowed('mcr','/')) {
                   5259:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5260:     foreach my $role (split(':',$sysrole)) {
                   5261: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5262:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5263:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5264: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5265:                return "refused:s:$crole&$cqual"; 
                   5266:             }
                   5267:         }
1.191     harris41 5268:     }
1.800     albertel 5269:     foreach my $role (split(':',$domrole)) {
                   5270: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5271:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5272:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5273: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5274:                return "refused:d:$crole&$cqual"; 
                   5275:             }
                   5276:         }
1.191     harris41 5277:     }
1.800     albertel 5278:     foreach my $role (split(':',$courole)) {
                   5279: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5280:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5281:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5282: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5283:                return "refused:c:$crole&$cqual"; 
                   5284:             }
                   5285:         }
1.191     harris41 5286:     }
1.620     albertel 5287:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5288:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5289: 	        "rolesdef_$rolename=".
                   5290:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5291:     return reply($command,$env{'user.home'});
1.12      www      5292:   } else {
                   5293:     return 'refused';
                   5294:   }
1.105     harris41 5295: }
                   5296: 
                   5297: # ---------------- Make a metadata query against the network of library servers
                   5298: 
                   5299: sub metadata_query {
1.244     matthew  5300:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5301:     my %rhash;
1.845     albertel 5302:     my %libserv = &all_library();
1.244     matthew  5303:     my @server_list = (defined($server_array) ? @$server_array
                   5304:                                               : keys(%libserv) );
                   5305:     for my $server (@server_list) {
1.118     harris41 5306: 	unless ($custom or $customshow) {
                   5307: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5308: 	    $rhash{$server}=$reply;
                   5309: 	}
                   5310: 	else {
                   5311: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5312: 			     &escape($custom).':'.&escape($customshow),
                   5313: 			     $server);
                   5314: 	    $rhash{$server}=$reply;
                   5315: 	}
1.112     harris41 5316:     }
1.118     harris41 5317:     return \%rhash;
1.240     www      5318: }
                   5319: 
                   5320: # ----------------------------------------- Send log queries and wait for reply
                   5321: 
                   5322: sub log_query {
                   5323:     my ($uname,$udom,$query,%filters)=@_;
                   5324:     my $uhome=&homeserver($uname,$udom);
                   5325:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5326:     my $uhost=&hostname($uhome);
1.800     albertel 5327:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5328:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5329:                        $uhome);
1.479     albertel 5330:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5331:     return get_query_reply($queryid);
                   5332: }
                   5333: 
1.818     raeburn  5334: # -------------------------- Update MySQL table for portfolio file
                   5335: 
                   5336: sub update_portfolio_table {
1.821     raeburn  5337:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5338:     if ($group ne '') {
                   5339:         $file_name =~s /^\Q$group\E//;
                   5340:     }
1.818     raeburn  5341:     my $homeserver = &homeserver($uname,$udom);
                   5342:     my $queryid=
1.821     raeburn  5343:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5344:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5345:     my $reply = &get_query_reply($queryid);
                   5346:     return $reply;
                   5347: }
                   5348: 
1.899     raeburn  5349: # -------------------------- Update MySQL allusers table
                   5350: 
                   5351: sub update_allusers_table {
                   5352:     my ($uname,$udom,$names) = @_;
                   5353:     my $homeserver = &homeserver($uname,$udom);
                   5354:     my $queryid=
                   5355:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5356:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5357:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5358:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5359:                'generation='.&escape($names->{'generation'}).'%%'.
                   5360:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5361:                'id='.&escape($names->{'id'}),$homeserver);
                   5362:     my $reply = &get_query_reply($queryid);
                   5363:     return $reply;
                   5364: }
                   5365: 
1.508     raeburn  5366: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5367: 
                   5368: sub fetch_enrollment_query {
1.511     raeburn  5369:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5370:     my $homeserver;
1.547     raeburn  5371:     my $maxtries = 1;
1.508     raeburn  5372:     if ($context eq 'automated') {
                   5373:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5374:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5375:     } else {
                   5376:         $homeserver = &homeserver($cnum,$dom);
                   5377:     }
1.838     albertel 5378:     my $host=&hostname($homeserver);
1.506     raeburn  5379:     my $cmd = '';
1.1000    raeburn  5380:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 5381:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5382:     }
                   5383:     $cmd =~ s/%%$//;
                   5384:     $cmd = &escape($cmd);
                   5385:     my $query = 'fetchenrollment';
1.620     albertel 5386:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5387:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5388:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5389:         return 'error: '.$queryid;
                   5390:     }
1.506     raeburn  5391:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5392:     my $tries = 1;
                   5393:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5394:         $reply = &get_query_reply($queryid);
                   5395:         $tries ++;
                   5396:     }
1.526     raeburn  5397:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5398:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5399:     } else {
1.901     albertel 5400:         my @responses = split(/:/,$reply);
1.515     raeburn  5401:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5402:             foreach my $line (@responses) {
                   5403:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5404:                 $$replyref{$key} = $value;
                   5405:             }
                   5406:         } else {
1.506     raeburn  5407:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5408:             foreach my $line (@responses) {
                   5409:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5410:                 $$replyref{$key} = $value;
                   5411:                 if ($value > 0) {
1.800     albertel 5412:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5413:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5414:                         my $destname = $pathname.'/'.$filename;
                   5415:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5416:                         if ($xml_classlist =~ /^error/) {
                   5417:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5418:                         } else {
1.506     raeburn  5419:                             if ( open(FILE,">$destname") ) {
                   5420:                                 print FILE &unescape($xml_classlist);
                   5421:                                 close(FILE);
1.526     raeburn  5422:                             } else {
                   5423:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5424:                             }
                   5425:                         }
                   5426:                     }
                   5427:                 }
                   5428:             }
                   5429:         }
                   5430:         return 'ok';
                   5431:     }
                   5432:     return 'error';
                   5433: }
                   5434: 
1.242     www      5435: sub get_query_reply {
                   5436:     my $queryid=shift;
1.240     www      5437:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5438:     my $reply='';
                   5439:     for (1..100) {
                   5440: 	sleep 2;
                   5441:         if (-e $replyfile.'.end') {
1.448     albertel 5442: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5443: 		$reply = join('',<$fh>);
                   5444: 		close($fh);
1.240     www      5445: 	   } else { return 'error: reply_file_error'; }
1.242     www      5446:            return &unescape($reply);
                   5447: 	}
1.240     www      5448:     }
1.242     www      5449:     return 'timeout:'.$queryid;
1.240     www      5450: }
                   5451: 
                   5452: sub courselog_query {
1.241     www      5453: #
                   5454: # possible filters:
                   5455: # url: url or symb
                   5456: # username
                   5457: # domain
                   5458: # action: view, submit, grade
                   5459: # start: timestamp
                   5460: # end: timestamp
                   5461: #
1.240     www      5462:     my (%filters)=@_;
1.620     albertel 5463:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5464:     if ($filters{'url'}) {
                   5465: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5466:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5467:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5468:     }
1.620     albertel 5469:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5470:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5471:     return &log_query($cname,$cdom,'courselog',%filters);
                   5472: }
                   5473: 
                   5474: sub userlog_query {
1.858     raeburn  5475: #
                   5476: # possible filters:
                   5477: # action: log check role
                   5478: # start: timestamp
                   5479: # end: timestamp
                   5480: #
1.240     www      5481:     my ($uname,$udom,%filters)=@_;
                   5482:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5483: }
                   5484: 
1.506     raeburn  5485: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5486: 
                   5487: sub auto_run {
1.508     raeburn  5488:     my ($cnum,$cdom) = @_;
1.876     raeburn  5489:     my $response = 0;
                   5490:     my $settings;
                   5491:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5492:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5493:         $settings = $domconfig{'autoenroll'};
                   5494:         if ($settings->{'run'} eq '1') {
                   5495:             $response = 1;
                   5496:         }
                   5497:     } else {
1.934     raeburn  5498:         my $homeserver;
                   5499:         if (&is_course($cdom,$cnum)) {
                   5500:             $homeserver = &homeserver($cnum,$cdom);
                   5501:         } else {
                   5502:             $homeserver = &domain($cdom,'primary');
                   5503:         }
                   5504:         if ($homeserver ne 'no_host') {
                   5505:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5506:         }
1.876     raeburn  5507:     }
1.506     raeburn  5508:     return $response;
                   5509: }
1.776     albertel 5510: 
1.506     raeburn  5511: sub auto_get_sections {
1.508     raeburn  5512:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  5513:     my $homeserver;
                   5514:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   5515:         $homeserver = &homeserver($cnum,$cdom);
                   5516:     }
                   5517:     if (!defined($homeserver)) { 
                   5518:         if ($cdom =~ /^$match_domain$/) {
                   5519:             $homeserver = &domain($cdom,'primary');
                   5520:         }
                   5521:     }
                   5522:     my @secs;
                   5523:     if (defined($homeserver)) {
                   5524:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   5525:         unless ($response eq 'refused') {
                   5526:             @secs = split(/:/,$response);
                   5527:         }
1.506     raeburn  5528:     }
                   5529:     return @secs;
                   5530: }
1.776     albertel 5531: 
1.506     raeburn  5532: sub auto_new_course {
1.508     raeburn  5533:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5534:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5535:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5536:     return $response;
                   5537: }
1.776     albertel 5538: 
1.506     raeburn  5539: sub auto_validate_courseID {
1.508     raeburn  5540:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5541:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5542:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5543:     return $response;
                   5544: }
1.776     albertel 5545: 
1.1007    raeburn  5546: sub auto_validate_instcode {
                   5547:     my ($cnum,$cdom,$instcode,$owner) = @_;
                   5548:     my ($homeserver,$response);
                   5549:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5550:         $homeserver = &homeserver($cnum,$cdom);
                   5551:     }
                   5552:     if (!defined($homeserver)) {
                   5553:         if ($cdom =~ /^$match_domain$/) {
                   5554:             $homeserver = &domain($cdom,'primary');
                   5555:         }
                   5556:     }
                   5557:     my $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   5558:                            &escape($instcode).':'.&escape($owner),$homeserver));
                   5559:     return $response;
                   5560: }
                   5561: 
1.506     raeburn  5562: sub auto_create_password {
1.873     raeburn  5563:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5564:     my ($homeserver,$response);
1.506     raeburn  5565:     my $create_passwd = 0;
                   5566:     my $authchk = '';
1.873     raeburn  5567:     if ($udom =~ /^$match_domain$/) {
                   5568:         $homeserver = &domain($udom,'primary');
                   5569:     }
                   5570:     if ($homeserver eq '') {
                   5571:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5572:             $homeserver = &homeserver($cnum,$cdom);
                   5573:         }
                   5574:     }
                   5575:     if ($homeserver eq '') {
                   5576:         $authchk = 'nodomain';
1.506     raeburn  5577:     } else {
1.873     raeburn  5578:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5579:         if ($response eq 'refused') {
                   5580:             $authchk = 'refused';
                   5581:         } else {
1.901     albertel 5582:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5583:         }
1.506     raeburn  5584:     }
                   5585:     return ($authparam,$create_passwd,$authchk);
                   5586: }
                   5587: 
1.706     raeburn  5588: sub auto_photo_permission {
                   5589:     my ($cnum,$cdom,$students) = @_;
                   5590:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5591:     my ($outcome,$perm_reqd,$conditions) = 
                   5592: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5593:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5594: 	return (undef,undef);
                   5595:     }
1.706     raeburn  5596:     return ($outcome,$perm_reqd,$conditions);
                   5597: }
                   5598: 
                   5599: sub auto_checkphotos {
                   5600:     my ($uname,$udom,$pid) = @_;
                   5601:     my $homeserver = &homeserver($uname,$udom);
                   5602:     my ($result,$resulttype);
                   5603:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5604: 				   &escape($uname).':'.&escape($pid),
                   5605: 				   $homeserver));
1.709     albertel 5606:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5607: 	return (undef,undef);
                   5608:     }
1.706     raeburn  5609:     if ($outcome) {
                   5610:         ($result,$resulttype) = split(/:/,$outcome);
                   5611:     } 
                   5612:     return ($result,$resulttype);
                   5613: }
                   5614: 
                   5615: sub auto_photochoice {
                   5616:     my ($cnum,$cdom) = @_;
                   5617:     my $homeserver = &homeserver($cnum,$cdom);
                   5618:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5619: 						       &escape($cdom),
                   5620: 						       $homeserver)));
1.709     albertel 5621:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5622: 	return (undef,undef);
                   5623:     }
1.706     raeburn  5624:     return ($update,$comment);
                   5625: }
                   5626: 
                   5627: sub auto_photoupdate {
                   5628:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5629:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5630:     my $host=&hostname($homeserver);
1.706     raeburn  5631:     my $cmd = '';
                   5632:     my $maxtries = 1;
1.800     albertel 5633:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5634:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5635:     }
                   5636:     $cmd =~ s/%%$//;
                   5637:     $cmd = &escape($cmd);
                   5638:     my $query = 'institutionalphotos';
                   5639:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5640:     unless ($queryid=~/^\Q$host\E\_/) {
                   5641:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5642:         return 'error: '.$queryid;
                   5643:     }
                   5644:     my $reply = &get_query_reply($queryid);
                   5645:     my $tries = 1;
                   5646:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5647:         $reply = &get_query_reply($queryid);
                   5648:         $tries ++;
                   5649:     }
                   5650:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5651:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5652:     } else {
                   5653:         my @responses = split(/:/,$reply);
                   5654:         my $outcome = shift(@responses); 
                   5655:         foreach my $item (@responses) {
                   5656:             my ($key,$value) = split(/=/,$item);
                   5657:             $$photo{$key} = $value;
                   5658:         }
                   5659:         return $outcome;
                   5660:     }
                   5661:     return 'error';
                   5662: }
                   5663: 
1.521     raeburn  5664: sub auto_instcode_format {
1.793     albertel 5665:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5666: 	$cat_order) = @_;
1.521     raeburn  5667:     my $courses = '';
1.772     raeburn  5668:     my @homeservers;
1.521     raeburn  5669:     if ($caller eq 'global') {
1.841     albertel 5670: 	my %servers = &get_servers($codedom,'library');
                   5671: 	foreach my $tryserver (keys(%servers)) {
                   5672: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5673: 		push(@homeservers,$tryserver);
                   5674: 	    }
1.584     raeburn  5675:         }
1.521     raeburn  5676:     } else {
1.772     raeburn  5677:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5678:     }
1.793     albertel 5679:     foreach my $code (keys(%{$instcodes})) {
                   5680:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5681:     }
                   5682:     chop($courses);
1.772     raeburn  5683:     my $ok_response = 0;
                   5684:     my $response;
                   5685:     while (@homeservers > 0 && $ok_response == 0) {
                   5686:         my $server = shift(@homeservers); 
                   5687:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5688:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5689:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5690: 		split(/:/,$response);
1.772     raeburn  5691:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5692:             push(@{$codetitles},&str2array($codetitles_str));
                   5693:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5694:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5695:             $ok_response = 1;
                   5696:         }
                   5697:     }
                   5698:     if ($ok_response) {
1.521     raeburn  5699:         return 'ok';
1.772     raeburn  5700:     } else {
                   5701:         return $response;
1.521     raeburn  5702:     }
                   5703: }
                   5704: 
1.792     raeburn  5705: sub auto_instcode_defaults {
                   5706:     my ($domain,$returnhash,$code_order) = @_;
                   5707:     my @homeservers;
1.841     albertel 5708: 
                   5709:     my %servers = &get_servers($domain,'library');
                   5710:     foreach my $tryserver (keys(%servers)) {
                   5711: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5712: 	    push(@homeservers,$tryserver);
                   5713: 	}
1.792     raeburn  5714:     }
1.841     albertel 5715: 
1.792     raeburn  5716:     my $response;
1.841     albertel 5717:     foreach my $server (@homeservers) {
1.792     raeburn  5718:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5719:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5720: 	
                   5721: 	foreach my $pair (split(/\&/,$response)) {
                   5722: 	    my ($name,$value)=split(/\=/,$pair);
                   5723: 	    if ($name eq 'code_order') {
                   5724: 		@{$code_order} = split(/\&/,&unescape($value));
                   5725: 	    } else {
                   5726: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5727: 	    }
                   5728: 	}
                   5729: 	return 'ok';
1.792     raeburn  5730:     }
1.841     albertel 5731: 
                   5732:     return $response;
1.1003    raeburn  5733: }
                   5734: 
                   5735: sub auto_possible_instcodes {
1.1007    raeburn  5736:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   5737:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   5738:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   5739:         return;
                   5740:     }
1.1003    raeburn  5741:     my (@homeservers,$uhome);
                   5742:     if (defined(&domain($domain,'primary'))) {
                   5743:         $uhome=&domain($domain,'primary');
                   5744:         push(@homeservers,&domain($domain,'primary'));
                   5745:     } else {
                   5746:         my %servers = &get_servers($domain,'library');
                   5747:         foreach my $tryserver (keys(%servers)) {
                   5748:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5749:                 push(@homeservers,$tryserver);
                   5750:             }
                   5751:         }
                   5752:     }
                   5753:     my $response;
                   5754:     foreach my $server (@homeservers) {
                   5755:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   5756:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  5757:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   5758:             split(':',$response);
                   5759:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   5760:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  5761:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  5762:             my ($name,$value)=split('=',$item);
                   5763:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  5764:         }
                   5765:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  5766:             my ($name,$value)=split('=',$item);
                   5767:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  5768:         }
                   5769:         return 'ok';
                   5770:     }
                   5771:     return $response;
                   5772: }
1.792     raeburn  5773: 
1.777     albertel 5774: sub auto_validate_class_sec {
1.918     raeburn  5775:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5776:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5777:     my $ownerlist;
                   5778:     if (ref($owners) eq 'ARRAY') {
                   5779:         $ownerlist = join(',',@{$owners});
                   5780:     } else {
                   5781:         $ownerlist = $owners;
                   5782:     }
1.773     raeburn  5783:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5784:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5785:     return $response;
                   5786: }
                   5787: 
1.679     raeburn  5788: # ------------------------------------------------------- Course Group routines
                   5789: 
                   5790: sub get_coursegroups {
1.809     raeburn  5791:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5792:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5793: }
                   5794: 
1.679     raeburn  5795: sub modify_coursegroup {
                   5796:     my ($cdom,$cnum,$groupsettings) = @_;
                   5797:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5798: }
                   5799: 
1.809     raeburn  5800: sub toggle_coursegroup_status {
                   5801:     my ($cdom,$cnum,$group,$action) = @_;
                   5802:     my ($from_namespace,$to_namespace);
                   5803:     if ($action eq 'delete') {
                   5804:         $from_namespace = 'coursegroups';
                   5805:         $to_namespace = 'deleted_groups';
                   5806:     } else {
                   5807:         $from_namespace = 'deleted_groups';
                   5808:         $to_namespace = 'coursegroups';
                   5809:     }
                   5810:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5811:     if (my $tmp = &error(%curr_group)) {
                   5812:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5813:         return ('read error',$tmp);
                   5814:     } else {
                   5815:         my %savedsettings = %curr_group; 
1.809     raeburn  5816:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5817:         my $deloutcome;
                   5818:         if ($result eq 'ok') {
1.809     raeburn  5819:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5820:         } else {
                   5821:             return ('write error',$result);
                   5822:         }
                   5823:         if ($deloutcome eq 'ok') {
                   5824:             return 'ok';
                   5825:         } else {
                   5826:             return ('delete error',$deloutcome);
                   5827:         }
                   5828:     }
                   5829: }
                   5830: 
1.679     raeburn  5831: sub modify_group_roles {
1.957     raeburn  5832:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  5833:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5834:     my $role = 'gr/'.&escape($userprivs);
                   5835:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  5836:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  5837:     if ($result eq 'ok') {
                   5838:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5839:     }
1.679     raeburn  5840:     return $result;
                   5841: }
                   5842: 
                   5843: sub modify_coursegroup_membership {
                   5844:     my ($cdom,$cnum,$membership) = @_;
                   5845:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5846:     return $result;
                   5847: }
                   5848: 
1.682     raeburn  5849: sub get_active_groups {
                   5850:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5851:     my $now = time;
                   5852:     my %groups = ();
                   5853:     foreach my $key (keys(%env)) {
1.811     albertel 5854:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5855:             my ($start,$end) = split(/\./,$env{$key});
                   5856:             if (($end!=0) && ($end<$now)) { next; }
                   5857:             if (($start!=0) && ($start>$now)) { next; }
                   5858:             if ($1 eq $cdom && $2 eq $cnum) {
                   5859:                 $groups{$3} = $env{$key} ;
                   5860:             }
                   5861:         }
                   5862:     }
                   5863:     return %groups;
                   5864: }
                   5865: 
1.683     raeburn  5866: sub get_group_membership {
                   5867:     my ($cdom,$cnum,$group) = @_;
                   5868:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5869: }
                   5870: 
                   5871: sub get_users_groups {
                   5872:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5873:     my @usersgroups;
1.683     raeburn  5874:     my $cachetime=1800;
                   5875: 
                   5876:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5877:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5878:     if (defined($cached)) {
1.734     albertel 5879:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5880:     } else {  
                   5881:         $grouplist = '';
1.816     raeburn  5882:         my $courseurl = &courseid_to_courseurl($courseid);
                   5883:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5884:         my $access_end = $env{'course.'.$courseid.
                   5885:                               '.default_enrollment_end_date'};
                   5886:         my $now = time;
                   5887:         foreach my $key (keys(%roleshash)) {
                   5888:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5889:                 my $group = $1;
                   5890:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5891:                     my $start = $2;
                   5892:                     my $end = $1;
                   5893:                     if ($start == -1) { next; } # deleted from group
                   5894:                     if (($start!=0) && ($start>$now)) { next; }
                   5895:                     if (($end!=0) && ($end<$now)) {
                   5896:                         if ($access_end && $access_end < $now) {
                   5897:                             if ($access_end - $end < 86400) {
                   5898:                                 push(@usersgroups,$group);
1.733     raeburn  5899:                             }
                   5900:                         }
1.817     raeburn  5901:                         next;
1.733     raeburn  5902:                     }
1.817     raeburn  5903:                     push(@usersgroups,$group);
1.683     raeburn  5904:                 }
                   5905:             }
                   5906:         }
1.817     raeburn  5907:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5908:         $grouplist = join(':',@usersgroups);
                   5909:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5910:     }
1.733     raeburn  5911:     return @usersgroups;
1.683     raeburn  5912: }
                   5913: 
                   5914: sub devalidate_getgroups_cache {
                   5915:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5916:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5917: 
1.683     raeburn  5918:     my $hashid="$udom:$uname:$courseid";
                   5919:     &devalidate_cache_new('getgroups',$hashid);
                   5920: }
                   5921: 
1.12      www      5922: # ------------------------------------------------------------------ Plain Text
                   5923: 
                   5924: sub plaintext {
1.988     raeburn  5925:     my ($short,$type,$cid,$forcedefault) = @_;
1.758     albertel 5926:     if ($short =~ /^cr/) {
                   5927: 	return (split('/',$short))[-1];
                   5928:     }
1.742     raeburn  5929:     if (!defined($cid)) {
                   5930:         $cid = $env{'request.course.id'};
                   5931:     }
1.988     raeburn  5932:     if (defined($cid) && ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '')) {
                   5933:         unless ($forcedefault) {
                   5934:             my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   5935:             &Apache::lonlocal::mt_escape(\$roletext);
                   5936:             return &Apache::lonlocal::mt($roletext);
                   5937:         }
1.742     raeburn  5938:     }
                   5939:     my %rolenames = (
1.1008    raeburn  5940:                       Course    => 'std',
                   5941:                       Community => 'alt1',
1.742     raeburn  5942:                     );
                   5943:     if (defined($type) && 
                   5944:          defined($rolenames{$type}) && 
                   5945:          defined($prp{$short}{$rolenames{$type}})) {
                   5946:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5947:     } else {
                   5948:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5949:     }
1.12      www      5950: }
                   5951: 
                   5952: # ----------------------------------------------------------------- Assign Role
                   5953: 
                   5954: sub assignrole {
1.957     raeburn  5955:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   5956:         $context)=@_;
1.21      www      5957:     my $mrole;
                   5958:     if ($role =~ /^cr\//) {
1.393     www      5959:         my $cwosec=$url;
1.811     albertel 5960:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5961: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5962:            &logthis('Refused custom assignrole: '.
                   5963:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5964: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5965:            return 'refused'; 
                   5966:         }
1.21      www      5967:         $mrole='cr';
1.678     raeburn  5968:     } elsif ($role =~ /^gr\//) {
                   5969:         my $cwogrp=$url;
1.811     albertel 5970:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5971:         unless (&allowed('mdg',$cwogrp)) {
                   5972:             &logthis('Refused group assignrole: '.
                   5973:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5974:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5975:             return 'refused';
                   5976:         }
                   5977:         $mrole='gr';
1.21      www      5978:     } else {
1.82      www      5979:         my $cwosec=$url;
1.811     albertel 5980:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5981:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5982:             my $refused;
                   5983:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5984:                 if (!(&allowed('c'.$role,$url))) {
                   5985:                     $refused = 1;
                   5986:                 }
                   5987:             } else {
                   5988:                 $refused = 1;
                   5989:             }
1.947     raeburn  5990:             if ($refused) {
                   5991:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5992:                     $refused = '';
                   5993:                 } else {
                   5994:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   5995:                              ' '.$role.' '.$end.' '.$start.' by '.
                   5996: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   5997:                     return 'refused';
                   5998:                 }
1.932     raeburn  5999:             }
1.104     www      6000:         }
1.21      www      6001:         $mrole=$role;
                   6002:     }
1.620     albertel 6003:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6004:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6005:     if ($end) { $command.='_'.$end; }
1.21      www      6006:     if ($start) {
                   6007: 	if ($end) { 
1.81      www      6008:            $command.='_'.$start; 
1.21      www      6009:         } else {
1.81      www      6010:            $command.='_0_'.$start;
1.21      www      6011:         }
                   6012:     }
1.739     raeburn  6013:     my $origstart = $start;
                   6014:     my $origend = $end;
1.957     raeburn  6015:     my $delflag;
1.357     www      6016: # actually delete
                   6017:     if ($deleteflag) {
1.373     www      6018: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6019: # modify command to delete the role
1.620     albertel 6020:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6021:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6022: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6023: # set start and finish to negative values for userrolelog
                   6024:            $start=-1;
                   6025:            $end=-1;
1.957     raeburn  6026:            $delflag = 1;
1.357     www      6027:         }
                   6028:     }
                   6029: # send command
1.349     www      6030:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6031: # log new user role if status is ok
1.349     www      6032:     if ($answer eq 'ok') {
1.663     raeburn  6033: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6034: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6035:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6036:         unless ($role =~ /^gr/) {
                   6037:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6038:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6039:         }
1.349     www      6040:     }
                   6041:     return $answer;
1.169     harris41 6042: }
                   6043: 
                   6044: # -------------------------------------------------- Modify user authentication
1.197     www      6045: # Overrides without validation
                   6046: 
1.169     harris41 6047: sub modifyuserauth {
                   6048:     my ($udom,$uname,$umode,$upass)=@_;
                   6049:     my $uhome=&homeserver($uname,$udom);
1.197     www      6050:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6051:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6052:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6053:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6054:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6055: 		     &escape($upass),$uhome);
1.620     albertel 6056:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6057:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6058:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6059:     &log($udom,,$uname,$uhome,
1.620     albertel 6060:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6061:                                      $env{'user.name'}.', '.$umode.
1.197     www      6062:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 6063:     unless ($reply eq 'ok') {
1.197     www      6064:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 6065: 	return 'error: '.$reply;
                   6066:     }   
1.170     harris41 6067:     return 'ok';
1.80      www      6068: }
                   6069: 
1.81      www      6070: # --------------------------------------------------------------- Modify a user
1.80      www      6071: 
1.81      www      6072: sub modifyuser {
1.206     matthew  6073:     my ($udom,    $uname, $uid,
                   6074:         $umode,   $upass, $first,
                   6075:         $middle,  $last,  $gene,
1.963     raeburn  6076:         $forceid, $desiredhome, $email, $inststatus)=@_;
1.807     albertel 6077:     $udom= &LONCAPA::clean_domain($udom);
                   6078:     $uname=&LONCAPA::clean_username($uname);
1.81      www      6079:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      6080:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  6081: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   6082:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   6083:                                      ' desiredhome not specified'). 
1.620     albertel 6084:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6085:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 6086:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      6087: # ----------------------------------------------------------------- Create User
1.406     albertel 6088:     if (($uhome eq 'no_host') && 
                   6089: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      6090:         my $unhome='';
1.844     albertel 6091:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  6092:             $unhome = $desiredhome;
1.620     albertel 6093: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   6094: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  6095:         } else { # load balancing routine for determining $unhome
1.81      www      6096:             my $loadm=10000000;
1.841     albertel 6097: 	    my %servers = &get_servers($udom,'library');
                   6098: 	    foreach my $tryserver (keys(%servers)) {
                   6099: 		my $answer=reply('load',$tryserver);
                   6100: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   6101: 		    $loadm=$answer;
                   6102: 		    $unhome=$tryserver;
                   6103: 		}
1.80      www      6104: 	    }
                   6105:         }
                   6106:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  6107: 	    return 'error: unable to find a home server for '.$uname.
                   6108:                    ' in domain '.$udom;
1.80      www      6109:         }
                   6110:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   6111:                          &escape($upass),$unhome);
                   6112: 	unless ($reply eq 'ok') {
                   6113:             return 'error: '.$reply;
                   6114:         }   
1.230     stredwic 6115:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      6116:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  6117: 	    return 'error: unable verify users home machine.';
1.80      www      6118:         }
1.209     matthew  6119:     }   # End of creation of new user
1.80      www      6120: # ---------------------------------------------------------------------- Add ID
                   6121:     if ($uid) {
                   6122:        $uid=~tr/A-Z/a-z/;
                   6123:        my %uidhash=&idrget($udom,$uname);
1.196     www      6124:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   6125:          && (!$forceid)) {
1.80      www      6126: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  6127: 	      return 'error: user id "'.$uid.'" does not match '.
                   6128:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      6129:           }
                   6130:        } else {
                   6131: 	  &idput($udom,($uname => $uid));
                   6132:        }
                   6133:     }
                   6134: # -------------------------------------------------------------- Add names, etc
1.313     matthew  6135:     my @tmp=&get('environment',
1.899     raeburn  6136: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  6137:                     'permanentemail','inststatus'],
1.134     albertel 6138: 		   $udom,$uname);
1.313     matthew  6139:     my %names;
                   6140:     if ($tmp[0] =~ m/^error:.*/) { 
                   6141:         %names=(); 
                   6142:     } else {
                   6143:         %names = @tmp;
                   6144:     }
1.388     www      6145: #
                   6146: # Make sure to not trash student environment if instructor does not bother
                   6147: # to supply name and email information
                   6148: #
                   6149:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  6150:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      6151:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  6152:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      6153:     if ($email) {
                   6154:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  6155:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      6156:     }
1.899     raeburn  6157:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  6158:     if (defined($inststatus)) {
                   6159:         $names{'inststatus'} = '';
                   6160:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   6161:         if (ref($usertypes) eq 'HASH') {
                   6162:             my @okstatuses; 
                   6163:             foreach my $item (split(/:/,$inststatus)) {
                   6164:                 if (defined($usertypes->{$item})) {
                   6165:                     push(@okstatuses,$item);  
                   6166:                 }
                   6167:             }
                   6168:             if (@okstatuses) {
                   6169:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   6170:             }
                   6171:         }
                   6172:     }
1.134     albertel 6173:     my $reply = &put('environment', \%names, $udom,$uname);
                   6174:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  6175:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      6176:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963     raeburn  6177:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
                   6178:                  $umode.', '.$first.', '.$middle.', '.
                   6179: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
                   6180:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   6181:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   6182:     } else {
                   6183:         $logmsg .= ' during self creation';
                   6184:     }
                   6185:     &logthis($logmsg);
1.134     albertel 6186:     return 'ok';
1.80      www      6187: }
                   6188: 
1.81      www      6189: # -------------------------------------------------------------- Modify student
1.80      www      6190: 
1.81      www      6191: sub modifystudent {
                   6192:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  6193:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  6194:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 6195:     if (!$cid) {
1.620     albertel 6196: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6197: 	    return 'not_in_class';
                   6198: 	}
1.80      www      6199:     }
                   6200: # --------------------------------------------------------------- Make the user
1.81      www      6201:     my $reply=&modifyuser
1.209     matthew  6202: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  6203:          $desiredhome,$email,$inststatus);
1.80      www      6204:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  6205:     # This will cause &modify_student_enrollment to get the uid from the
                   6206:     # students environment
                   6207:     $uid = undef if (!$forceid);
1.455     albertel 6208:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  6209: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  6210:     return $reply;
                   6211: }
                   6212: 
                   6213: sub modify_student_enrollment {
1.957     raeburn  6214:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 6215:     my ($cdom,$cnum,$chome);
                   6216:     if (!$cid) {
1.620     albertel 6217: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6218: 	    return 'not_in_class';
                   6219: 	}
1.620     albertel 6220: 	$cdom=$env{'course.'.$cid.'.domain'};
                   6221: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 6222:     } else {
                   6223: 	($cdom,$cnum)=split(/_/,$cid);
                   6224:     }
1.620     albertel 6225:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 6226:     if (!$chome) {
1.457     raeburn  6227: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  6228:     }
1.455     albertel 6229:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  6230:     # Make sure the user exists
1.81      www      6231:     my $uhome=&homeserver($uname,$udom);
                   6232:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6233: 	return 'error: no such user';
                   6234:     }
1.297     matthew  6235:     # Get student data if we were not given enough information
                   6236:     if (!defined($first)  || $first  eq '' || 
                   6237:         !defined($last)   || $last   eq '' || 
                   6238:         !defined($uid)    || $uid    eq '' || 
                   6239:         !defined($middle) || $middle eq '' || 
                   6240:         !defined($gene)   || $gene   eq '') {
1.294     matthew  6241:         # They did not supply us with enough data to enroll the student, so
                   6242:         # we need to pick up more information.
1.297     matthew  6243:         my %tmp = &get('environment',
1.294     matthew  6244:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  6245:                        ,$udom,$uname);
                   6246: 
1.800     albertel 6247:         #foreach my $key (keys(%tmp)) {
                   6248:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 6249:         #}
1.294     matthew  6250:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   6251:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   6252:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  6253:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  6254:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   6255:     }
1.556     albertel 6256:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 6257:     my $reply=cput('classlist',
                   6258: 		   {"$uname:$udom" => 
1.515     raeburn  6259: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 6260: 		   $cdom,$cnum);
1.81      www      6261:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   6262: 	return 'error: '.$reply;
1.652     albertel 6263:     } else {
                   6264: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      6265:     }
1.297     matthew  6266:     # Add student role to user
1.83      www      6267:     my $uurl='/'.$cid;
1.81      www      6268:     $uurl=~s/\_/\//g;
                   6269:     if ($usec) {
                   6270: 	$uurl.='/'.$usec;
                   6271:     }
1.957     raeburn  6272:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      6273: }
                   6274: 
1.556     albertel 6275: sub format_name {
                   6276:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   6277:     my $name;
                   6278:     if ($first ne 'lastname') {
                   6279: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   6280:     } else {
                   6281: 	if ($lastname=~/\S/) {
                   6282: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   6283: 	    $name=~s/\s+,/,/;
                   6284: 	} else {
                   6285: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   6286: 	}
                   6287:     }
                   6288:     $name=~s/^\s+//;
                   6289:     $name=~s/\s+$//;
                   6290:     $name=~s/\s+/ /g;
                   6291:     return $name;
                   6292: }
                   6293: 
1.84      www      6294: # ------------------------------------------------- Write to course preferences
                   6295: 
                   6296: sub writecoursepref {
                   6297:     my ($courseid,%prefs)=@_;
                   6298:     $courseid=~s/^\///;
                   6299:     $courseid=~s/\_/\//g;
                   6300:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   6301:     my $chome=homeserver($cnum,$cdomain);
                   6302:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   6303: 	return 'error: no such course';
                   6304:     }
                   6305:     my $cstring='';
1.800     albertel 6306:     foreach my $pref (keys(%prefs)) {
                   6307: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 6308:     }
1.84      www      6309:     $cstring=~s/\&$//;
                   6310:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   6311: }
                   6312: 
                   6313: # ---------------------------------------------------------- Make/modify course
                   6314: 
                   6315: sub createcourse {
1.741     raeburn  6316:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   6317:         $course_owner,$crstype)=@_;
1.84      www      6318:     $url=&declutter($url);
                   6319:     my $cid='';
1.264     matthew  6320:     unless (&allowed('ccc',$udom)) {
1.84      www      6321:         return 'refused';
                   6322:     }
                   6323: # ------------------------------------------------------------------- Create ID
1.674     www      6324:    my $uname=int(1+rand(9)).
                   6325:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   6326:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      6327:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   6328: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 6329:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      6330:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6331:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   6332:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 6333:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      6334:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6335:            return 'error: unable to generate unique course-ID';
                   6336:        } 
                   6337:    }
1.264     matthew  6338: # ------------------------------------------------ Check supplied server name
1.620     albertel 6339:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 6340:     if (! &is_library($course_server)) {
1.264     matthew  6341:         return 'error:bad server name '.$course_server;
                   6342:     }
1.84      www      6343: # ------------------------------------------------------------- Make the course
                   6344:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  6345:                       $course_server);
1.84      www      6346:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 6347:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      6348:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6349: 	return 'error: no such course';
                   6350:     }
1.271     www      6351: # ----------------------------------------------------------------- Course made
1.516     raeburn  6352: # log existence
1.918     raeburn  6353:     my $newcourse = {
                   6354:                     $udom.'_'.$uname => {
1.921     raeburn  6355:                                      description => $description,
                   6356:                                      inst_code   => $inst_code,
                   6357:                                      owner       => $course_owner,
                   6358:                                      type        => $crstype,
1.918     raeburn  6359:                                                 },
                   6360:                     };
1.921     raeburn  6361:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      6362: # set toplevel url
1.271     www      6363:     my $topurl=$url;
                   6364:     unless ($nonstandard) {
                   6365: # ------------------------------------------ For standard courses, make top url
                   6366:         my $mapurl=&clutter($url);
1.278     www      6367:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 6368:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      6369: <map>
                   6370: <resource id="1" type="start"></resource>
                   6371: <resource id="2" src="$mapurl"></resource>
                   6372: <resource id="3" type="finish"></resource>
                   6373: <link index="1" from="1" to="2"></link>
                   6374: <link index="2" from="2" to="3"></link>
                   6375: </map>
                   6376: ENDINITMAP
                   6377:         $topurl=&declutter(
1.638     albertel 6378:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      6379:                           );
                   6380:     }
                   6381: # ----------------------------------------------------------- Write preferences
1.84      www      6382:     &writecoursepref($udom.'_'.$uname,
                   6383:                      ('description' => $description,
1.271     www      6384:                       'url'         => $topurl));
1.84      www      6385:     return '/'.$udom.'/'.$uname;
                   6386: }
                   6387: 
1.813     albertel 6388: sub is_course {
                   6389:     my ($cdom,$cnum) = @_;
                   6390:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  6391: 				undef,'.');
1.813     albertel 6392:     if (exists($courses{$cdom.'_'.$cnum})) {
                   6393:         return 1;
                   6394:     }
                   6395:     return 0;
                   6396: }
                   6397: 
1.21      www      6398: # ---------------------------------------------------------- Assign Custom Role
                   6399: 
                   6400: sub assigncustomrole {
1.957     raeburn  6401:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6402:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  6403:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      6404: }
                   6405: 
                   6406: # ----------------------------------------------------------------- Revoke Role
                   6407: 
                   6408: sub revokerole {
1.957     raeburn  6409:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6410:     my $now=time;
1.965     raeburn  6411:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      6412: }
                   6413: 
                   6414: # ---------------------------------------------------------- Revoke Custom Role
                   6415: 
                   6416: sub revokecustomrole {
1.957     raeburn  6417:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6418:     my $now=time;
1.357     www      6419:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  6420:            $deleteflag,$selfenroll,$context);
1.17      www      6421: }
                   6422: 
1.533     banghart 6423: # ------------------------------------------------------------ Disk usage
1.535     albertel 6424: sub diskusage {
1.955     raeburn  6425:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   6426:     $directorypath =~ s/\/$//;
                   6427:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   6428:                        .&escape($getpropath).':'.&escape($uname).':'
                   6429:                        .&escape($udom),homeserver($uname,$udom));
                   6430:     if ($listing eq 'unknown_cmd') {
                   6431:         if ($getpropath) {
                   6432:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   6433:         }
                   6434:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   6435:     }
1.514     albertel 6436:     return $listing;
1.512     banghart 6437: }
                   6438: 
1.566     banghart 6439: sub is_locked {
                   6440:     my ($file_name, $domain, $user) = @_;
                   6441:     my @check;
                   6442:     my $is_locked;
                   6443:     push @check, $file_name;
1.613     albertel 6444:     my %locked = &get('file_permissions',\@check,
1.620     albertel 6445: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 6446:     my ($tmp)=keys(%locked);
                   6447:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  6448:     
1.566     banghart 6449:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  6450:         $is_locked = 'false';
                   6451:         foreach my $entry (@{$locked{$file_name}}) {
                   6452:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  6453:                $is_locked = 'true';
                   6454:                last;
1.745     raeburn  6455:            }
                   6456:        }
1.566     banghart 6457:     } else {
                   6458:         $is_locked = 'false';
                   6459:     }
                   6460: }
                   6461: 
1.759     albertel 6462: sub declutter_portfile {
                   6463:     my ($file) = @_;
1.833     albertel 6464:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 6465:     return $file;
                   6466: }
                   6467: 
1.559     banghart 6468: # ------------------------------------------------------------- Mark as Read Only
                   6469: 
                   6470: sub mark_as_readonly {
                   6471:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 6472:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6473:     my ($tmp)=keys(%current_permissions);
                   6474:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 6475:     foreach my $file (@{$files}) {
1.759     albertel 6476: 	$file = &declutter_portfile($file);
1.561     banghart 6477:         push(@{$current_permissions{$file}},$what);
1.559     banghart 6478:     }
1.613     albertel 6479:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6480:     return;
                   6481: }
                   6482: 
1.572     banghart 6483: # ------------------------------------------------------------Save Selected Files
                   6484: 
                   6485: sub save_selected_files {
                   6486:     my ($user, $path, @files) = @_;
                   6487:     my $filename = $user."savedfiles";
1.573     banghart 6488:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 6489:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 6490:     foreach my $file (@files) {
1.620     albertel 6491:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 6492:     }
                   6493:     foreach my $file (@other_files) {
1.574     banghart 6494:         print (OUT $file."\n");
1.572     banghart 6495:     }
1.574     banghart 6496:     close (OUT);
1.572     banghart 6497:     return 'ok';
                   6498: }
                   6499: 
1.574     banghart 6500: sub clear_selected_files {
                   6501:     my ($user) = @_;
                   6502:     my $filename = $user."savedfiles";
                   6503:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6504:     print (OUT undef);
                   6505:     close (OUT);
                   6506:     return ("ok");    
                   6507: }
                   6508: 
1.572     banghart 6509: sub files_in_path {
                   6510:     my ($user, $path) = @_;
                   6511:     my $filename = $user."savedfiles";
                   6512:     my %return_files;
1.574     banghart 6513:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 6514:     while (my $line_in = <IN>) {
1.574     banghart 6515:         chomp ($line_in);
                   6516:         my @paths_and_file = split (m!/!, $line_in);
                   6517:         my $file_part = pop (@paths_and_file);
                   6518:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 6519:         $path_part.='/';
                   6520:         my $path_and_file = $path_part.$file_part;
                   6521:         if ($path_part eq $path) {
                   6522:             $return_files{$file_part}= 'selected';
                   6523:         }
                   6524:     }
1.574     banghart 6525:     close (IN);
                   6526:     return (\%return_files);
1.572     banghart 6527: }
                   6528: 
                   6529: # called in portfolio select mode, to show files selected NOT in current directory
                   6530: sub files_not_in_path {
                   6531:     my ($user, $path) = @_;
                   6532:     my $filename = $user."savedfiles";
                   6533:     my @return_files;
                   6534:     my $path_part;
1.800     albertel 6535:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6536:     while (my $line = <IN>) {
1.572     banghart 6537:         #ok, I know it's clunky, but I want it to work
1.800     albertel 6538:         my @paths_and_file = split(m|/|, $line);
                   6539:         my $file_part = pop(@paths_and_file);
                   6540:         chomp($file_part);
                   6541:         my $path_part = join('/', @paths_and_file);
1.572     banghart 6542:         $path_part .= '/';
                   6543:         my $path_and_file = $path_part.$file_part;
                   6544:         if ($path_part ne $path) {
1.800     albertel 6545:             push(@return_files, ($path_and_file));
1.572     banghart 6546:         }
                   6547:     }
1.800     albertel 6548:     close(OUT);
1.574     banghart 6549:     return (@return_files);
1.572     banghart 6550: }
                   6551: 
1.745     raeburn  6552: #----------------------------------------------Get portfolio file permissions
1.629     banghart 6553: 
1.745     raeburn  6554: sub get_portfile_permissions {
                   6555:     my ($domain,$user) = @_;
1.613     albertel 6556:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6557:     my ($tmp)=keys(%current_permissions);
                   6558:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6559:     return \%current_permissions;
                   6560: }
                   6561: 
                   6562: #---------------------------------------------Get portfolio file access controls
                   6563: 
1.749     raeburn  6564: sub get_access_controls {
1.745     raeburn  6565:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 6566:     my %access;
                   6567:     my $real_file = $file;
                   6568:     $file =~ s/\.meta$//;
1.745     raeburn  6569:     if (defined($file)) {
1.749     raeburn  6570:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   6571:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 6572:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  6573:             }
                   6574:         }
1.745     raeburn  6575:     } else {
1.749     raeburn  6576:         foreach my $key (keys(%{$current_permissions})) {
                   6577:             if ($key =~ /\0accesscontrol$/) {
                   6578:                 if (defined($group)) {
                   6579:                     if ($key !~ m-^\Q$group\E/-) {
                   6580:                         next;
                   6581:                     }
                   6582:                 }
                   6583:                 my ($fullpath) = split(/\0/,$key);
                   6584:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   6585:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   6586:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   6587:                     }
                   6588:                 }
                   6589:             }
                   6590:         }
                   6591:     }
                   6592:     return %access;
                   6593: }
                   6594: 
                   6595: sub modify_access_controls {
                   6596:     my ($file_name,$changes,$domain,$user)=@_;
                   6597:     my ($outcome,$deloutcome);
                   6598:     my %store_permissions;
                   6599:     my %new_values;
                   6600:     my %new_control;
                   6601:     my %translation;
                   6602:     my @deletions = ();
                   6603:     my $now = time;
                   6604:     if (exists($$changes{'activate'})) {
                   6605:         if (ref($$changes{'activate'}) eq 'HASH') {
                   6606:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   6607:             my $numnew = scalar(@newitems);
                   6608:             for (my $i=0; $i<$numnew; $i++) {
                   6609:                 my $newkey = $newitems[$i];
                   6610:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  6611:                 if ($newkey =~ /^\d+:/) { 
                   6612:                     $newkey =~ s/^(\d+)/$newid/;
                   6613:                     $translation{$1} = $newid;
                   6614:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   6615:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   6616:                     $translation{$1} = $newid;
                   6617:                 }
1.749     raeburn  6618:                 $new_values{$file_name."\0".$newkey} = 
                   6619:                                           $$changes{'activate'}{$newitems[$i]};
                   6620:                 $new_control{$newkey} = $now;
                   6621:             }
                   6622:         }
                   6623:     }
                   6624:     my %todelete;
                   6625:     my %changed_items;
                   6626:     foreach my $action ('delete','update') {
                   6627:         if (exists($$changes{$action})) {
                   6628:             if (ref($$changes{$action}) eq 'HASH') {
                   6629:                 foreach my $key (keys(%{$$changes{$action}})) {
                   6630:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   6631:                     if ($action eq 'delete') { 
                   6632:                         $todelete{$itemnum} = 1;
                   6633:                     } else {
                   6634:                         $changed_items{$itemnum} = $key;
                   6635:                     }
                   6636:                 }
1.745     raeburn  6637:             }
                   6638:         }
1.749     raeburn  6639:     }
                   6640:     # get lock on access controls for file.
                   6641:     my $lockhash = {
                   6642:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   6643:                                                        ':'.$env{'user.domain'},
                   6644:                    }; 
                   6645:     my $tries = 0;
                   6646:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6647:    
                   6648:     while (($gotlock ne 'ok') && $tries <3) {
                   6649:         $tries ++;
                   6650:         sleep 1;
                   6651:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6652:     }
                   6653:     if ($gotlock eq 'ok') {
                   6654:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6655:         my ($tmp)=keys(%curr_permissions);
                   6656:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6657:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6658:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6659:             if (ref($curr_controls) eq 'HASH') {
                   6660:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6661:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6662:                     if (defined($todelete{$itemnum})) {
                   6663:                         push(@deletions,$file_name."\0".$control_item);
                   6664:                     } else {
                   6665:                         if (defined($changed_items{$itemnum})) {
                   6666:                             $new_control{$changed_items{$itemnum}} = $now;
                   6667:                             push(@deletions,$file_name."\0".$control_item);
                   6668:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6669:                         } else {
                   6670:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6671:                         }
                   6672:                     }
1.745     raeburn  6673:                 }
                   6674:             }
                   6675:         }
1.970     raeburn  6676:         my ($group);
                   6677:         if (&is_course($domain,$user)) {
                   6678:             ($group,my $file) = split(/\//,$file_name,2);
                   6679:         }
1.749     raeburn  6680:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6681:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6682:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6683:         #  remove lock
                   6684:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6685:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6686:         my $sqlresult =
1.970     raeburn  6687:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  6688:                                     $group);
1.749     raeburn  6689:     } else {
                   6690:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6691:     }
1.749     raeburn  6692:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6693: }
                   6694: 
1.827     raeburn  6695: sub make_public_indefinitely {
                   6696:     my ($requrl) = @_;
                   6697:     my $now = time;
                   6698:     my $action = 'activate';
                   6699:     my $aclnum = 0;
                   6700:     if (&is_portfolio_url($requrl)) {
                   6701:         my (undef,$udom,$unum,$file_name,$group) =
                   6702:             &parse_portfolio_url($requrl);
                   6703:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6704:         my %access_controls = &get_access_controls($current_perms,
                   6705:                                                    $group,$file_name);
                   6706:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6707:             my ($num,$scope,$end,$start) = 
                   6708:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6709:             if ($scope eq 'public') {
                   6710:                 if ($start <= $now && $end == 0) {
                   6711:                     $action = 'none';
                   6712:                 } else {
                   6713:                     $action = 'update';
                   6714:                     $aclnum = $num;
                   6715:                 }
                   6716:                 last;
                   6717:             }
                   6718:         }
                   6719:         if ($action eq 'none') {
                   6720:              return 'ok';
                   6721:         } else {
                   6722:             my %changes;
                   6723:             my $newend = 0;
                   6724:             my $newstart = $now;
                   6725:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6726:             $changes{$action}{$newkey} = {
                   6727:                 type => 'public',
                   6728:                 time => {
                   6729:                     start => $newstart,
                   6730:                     end   => $newend,
                   6731:                 },
                   6732:             };
                   6733:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6734:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6735:             return $outcome;
                   6736:         }
                   6737:     } else {
                   6738:         return 'invalid';
                   6739:     }
                   6740: }
                   6741: 
1.745     raeburn  6742: #------------------------------------------------------Get Marked as Read Only
                   6743: 
                   6744: sub get_marked_as_readonly {
                   6745:     my ($domain,$user,$what,$group) = @_;
                   6746:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6747:     my @readonly_files;
1.629     banghart 6748:     my $cmp1=$what;
                   6749:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6750:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6751:         if (defined($group)) {
                   6752:             if ($file_name !~ m-^\Q$group\E/-) {
                   6753:                 next;
                   6754:             }
                   6755:         }
1.561     banghart 6756:         if (ref($value) eq "ARRAY"){
                   6757:             foreach my $stored_what (@{$value}) {
1.629     banghart 6758:                 my $cmp2=$stored_what;
1.759     albertel 6759:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6760:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6761:                 }
1.629     banghart 6762:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6763:                     push(@readonly_files, $file_name);
1.745     raeburn  6764:                     last;
1.563     banghart 6765:                 } elsif (!defined($what)) {
                   6766:                     push(@readonly_files, $file_name);
1.745     raeburn  6767:                     last;
1.561     banghart 6768:                 }
                   6769:             }
1.745     raeburn  6770:         }
1.561     banghart 6771:     }
                   6772:     return @readonly_files;
                   6773: }
1.577     banghart 6774: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6775: 
1.577     banghart 6776: sub get_marked_as_readonly_hash {
1.745     raeburn  6777:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6778:     my %readonly_files;
1.745     raeburn  6779:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6780:         if (defined($group)) {
                   6781:             if ($file_name !~ m-^\Q$group\E/-) {
                   6782:                 next;
                   6783:             }
                   6784:         }
1.577     banghart 6785:         if (ref($value) eq "ARRAY"){
                   6786:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6787:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6788:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6789:                         if ($lock_descriptor eq 'graded') {
                   6790:                             $readonly_files{$file_name} = 'graded';
                   6791:                         } elsif ($lock_descriptor eq 'handback') {
                   6792:                             $readonly_files{$file_name} = 'handback';
                   6793:                         } else {
                   6794:                             if (!exists($readonly_files{$file_name})) {
                   6795:                                 $readonly_files{$file_name} = 'locked';
                   6796:                             }
                   6797:                         }
1.745     raeburn  6798:                     }
1.750     banghart 6799:                 } 
1.577     banghart 6800:             }
                   6801:         } 
                   6802:     }
                   6803:     return %readonly_files;
                   6804: }
1.559     banghart 6805: # ------------------------------------------------------------ Unmark as Read Only
                   6806: 
                   6807: sub unmark_as_readonly {
1.629     banghart 6808:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6809:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6810:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6811:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6812:     my $symb_crs = $what;
                   6813:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6814:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6815:     my ($tmp)=keys(%current_permissions);
                   6816:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6817:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6818:     foreach my $file (@readonly_files) {
1.759     albertel 6819: 	my $clean_file = &declutter_portfile($file);
                   6820: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6821: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6822:         my @new_locks;
                   6823:         my @del_keys;
                   6824:         if (ref($current_locks) eq "ARRAY"){
                   6825:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6826:                 my $compare=$locker;
1.749     raeburn  6827:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6828:                     $compare=join('',@{$locker});
1.746     raeburn  6829:                     if ($compare ne $symb_crs) {
                   6830:                         push(@new_locks, $locker);
                   6831:                     }
1.563     banghart 6832:                 }
                   6833:             }
1.650     albertel 6834:             if (scalar(@new_locks) > 0) {
1.563     banghart 6835:                 $current_permissions{$file} = \@new_locks;
                   6836:             } else {
                   6837:                 push(@del_keys, $file);
1.613     albertel 6838:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6839:                 delete($current_permissions{$file});
1.563     banghart 6840:             }
                   6841:         }
1.561     banghart 6842:     }
1.613     albertel 6843:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6844:     return;
                   6845: }
1.512     banghart 6846: 
1.17      www      6847: # ------------------------------------------------------------ Directory lister
                   6848: 
                   6849: sub dirlist {
1.955     raeburn  6850:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      6851:     $uri=~s/^\///;
                   6852:     $uri=~s/\/$//;
1.253     stredwic 6853:     my ($udom, $uname);
1.955     raeburn  6854:     if ($getuserdir) {
1.253     stredwic 6855:         $udom = $userdomain;
                   6856:         $uname = $username;
1.955     raeburn  6857:     } else {
                   6858:         (undef,$udom,$uname)=split(/\//,$uri);
                   6859:         if(defined($userdomain)) {
                   6860:             $udom = $userdomain;
                   6861:         }
                   6862:         if(defined($username)) {
                   6863:             $uname = $username;
                   6864:         }
1.253     stredwic 6865:     }
1.955     raeburn  6866:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 6867: 
1.955     raeburn  6868:     $dirRoot = $perlvar{'lonDocRoot'};
                   6869:     if (defined($getpropath)) {
                   6870:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 6871:         $dirRoot =~ s/\/$//;
1.955     raeburn  6872:     } elsif (defined($getuserdir)) {
                   6873:         my $subdir=$uname.'__';
                   6874:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6875:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   6876:                    ."/$udom/$subdir/$uname";
                   6877:     } elsif (defined($alternateRoot)) {
                   6878:         $dirRoot = $alternateRoot;
1.751     banghart 6879:     }
1.253     stredwic 6880: 
                   6881:     if($udom) {
                   6882:         if($uname) {
1.955     raeburn  6883:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  6884:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  6885:                               .':'.&escape($uname).':'.&escape($udom),
                   6886:                               &homeserver($uname,$udom));
                   6887:             if ($listing eq 'unknown_cmd') {
                   6888:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6889:                                   &homeserver($uname,$udom));
                   6890:             } else {
                   6891:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6892:             }
1.605     matthew  6893:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6894:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6895: 				  &homeserver($uname,$udom));
1.605     matthew  6896:                 @listing_results = split(/:/,$listing);
                   6897:             } else {
                   6898:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6899:             }
                   6900:             return @listing_results;
1.955     raeburn  6901:         } elsif(!$alternateRoot) {
1.800     albertel 6902:             my %allusers;
1.841     albertel 6903: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  6904:  	    foreach my $tryserver (keys(%servers)) {
                   6905:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   6906:                                   &escape($udom),$tryserver);
                   6907:                 if ($listing eq 'unknown_cmd') {
                   6908: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6909: 				      $udom, $tryserver);
                   6910:                 } else {
                   6911:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6912:                 }
1.841     albertel 6913: 		if ($listing eq 'unknown_cmd') {
                   6914: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6915: 				      $udom, $tryserver);
                   6916: 		    @listing_results = split(/:/,$listing);
                   6917: 		} else {
                   6918: 		    @listing_results =
                   6919: 			map { &unescape($_); } split(/:/,$listing);
                   6920: 		}
                   6921: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6922: 		    $listing_results[0] ne 'empty'       &&
                   6923: 		    $listing_results[0] ne 'con_lost') {
                   6924: 		    foreach my $line (@listing_results) {
                   6925: 			my ($entry) = split(/&/,$line,2);
                   6926: 			$allusers{$entry} = 1;
                   6927: 		    }
                   6928: 		}
1.253     stredwic 6929:             }
                   6930:             my $alluserstr='';
1.800     albertel 6931:             foreach my $user (sort(keys(%allusers))) {
                   6932:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6933:             }
                   6934:             $alluserstr=~s/:$//;
                   6935:             return split(/:/,$alluserstr);
                   6936:         } else {
1.800     albertel 6937:             return ('missing user name');
1.253     stredwic 6938:         }
1.955     raeburn  6939:     } elsif(!defined($getpropath)) {
1.841     albertel 6940:         my @all_domains = sort(&all_domains());
1.955     raeburn  6941:         foreach my $domain (@all_domains) {
                   6942:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6943:         }
                   6944:         return @all_domains;
                   6945:     } else {
1.800     albertel 6946:         return ('missing domain');
1.275     stredwic 6947:     }
                   6948: }
                   6949: 
                   6950: # --------------------------------------------- GetFileTimestamp
                   6951: # This function utilizes dirlist and returns the date stamp for
                   6952: # when it was last modified.  It will also return an error of -1
                   6953: # if an error occurs
                   6954: 
                   6955: sub GetFileTimestamp {
1.955     raeburn  6956:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 6957:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6958:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  6959:     my ($fileStat) = 
                   6960:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   6961:                                  undef,$getuserdir);
1.275     stredwic 6962:     my @stats = split('&', $fileStat);
                   6963:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6964:         # @stats contains first the filename, then the stat output
                   6965:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6966:     } else {
                   6967:         return -1;
1.253     stredwic 6968:     }
1.26      www      6969: }
                   6970: 
1.712     albertel 6971: sub stat_file {
                   6972:     my ($uri) = @_;
1.787     albertel 6973:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6974: 
1.955     raeburn  6975:     my ($udom,$uname,$file);
1.712     albertel 6976:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6977: 	($udom,$uname,$file) =
1.811     albertel 6978: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6979: 	$file = 'userfiles/'.$file;
                   6980:     }
                   6981:     if ($uri =~ m-^/res/-) {
                   6982: 	($udom,$uname) = 
1.807     albertel 6983: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6984: 	$file = $uri;
                   6985:     }
                   6986: 
                   6987:     if (!$udom || !$uname || !$file) {
                   6988: 	# unable to handle the uri
                   6989: 	return ();
                   6990:     }
1.956     raeburn  6991:     my $getpropath;
                   6992:     if ($file =~ /^userfiles\//) {
                   6993:         $getpropath = 1;
                   6994:     }
1.955     raeburn  6995:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 6996:     my @stats = split('&', $result);
1.721     banghart 6997:     
1.712     albertel 6998:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6999: 	shift(@stats); #filename is first
                   7000: 	return @stats;
                   7001:     }
                   7002:     return ();
                   7003: }
                   7004: 
1.26      www      7005: # -------------------------------------------------------- Value of a Condition
                   7006: 
1.713     albertel 7007: # gets the value of a specific preevaluated condition
                   7008: #    stored in the string  $env{user.state.<cid>}
                   7009: # or looks up a condition reference in the bighash and if if hasn't
                   7010: # already been evaluated recurses into docondval to get the value of
                   7011: # the condition, then memoizing it to 
                   7012: #   $env{user.state.<cid>.<condition>}
1.40      www      7013: sub directcondval {
                   7014:     my $number=shift;
1.620     albertel 7015:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 7016: 	&Apache::lonuserstate::evalstate();
                   7017:     }
1.713     albertel 7018:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   7019: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   7020:     } elsif ($number =~ /^_/) {
                   7021: 	my $sub_condition;
                   7022: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7023: 		&GDBM_READER(),0640)) {
                   7024: 	    $sub_condition=$bighash{'conditions'.$number};
                   7025: 	    untie(%bighash);
                   7026: 	}
                   7027: 	my $value = &docondval($sub_condition);
1.949     raeburn  7028: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 7029: 	return $value;
                   7030:     }
1.620     albertel 7031:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   7032:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      7033:     } else {
                   7034:        return 2;
                   7035:     }
                   7036: }
                   7037: 
1.713     albertel 7038: # get the collection of conditions for this resource
1.26      www      7039: sub condval {
                   7040:     my $condidx=shift;
1.54      www      7041:     my $allpathcond='';
1.713     albertel 7042:     foreach my $cond (split(/\|/,$condidx)) {
                   7043: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   7044: 	    $allpathcond.=
                   7045: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   7046: 	}
1.191     harris41 7047:     }
1.54      www      7048:     $allpathcond=~s/\|$//;
1.713     albertel 7049:     return &docondval($allpathcond);
                   7050: }
                   7051: 
                   7052: #evaluates an expression of conditions
                   7053: sub docondval {
                   7054:     my ($allpathcond) = @_;
                   7055:     my $result=0;
                   7056:     if ($env{'request.course.id'}
                   7057: 	&& defined($allpathcond)) {
                   7058: 	my $operand='|';
                   7059: 	my @stack;
                   7060: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   7061: 	    if ($chunk eq '(') {
                   7062: 		push @stack,($operand,$result);
                   7063: 	    } elsif ($chunk eq ')') {
                   7064: 		my $before=pop @stack;
                   7065: 		if (pop @stack eq '&') {
                   7066: 		    $result=$result>$before?$before:$result;
                   7067: 		} else {
                   7068: 		    $result=$result>$before?$result:$before;
                   7069: 		}
                   7070: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   7071: 		$operand=$chunk;
                   7072: 	    } else {
                   7073: 		my $new=directcondval($chunk);
                   7074: 		if ($operand eq '&') {
                   7075: 		    $result=$result>$new?$new:$result;
                   7076: 		} else {
                   7077: 		    $result=$result>$new?$result:$new;
                   7078: 		}
                   7079: 	    }
                   7080: 	}
1.26      www      7081:     }
                   7082:     return $result;
1.421     albertel 7083: }
                   7084: 
                   7085: # ---------------------------------------------------- Devalidate courseresdata
                   7086: 
                   7087: sub devalidatecourseresdata {
                   7088:     my ($coursenum,$coursedomain)=@_;
                   7089:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7090:     &devalidate_cache_new('courseres',$hashid);
1.28      www      7091: }
                   7092: 
1.763     www      7093: 
1.200     www      7094: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     7095: #
                   7096: #  Parameters:
                   7097: #      $coursenum    - Number of the course.
                   7098: #      $coursedomain - Domain at which the course was created.
                   7099: #  Returns:
                   7100: #     A hash of the course parameters along (I think) with timestamps
                   7101: #     and version info.
1.877     foxr     7102: 
1.624     albertel 7103: sub get_courseresdata {
                   7104:     my ($coursenum,$coursedomain)=@_;
1.200     www      7105:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   7106:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7107:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 7108:     my %dumpreply;
1.417     albertel 7109:     unless (defined($cached)) {
1.624     albertel 7110: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 7111: 	$result=\%dumpreply;
1.251     albertel 7112: 	my ($tmp) = keys(%dumpreply);
                   7113: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 7114: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 7115: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   7116: 	    return $tmp;
1.416     albertel 7117: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 7118: 	    $result=undef;
1.599     albertel 7119: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 7120: 	}
                   7121:     }
1.624     albertel 7122:     return $result;
                   7123: }
                   7124: 
1.633     albertel 7125: sub devalidateuserresdata {
                   7126:     my ($uname,$udom)=@_;
                   7127:     my $hashid="$udom:$uname";
                   7128:     &devalidate_cache_new('userres',$hashid);
                   7129: }
                   7130: 
1.624     albertel 7131: sub get_userresdata {
                   7132:     my ($uname,$udom)=@_;
                   7133:     #most student don\'t have any data set, check if there is some data
                   7134:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   7135: 
                   7136:     my $hashid="$udom:$uname";
                   7137:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   7138:     if (!defined($cached)) {
                   7139: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   7140: 	$result=\%resourcedata;
                   7141: 	&do_cache_new('userres',$hashid,$result,600);
                   7142:     }
                   7143:     my ($tmp)=keys(%$result);
                   7144:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   7145: 	return $result;
                   7146:     }
                   7147:     #error 2 occurs when the .db doesn't exist
                   7148:     if ($tmp!~/error: 2 /) {
1.672     albertel 7149: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 7150: 		 " Trying to get resource data for ".
                   7151: 		 $uname." at ".$udom.": ".
                   7152: 		 $tmp."</font>");
                   7153:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 7154: 	#&EXT_cache_set($udom,$uname);
                   7155: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 7156: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 7157:     }
                   7158:     return $tmp;
                   7159: }
1.879     foxr     7160: #----------------------------------------------- resdata - return resource data
                   7161: #  Purpose:
                   7162: #    Return resource data for either users or for a course.
                   7163: #  Parameters:
                   7164: #     $name      - Course/user name.
                   7165: #     $domain    - Name of the domain the user/course is registered on.
                   7166: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   7167: #     @which     - Array of names of resources desired.
                   7168: #  Returns:
                   7169: #     The value of the first reasource in @which that is found in the
                   7170: #     resource hash.
                   7171: #  Exceptional Conditions:
                   7172: #     If the $type passed in is not valid (not the string 'course' or 
                   7173: #     'user', an undefined  reference is returned.
                   7174: #     If none of the resources are found, an undef is returned
1.624     albertel 7175: sub resdata {
                   7176:     my ($name,$domain,$type,@which)=@_;
                   7177:     my $result;
                   7178:     if ($type eq 'course') {
                   7179: 	$result=&get_courseresdata($name,$domain);
                   7180:     } elsif ($type eq 'user') {
                   7181: 	$result=&get_userresdata($name,$domain);
                   7182:     }
                   7183:     if (!ref($result)) { return $result; }    
1.251     albertel 7184:     foreach my $item (@which) {
1.927     albertel 7185: 	if (defined($result->{$item->[0]})) {
                   7186: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 7187: 	}
1.250     albertel 7188:     }
1.291     albertel 7189:     return undef;
1.200     www      7190: }
                   7191: 
1.379     matthew  7192: #
                   7193: # EXT resource caching routines
                   7194: #
                   7195: 
                   7196: sub clear_EXT_cache_status {
1.383     albertel 7197:     &delenv('cache.EXT.');
1.379     matthew  7198: }
                   7199: 
                   7200: sub EXT_cache_status {
                   7201:     my ($target_domain,$target_user) = @_;
1.383     albertel 7202:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 7203:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  7204:         # We know already the user has no data
                   7205:         return 1;
                   7206:     } else {
                   7207:         return 0;
                   7208:     }
                   7209: }
                   7210: 
                   7211: sub EXT_cache_set {
                   7212:     my ($target_domain,$target_user) = @_;
1.383     albertel 7213:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  7214:     #&appenv({$cachename => time});
1.379     matthew  7215: }
                   7216: 
1.28      www      7217: # --------------------------------------------------------- Value of a Variable
1.58      www      7218: sub EXT {
1.715     albertel 7219: 
1.395     albertel 7220:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      7221:     unless ($varname) { return ''; }
1.218     albertel 7222:     #get real user name/domain, courseid and symb
                   7223:     my $courseid;
1.359     albertel 7224:     my $publicuser;
1.427     www      7225:     if ($symbparm) {
                   7226: 	$symbparm=&get_symb_from_alias($symbparm);
                   7227:     }
1.218     albertel 7228:     if (!($uname && $udom)) {
1.790     albertel 7229:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 7230:       if (!$symbparm) {	$symbparm=$cursymb; }
                   7231:     } else {
1.620     albertel 7232: 	$courseid=$env{'request.course.id'};
1.218     albertel 7233:     }
1.48      www      7234:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   7235:     my $rest;
1.320     albertel 7236:     if (defined($therest[0])) {
1.48      www      7237:        $rest=join('.',@therest);
                   7238:     } else {
                   7239:        $rest='';
                   7240:     }
1.320     albertel 7241: 
1.57      www      7242:     my $qualifierrest=$qualifier;
                   7243:     if ($rest) { $qualifierrest.='.'.$rest; }
                   7244:     my $spacequalifierrest=$space;
                   7245:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      7246:     if ($realm eq 'user') {
1.48      www      7247: # --------------------------------------------------------------- user.resource
                   7248: 	if ($space eq 'resource') {
1.651     albertel 7249: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   7250: 		  || defined($Apache::lonhomework::parsing_a_task))
                   7251: 		 &&
1.744     albertel 7252: 		 ($symbparm eq &symbread()) ) {	
                   7253: 		# if we are in the middle of processing the resource the
                   7254: 		# get the value we are planning on committing
                   7255:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   7256:                     return $Apache::lonhomework::results{$qualifierrest};
                   7257:                 } else {
                   7258:                     return $Apache::lonhomework::history{$qualifierrest};
                   7259:                 }
1.335     albertel 7260: 	    } else {
1.359     albertel 7261: 		my %restored;
1.620     albertel 7262: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 7263: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   7264: 		} else {
                   7265: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   7266: 		}
1.335     albertel 7267: 		return $restored{$qualifierrest};
                   7268: 	    }
1.48      www      7269: # ----------------------------------------------------------------- user.access
                   7270:         } elsif ($space eq 'access') {
1.218     albertel 7271: 	    # FIXME - not supporting calls for a specific user
1.48      www      7272:             return &allowed($qualifier,$rest);
                   7273: # ------------------------------------------ user.preferences, user.environment
                   7274:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 7275: 	    if (($uname eq $env{'user.name'}) &&
                   7276: 		($udom eq $env{'user.domain'})) {
                   7277: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 7278: 	    } else {
1.359     albertel 7279: 		my %returnhash;
                   7280: 		if (!$publicuser) {
                   7281: 		    %returnhash=&userenvironment($udom,$uname,
                   7282: 						 $qualifierrest);
                   7283: 		}
1.218     albertel 7284: 		return $returnhash{$qualifierrest};
                   7285: 	    }
1.48      www      7286: # ----------------------------------------------------------------- user.course
                   7287:         } elsif ($space eq 'course') {
1.218     albertel 7288: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 7289:             return $env{join('.',('request.course',$qualifier))};
1.48      www      7290: # ------------------------------------------------------------------- user.role
                   7291:         } elsif ($space eq 'role') {
1.218     albertel 7292: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 7293:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      7294:             if ($qualifier eq 'value') {
                   7295: 		return $role;
                   7296:             } elsif ($qualifier eq 'extent') {
                   7297:                 return $where;
                   7298:             }
                   7299: # ----------------------------------------------------------------- user.domain
                   7300:         } elsif ($space eq 'domain') {
1.218     albertel 7301:             return $udom;
1.48      www      7302: # ------------------------------------------------------------------- user.name
                   7303:         } elsif ($space eq 'name') {
1.218     albertel 7304:             return $uname;
1.48      www      7305: # ---------------------------------------------------- Any other user namespace
1.29      www      7306:         } else {
1.359     albertel 7307: 	    my %reply;
                   7308: 	    if (!$publicuser) {
                   7309: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   7310: 	    }
                   7311: 	    return $reply{$qualifierrest};
1.48      www      7312:         }
1.236     www      7313:     } elsif ($realm eq 'query') {
                   7314: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 7315:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   7316: 						[$spacequalifierrest]);
1.620     albertel 7317: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      7318:    } elsif ($realm eq 'request') {
1.48      www      7319: # ------------------------------------------------------------- request.browser
                   7320:         if ($space eq 'browser') {
1.430     www      7321: 	    if ($qualifier eq 'textremote') {
1.676     albertel 7322: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      7323: 		    return 1;
                   7324: 		} else {
                   7325: 		    return 0;
                   7326: 		}
                   7327: 	    } else {
1.620     albertel 7328: 		return $env{'browser.'.$qualifier};
1.430     www      7329: 	    }
1.57      www      7330: # ------------------------------------------------------------ request.filename
                   7331:         } else {
1.620     albertel 7332:             return $env{'request.'.$spacequalifierrest};
1.29      www      7333:         }
1.28      www      7334:     } elsif ($realm eq 'course') {
1.48      www      7335: # ---------------------------------------------------------- course.description
1.620     albertel 7336:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      7337:     } elsif ($realm eq 'resource') {
1.165     www      7338: 
1.620     albertel 7339: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 7340: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   7341: 	}
1.693     albertel 7342: 
                   7343: 	if ($space eq 'title') {
                   7344: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   7345: 	    return &gettitle($symbparm);
                   7346: 	}
                   7347: 	
                   7348: 	if ($space eq 'map') {
                   7349: 	    my ($map) = &decode_symb($symbparm);
                   7350: 	    return &symbread($map);
                   7351: 	}
1.905     albertel 7352: 	if ($space eq 'filename') {
                   7353: 	    if ($symbparm) {
                   7354: 		return &clutter((&decode_symb($symbparm))[2]);
                   7355: 	    }
                   7356: 	    return &hreflocation('',$env{'request.filename'});
                   7357: 	}
1.693     albertel 7358: 
                   7359: 	my ($section, $group, @groups);
1.593     albertel 7360: 	my ($courselevelm,$courselevel);
1.539     albertel 7361: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7362: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      7363: 
1.218     albertel 7364: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      7365: 
1.60      www      7366: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 7367: 	    my $symbp=$symbparm;
1.735     albertel 7368: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 7369: 
                   7370: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   7371: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   7372: 
1.620     albertel 7373: 	    if (($env{'user.name'} eq $uname) &&
                   7374: 		($env{'user.domain'} eq $udom)) {
                   7375: 		$section=$env{'request.course.sec'};
1.733     raeburn  7376:                 @groups = split(/:/,$env{'request.course.groups'});  
                   7377:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 7378: 	    } else {
1.539     albertel 7379: 		if (! defined($usection)) {
1.551     albertel 7380: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 7381: 		} else {
                   7382: 		    $section = $usection;
                   7383: 		}
1.733     raeburn  7384:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 7385: 	    }
                   7386: 
                   7387: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   7388: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   7389: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   7390: 
1.593     albertel 7391: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 7392: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 7393: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      7394: 
1.60      www      7395: # ----------------------------------------------------------- first, check user
1.624     albertel 7396: 
                   7397: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 7398: 				       ([$courselevelr,'resource'],
                   7399: 					[$courselevelm,'map'     ],
                   7400: 					[$courselevel, 'course'  ]));
1.931     albertel 7401: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      7402: 
1.594     albertel 7403: # ------------------------------------------------ second, check some of course
1.684     raeburn  7404:             my $coursereply;
1.691     raeburn  7405:             if (@groups > 0) {
                   7406:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   7407:                                        $mapparm,$spacequalifierrest);
1.927     albertel 7408:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  7409:             }
1.96      www      7410: 
1.684     raeburn  7411: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 7412: 				  $env{'course.'.$courseid.'.domain'},
                   7413: 				  'course',
                   7414: 				  ([$seclevelr,   'resource'],
                   7415: 				   [$seclevelm,   'map'     ],
                   7416: 				   [$seclevel,    'course'  ],
                   7417: 				   [$courselevelr,'resource']));
                   7418: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      7419: 
1.60      www      7420: # ------------------------------------------------------ third, check map parms
1.218     albertel 7421: 	    my %parmhash=();
                   7422: 	    my $thisparm='';
                   7423: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 7424: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 7425: 		    &GDBM_READER(),0640)) {
1.218     albertel 7426: 		$thisparm=$parmhash{$symbparm};
                   7427: 		untie(%parmhash);
                   7428: 	    }
1.927     albertel 7429: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 7430: 	}
1.594     albertel 7431: # ------------------------------------------ fourth, look in resource metadata
1.71      www      7432: 
1.218     albertel 7433: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 7434: 	my $filename;
                   7435: 	if (!$symbparm) { $symbparm=&symbread(); }
                   7436: 	if ($symbparm) {
1.409     www      7437: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 7438: 	} else {
1.620     albertel 7439: 	    $filename=$env{'request.filename'};
1.282     albertel 7440: 	}
                   7441: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 7442: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 7443: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 7444: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      7445: 
1.927     albertel 7446: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 7447: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7448: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 7449: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   7450: 				     $env{'course.'.$courseid.'.domain'},
                   7451: 				     'course',
1.927     albertel 7452: 				     ([$courselevelm,'map'   ],
                   7453: 				      [$courselevel, 'course']));
                   7454: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 7455: 	}
1.145     www      7456: # ------------------------------------------------------------------ Cascade up
1.218     albertel 7457: 	unless ($space eq '0') {
1.336     albertel 7458: 	    my @parts=split(/_/,$space);
                   7459: 	    my $id=pop(@parts);
                   7460: 	    my $part=join('_',@parts);
                   7461: 	    if ($part eq '') { $part='0'; }
1.927     albertel 7462: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 7463: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  7464: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 7465: 	}
1.395     albertel 7466: 	if ($recurse) { return undef; }
                   7467: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 7468: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      7469: # ---------------------------------------------------- Any other user namespace
                   7470:     } elsif ($realm eq 'environment') {
                   7471: # ----------------------------------------------------------------- environment
1.620     albertel 7472: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   7473: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 7474: 	} else {
1.770     albertel 7475: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   7476: 		return '';
                   7477: 	    }
1.219     albertel 7478: 	    my %returnhash=&userenvironment($udom,$uname,
                   7479: 					    $spacequalifierrest);
                   7480: 	    return $returnhash{$spacequalifierrest};
                   7481: 	}
1.28      www      7482:     } elsif ($realm eq 'system') {
1.48      www      7483: # ----------------------------------------------------------------- system.time
                   7484: 	if ($space eq 'time') {
                   7485: 	    return time;
                   7486:         }
1.696     albertel 7487:     } elsif ($realm eq 'server') {
                   7488: # ----------------------------------------------------------------- system.time
                   7489: 	if ($space eq 'name') {
                   7490: 	    return $ENV{'SERVER_NAME'};
                   7491:         }
1.28      www      7492:     }
1.48      www      7493:     return '';
1.61      www      7494: }
                   7495: 
1.927     albertel 7496: sub get_reply {
                   7497:     my ($reply_value) = @_;
1.940     raeburn  7498:     if (ref($reply_value) eq 'ARRAY') {
                   7499:         if (wantarray) {
                   7500: 	    return @$reply_value;
                   7501:         }
                   7502:         return $reply_value->[0];
                   7503:     } else {
                   7504:         return $reply_value;
1.927     albertel 7505:     }
                   7506: }
                   7507: 
1.691     raeburn  7508: sub check_group_parms {
                   7509:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   7510:     my @groupitems = ();
                   7511:     my $resultitem;
1.927     albertel 7512:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  7513:     foreach my $group (@{$groups}) {
                   7514:         foreach my $level (@levels) {
1.927     albertel 7515:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   7516:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  7517:         }
                   7518:     }
                   7519:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   7520:                             $env{'course.'.$courseid.'.domain'},
                   7521:                                      'course',@groupitems);
                   7522:     return $coursereply;
                   7523: }
                   7524: 
                   7525: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  7526:     my ($courseid,@groups) = @_;
                   7527:     @groups = sort(@groups);
1.691     raeburn  7528:     return @groups;
                   7529: }
                   7530: 
1.395     albertel 7531: sub packages_tab_default {
                   7532:     my ($uri,$varname)=@_;
                   7533:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 7534: 
                   7535:     my (@extension,@specifics,$do_default);
                   7536:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 7537: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 7538: 	if ($pack_type eq 'default') {
                   7539: 	    $do_default=1;
                   7540: 	} elsif ($pack_type eq 'extension') {
                   7541: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 7542: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 7543: 	    # only look at packages defaults for packages that this id is
1.738     albertel 7544: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   7545: 	}
                   7546:     }
                   7547:     # first look for a package that matches the requested part id
                   7548:     foreach my $package (@specifics) {
                   7549: 	my (undef,$pack_type,$pack_part)=@{$package};
                   7550: 	next if ($pack_part ne $part);
                   7551: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7552: 	    return $packagetab{"$pack_type&$name&default"};
                   7553: 	}
                   7554:     }
                   7555:     # look for any possible matching non extension_ package
                   7556:     foreach my $package (@specifics) {
                   7557: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 7558: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7559: 	    return $packagetab{"$pack_type&$name&default"};
                   7560: 	}
1.585     albertel 7561: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 7562: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   7563: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 7564: 	}
                   7565:     }
1.738     albertel 7566:     # look for any posible extension_ match
                   7567:     foreach my $package (@extension) {
                   7568: 	my ($package,$pack_type)=@{$package};
                   7569: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7570: 	    return $packagetab{"$pack_type&$name&default"};
                   7571: 	}
                   7572: 	if (defined($packagetab{$package."&$name&default"})) {
                   7573: 	    return $packagetab{$package."&$name&default"};
                   7574: 	}
                   7575:     }
                   7576:     # look for a global default setting
                   7577:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   7578: 	return $packagetab{"default&$name&default"};
                   7579:     }
1.395     albertel 7580:     return undef;
                   7581: }
                   7582: 
1.334     albertel 7583: sub add_prefix_and_part {
                   7584:     my ($prefix,$part)=@_;
                   7585:     my $keyroot;
                   7586:     if (defined($prefix) && $prefix !~ /^__/) {
                   7587: 	# prefix that has a part already
                   7588: 	$keyroot=$prefix;
                   7589:     } elsif (defined($prefix)) {
                   7590: 	# prefix that is missing a part
                   7591: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   7592:     } else {
                   7593: 	# no prefix at all
                   7594: 	if (defined($part)) { $keyroot='_'.$part; }
                   7595:     }
                   7596:     return $keyroot;
                   7597: }
                   7598: 
1.71      www      7599: # ---------------------------------------------------------------- Get metadata
                   7600: 
1.599     albertel 7601: my %metaentry;
1.71      www      7602: sub metadata {
1.176     www      7603:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      7604:     $uri=&declutter($uri);
1.288     albertel 7605:     # if it is a non metadata possible uri return quickly
1.529     albertel 7606:     if (($uri eq '') || 
                   7607: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 7608: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 7609:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   7610: 	return undef;
                   7611:     }
                   7612:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   7613: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 7614: 	return undef;
1.288     albertel 7615:     }
1.73      www      7616:     my $filename=$uri;
                   7617:     $uri=~s/\.meta$//;
1.172     www      7618: #
                   7619: # Is the metadata already cached?
1.177     www      7620: # Look at timestamp of caching
1.172     www      7621: # Everything is cached by the main uri, libraries are never directly cached
                   7622: #
1.428     albertel 7623:     if (!defined($liburi)) {
1.599     albertel 7624: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 7625: 	if (defined($cached)) { return $result->{':'.$what}; }
                   7626:     }
                   7627:     {
1.172     www      7628: #
                   7629: # Is this a recursive call for a library?
                   7630: #
1.599     albertel 7631: #	if (! exists($metacache{$uri})) {
                   7632: #	    $metacache{$uri}={};
                   7633: #	}
1.924     albertel 7634: 	my $cachetime = 60*60;
1.171     www      7635:         if ($liburi) {
                   7636: 	    $liburi=&declutter($liburi);
                   7637:             $filename=$liburi;
1.401     bowersj2 7638:         } else {
1.599     albertel 7639: 	    &devalidate_cache_new('meta',$uri);
                   7640: 	    undef(%metaentry);
1.401     bowersj2 7641: 	}
1.140     www      7642:         my %metathesekeys=();
1.73      www      7643:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 7644: 	my $metastring;
1.924     albertel 7645: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 7646: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 7647: 	    $metastring = 
1.929     albertel 7648: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 7649: 					  ('grade_target' => 'meta'));
                   7650: 	    $cachetime = 1; # only want this cached in the child not long term
                   7651: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 7652: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 7653: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 7654: 	    $metastring=&getfile($file);
1.489     albertel 7655: 	}
1.208     albertel 7656:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      7657:         my $token;
1.140     www      7658:         undef %metathesekeys;
1.71      www      7659:         while ($token=$parser->get_token) {
1.339     albertel 7660: 	    if ($token->[0] eq 'S') {
                   7661: 		if (defined($token->[2]->{'package'})) {
1.172     www      7662: #
                   7663: # This is a package - get package info
                   7664: #
1.339     albertel 7665: 		    my $package=$token->[2]->{'package'};
                   7666: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7667: 		    if (defined($token->[2]->{'id'})) { 
                   7668: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7669: 		    }
1.599     albertel 7670: 		    if ($metaentry{':packages'}) {
                   7671: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7672: 		    } else {
1.599     albertel 7673: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7674: 		    }
1.736     albertel 7675: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7676: 			my $part=$keyroot;
                   7677: 			$part=~s/^\_//;
1.736     albertel 7678: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7679: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7680: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7681: 			    # ignore package.tab specified default values
                   7682:                             # here &package_tab_default() will fetch those
                   7683: 			    if ($subp eq 'default') { next; }
1.736     albertel 7684: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7685: 			    my $unikey;
                   7686: 			    if ($pack =~ /_0$/) {
                   7687: 				$unikey='parameter_0_'.$name;
                   7688: 				$part=0;
                   7689: 			    } else {
                   7690: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7691: 			    }
1.339     albertel 7692: 			    if ($subp eq 'display') {
                   7693: 				$value.=' [Part: '.$part.']';
                   7694: 			    }
1.599     albertel 7695: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7696: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7697: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7698: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7699: 			    }
1.599     albertel 7700: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7701: 				$metaentry{':'.$unikey}=
                   7702: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7703: 			    }
1.339     albertel 7704: 			}
                   7705: 		    }
                   7706: 		} else {
1.172     www      7707: #
                   7708: # This is not a package - some other kind of start tag
1.339     albertel 7709: #
                   7710: 		    my $entry=$token->[1];
                   7711: 		    my $unikey;
                   7712: 		    if ($entry eq 'import') {
                   7713: 			$unikey='';
                   7714: 		    } else {
                   7715: 			$unikey=$entry;
                   7716: 		    }
                   7717: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7718: 
                   7719: 		    if (defined($token->[2]->{'id'})) { 
                   7720: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7721: 		    }
1.175     www      7722: 
1.339     albertel 7723: 		    if ($entry eq 'import') {
1.175     www      7724: #
                   7725: # Importing a library here
1.339     albertel 7726: #
                   7727: 			if ($depthcount<20) {
                   7728: 			    my $location=$parser->get_text('/import');
                   7729: 			    my $dir=$filename;
                   7730: 			    $dir=~s|[^/]*$||;
                   7731: 			    $location=&filelocation($dir,$location);
1.736     albertel 7732: 			    my $metadata = 
                   7733: 				&metadata($uri,'keys', $location,$unikey,
                   7734: 					  $depthcount+1);
                   7735: 			    foreach my $meta (split(',',$metadata)) {
                   7736: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7737: 				$metathesekeys{$meta}=1;
1.339     albertel 7738: 			    }
                   7739: 			}
                   7740: 		    } else { 
                   7741: 			
                   7742: 			if (defined($token->[2]->{'name'})) { 
                   7743: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7744: 			}
                   7745: 			$metathesekeys{$unikey}=1;
1.736     albertel 7746: 			foreach my $param (@{$token->[3]}) {
                   7747: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7748: 				$token->[2]->{$param};
1.339     albertel 7749: 			}
                   7750: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7751: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7752: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7753: 		 # only ws inside the tag, and not in default, so use default
                   7754: 		 # as value
1.599     albertel 7755: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7756: 			} elsif ( $internaltext =~ /\S/ ) {
                   7757: 		  # something interesting inside the tag
                   7758: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7759: 			} else {
1.908     albertel 7760: 		  # no interesting values, don't set a default
1.339     albertel 7761: 			}
1.172     www      7762: # end of not-a-package not-a-library import
1.339     albertel 7763: 		    }
1.172     www      7764: # end of not-a-package start tag
1.339     albertel 7765: 		}
1.172     www      7766: # the next is the end of "start tag"
1.339     albertel 7767: 	    }
                   7768: 	}
1.483     albertel 7769: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7770: 	$extension = lc($extension);
                   7771: 	if ($extension eq 'htm') { $extension='html'; }
                   7772: 
1.737     albertel 7773: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7774: 	    #no specific packages #how's our extension
                   7775: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7776: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7777: 					 \%metathesekeys);
                   7778: 	}
1.883     albertel 7779: 
                   7780: 	if (!exists($metaentry{':packages'})
                   7781: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7782: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7783: 		#no specific packages well let's get default then
                   7784: 		if ($key!~/^default&/) { next; }
1.488     albertel 7785: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7786: 					     \%metathesekeys);
                   7787: 	    }
                   7788: 	}
1.338     www      7789: # are there custom rights to evaluate
1.599     albertel 7790: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7791: 
1.338     www      7792:     #
                   7793:     # Importing a rights file here
1.339     albertel 7794:     #
                   7795: 	    unless ($depthcount) {
1.599     albertel 7796: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7797: 		my $dir=$filename;
                   7798: 		$dir=~s|[^/]*$||;
                   7799: 		$location=&filelocation($dir,$location);
1.736     albertel 7800: 		my $rights_metadata =
                   7801: 		    &metadata($uri,'keys',$location,'_rights',
                   7802: 			      $depthcount+1);
                   7803: 		foreach my $rights (split(',',$rights_metadata)) {
                   7804: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7805: 		    $metathesekeys{$rights}=1;
1.339     albertel 7806: 		}
                   7807: 	    }
                   7808: 	}
1.737     albertel 7809: 	# uniqifiy package listing
                   7810: 	my %seen;
                   7811: 	my @uniq_packages =
                   7812: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7813: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7814: 
                   7815: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7816: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7817: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7818: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7819: # this is the end of "was not already recently cached
1.71      www      7820:     }
1.599     albertel 7821:     return $metaentry{':'.$what};
1.261     albertel 7822: }
                   7823: 
1.488     albertel 7824: sub metadata_create_package_def {
1.483     albertel 7825:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7826:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7827:     if ($subp eq 'default') { next; }
                   7828:     
1.599     albertel 7829:     if (defined($metaentry{':packages'})) {
                   7830: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7831:     } else {
1.599     albertel 7832: 	$metaentry{':packages'}=$package;
1.483     albertel 7833:     }
                   7834:     my $value=$packagetab{$key};
                   7835:     my $unikey;
                   7836:     $unikey='parameter_0_'.$name;
1.599     albertel 7837:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7838:     $$metathesekeys{$unikey}=1;
1.599     albertel 7839:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7840: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7841:     }
1.599     albertel 7842:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7843: 	$metaentry{':'.$unikey}=
                   7844: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7845:     }
                   7846: }
                   7847: 
1.261     albertel 7848: sub metadata_generate_part0 {
                   7849:     my ($metadata,$metacache,$uri) = @_;
                   7850:     my %allnames;
1.737     albertel 7851:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7852: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7853: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7854: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7855: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7856: 	    $allnames{$name}=$part;
                   7857: 	  }
                   7858: 	}
                   7859:     }
                   7860:     foreach my $name (keys(%allnames)) {
                   7861:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7862:       my $key=":parameter_0_$name";
1.261     albertel 7863:       $$metacache{"$key.part"}='0';
                   7864:       $$metacache{"$key.name"}=$name;
1.428     albertel 7865:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7866: 					   $allnames{$name}.'_'.$name.
                   7867: 					   '.type'};
1.428     albertel 7868:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7869: 			     '.display'};
1.644     www      7870:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7871:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7872:       $$metacache{"$key.display"}=$olddis;
                   7873:     }
1.71      www      7874: }
                   7875: 
1.764     albertel 7876: # ------------------------------------------------------ Devalidate title cache
                   7877: 
                   7878: sub devalidate_title_cache {
                   7879:     my ($url)=@_;
                   7880:     if (!$env{'request.course.id'}) { return; }
                   7881:     my $symb=&symbread($url);
                   7882:     if (!$symb) { return; }
                   7883:     my $key=$env{'request.course.id'}."\0".$symb;
                   7884:     &devalidate_cache_new('title',$key);
                   7885: }
                   7886: 
1.301     www      7887: # ------------------------------------------------- Get the title of a resource
                   7888: 
                   7889: sub gettitle {
                   7890:     my $urlsymb=shift;
                   7891:     my $symb=&symbread($urlsymb);
1.534     albertel 7892:     if ($symb) {
1.620     albertel 7893: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7894: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7895: 	if (defined($cached)) { 
                   7896: 	    return $result;
                   7897: 	}
1.534     albertel 7898: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7899: 	my $title='';
1.907     albertel 7900: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7901: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7902: 	} else {
                   7903: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7904: 		    &GDBM_READER(),0640)) {
                   7905: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7906: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7907: 		untie(%bighash);
                   7908: 	    }
1.534     albertel 7909: 	}
                   7910: 	$title=~s/\&colon\;/\:/gs;
                   7911: 	if ($title) {
1.599     albertel 7912: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7913: 	}
                   7914: 	$urlsymb=$url;
                   7915:     }
                   7916:     my $title=&metadata($urlsymb,'title');
                   7917:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7918:     return $title;
1.301     www      7919: }
1.613     albertel 7920: 
1.614     albertel 7921: sub get_slot {
                   7922:     my ($which,$cnum,$cdom)=@_;
                   7923:     if (!$cnum || !$cdom) {
1.790     albertel 7924: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7925: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7926: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7927:     }
1.703     albertel 7928:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7929:     my %slotinfo;
                   7930:     if (exists($remembered{$key})) {
                   7931: 	$slotinfo{$which} = $remembered{$key};
                   7932:     } else {
                   7933: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7934: 	&Apache::lonhomework::showhash(%slotinfo);
                   7935: 	my ($tmp)=keys(%slotinfo);
                   7936: 	if ($tmp=~/^error:/) { return (); }
                   7937: 	$remembered{$key} = $slotinfo{$which};
                   7938:     }
1.616     albertel 7939:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7940: 	return %{$slotinfo{$which}};
                   7941:     }
                   7942:     return $slotinfo{$which};
1.614     albertel 7943: }
1.31      www      7944: # ------------------------------------------------- Update symbolic store links
                   7945: 
                   7946: sub symblist {
                   7947:     my ($mapname,%newhash)=@_;
1.438     www      7948:     $mapname=&deversion(&declutter($mapname));
1.31      www      7949:     my %hash;
1.620     albertel 7950:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7951:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7952:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  7953: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 7954: 		next if ($url eq 'last_known'
                   7955: 			 && $env{'form.no_update_last_known'});
                   7956: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7957: 						    $newhash{$url}->[1],
                   7958: 						    $newhash{$url}->[0]);
1.191     harris41 7959:             }
1.31      www      7960:             if (untie(%hash)) {
                   7961: 		return 'ok';
                   7962:             }
                   7963:         }
                   7964:     }
                   7965:     return 'error';
1.212     www      7966: }
                   7967: 
                   7968: # --------------------------------------------------------------- Verify a symb
                   7969: 
                   7970: sub symbverify {
1.510     www      7971:     my ($symb,$thisurl)=@_;
                   7972:     my $thisfn=$thisurl;
1.439     www      7973:     $thisfn=&declutter($thisfn);
1.215     www      7974: # direct jump to resource in page or to a sequence - will construct own symbs
                   7975:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7976: # check URL part
1.409     www      7977:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7978: 
1.431     www      7979:     unless ($url eq $thisfn) { return 0; }
1.213     www      7980: 
1.216     www      7981:     $symb=&symbclean($symb);
1.510     www      7982:     $thisurl=&deversion($thisurl);
1.439     www      7983:     $thisfn=&deversion($thisfn);
1.213     www      7984: 
                   7985:     my %bighash;
                   7986:     my $okay=0;
1.431     www      7987: 
1.620     albertel 7988:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7989:                             &GDBM_READER(),0640)) {
1.510     www      7990:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7991:         unless ($ids) { 
1.510     www      7992:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7993:         }
                   7994:         if ($ids) {
                   7995: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7996: 	    foreach my $id (split(/\,/,$ids)) {
                   7997: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7998:                if (
                   7999:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   8000:    eq $symb) { 
1.620     albertel 8001: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 8002: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 8003: 		       $okay=1; 
                   8004: 		   }
                   8005: 	       }
1.216     www      8006: 	   }
                   8007:         }
1.213     www      8008: 	untie(%bighash);
                   8009:     }
                   8010:     return $okay;
1.31      www      8011: }
                   8012: 
1.210     www      8013: # --------------------------------------------------------------- Clean-up symb
                   8014: 
                   8015: sub symbclean {
                   8016:     my $symb=shift;
1.568     albertel 8017:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      8018: # remove version from map
                   8019:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      8020: 
1.210     www      8021: # remove version from URL
                   8022:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      8023: 
1.507     www      8024: # remove wrapper
                   8025: 
1.510     www      8026:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 8027:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      8028:     return $symb;
1.409     www      8029: }
                   8030: 
                   8031: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 8032: 
                   8033: sub encode_symb {
                   8034:     my ($map,$resid,$url)=@_;
                   8035:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   8036: }
1.409     www      8037: 
                   8038: sub decode_symb {
1.568     albertel 8039:     my $symb=shift;
                   8040:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   8041:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      8042:     return (&fixversion($map),$resid,&fixversion($url));
                   8043: }
                   8044: 
                   8045: sub fixversion {
                   8046:     my $fn=shift;
1.609     banghart 8047:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      8048:     my %bighash;
                   8049:     my $uri=&clutter($fn);
1.620     albertel 8050:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      8051: # is this cached?
1.599     albertel 8052:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      8053:     if (defined($cached)) { return $result; }
                   8054: # unfortunately not cached, or expired
1.620     albertel 8055:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      8056: 	    &GDBM_READER(),0640)) {
                   8057:  	if ($bighash{'version_'.$uri}) {
                   8058:  	    my $version=$bighash{'version_'.$uri};
1.444     www      8059:  	    unless (($version eq 'mostrecent') || 
                   8060: 		    ($version==&getversion($uri))) {
1.440     www      8061:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   8062:  	    }
                   8063:  	}
                   8064:  	untie %bighash;
1.413     www      8065:     }
1.599     albertel 8066:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      8067: }
                   8068: 
                   8069: sub deversion {
                   8070:     my $url=shift;
                   8071:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   8072:     return $url;
1.210     www      8073: }
                   8074: 
1.31      www      8075: # ------------------------------------------------------ Return symb list entry
                   8076: 
                   8077: sub symbread {
1.249     www      8078:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 8079:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 8080:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      8081: # no filename provided? try from environment
1.44      www      8082:     unless ($thisfn) {
1.620     albertel 8083:         if ($env{'request.symb'}) {
                   8084: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 8085: 	}
1.620     albertel 8086: 	$thisfn=$env{'request.filename'};
1.44      www      8087:     }
1.569     albertel 8088:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      8089: # is that filename actually a symb? Verify, clean, and return
                   8090:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 8091: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 8092: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 8093: 	}
1.242     www      8094:     }
1.44      www      8095:     $thisfn=declutter($thisfn);
1.31      www      8096:     my %hash;
1.37      www      8097:     my %bighash;
                   8098:     my $syval='';
1.620     albertel 8099:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  8100:         my $targetfn = $thisfn;
1.609     banghart 8101:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  8102:             $targetfn = 'adm/wrapper/'.$thisfn;
                   8103:         }
1.687     albertel 8104: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   8105: 	    $targetfn=$1;
                   8106: 	}
1.620     albertel 8107:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8108:                       &GDBM_READER(),0640)) {
1.481     raeburn  8109: 	    $syval=$hash{$targetfn};
1.37      www      8110:             untie(%hash);
                   8111:         }
                   8112: # ---------------------------------------------------------- There was an entry
                   8113:         if ($syval) {
1.601     albertel 8114: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 8115: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  8116: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 8117: 		    #return $env{$cache_str}='';
1.601     albertel 8118: 		#}    
                   8119: 		#$syval.=$1;
                   8120: 	    #}
1.37      www      8121:         } else {
                   8122: # ------------------------------------------------------- Was not in symb table
1.620     albertel 8123:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8124:                             &GDBM_READER(),0640)) {
1.37      www      8125: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      8126:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      8127:               unless ($ids) { 
                   8128:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      8129:               }
                   8130:               unless ($ids) {
                   8131: # alias?
                   8132: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      8133:               }
1.37      www      8134:               if ($ids) {
                   8135: # ------------------------------------------------------------------- Has ID(s)
                   8136:                  my @possibilities=split(/\,/,$ids);
1.39      www      8137:                  if ($#possibilities==0) {
                   8138: # ----------------------------------------------- There is only one possibility
1.37      www      8139: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 8140: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   8141: 						    $resid,$thisfn);
1.249     www      8142:                  } elsif (!$donotrecurse) {
1.39      www      8143: # ------------------------------------------ There is more than one possibility
                   8144:                      my $realpossible=0;
1.800     albertel 8145:                      foreach my $id (@possibilities) {
                   8146: 			 my $file=$bighash{'src_'.$id};
1.39      www      8147:                          if (&allowed('bre',$file)) {
1.800     albertel 8148:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      8149:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   8150: 				$realpossible++;
1.626     albertel 8151:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   8152: 						    $resid,$thisfn);
1.39      www      8153:                             }
                   8154: 			 }
1.191     harris41 8155:                      }
1.39      www      8156: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      8157:                  } else {
                   8158:                      $syval='';
1.37      www      8159:                  }
                   8160: 	      }
                   8161:               untie(%bighash)
1.481     raeburn  8162:            }
1.31      www      8163:         }
1.62      www      8164:         if ($syval) {
1.620     albertel 8165: 	    return $env{$cache_str}=$syval;
1.62      www      8166:         }
1.31      www      8167:     }
1.949     raeburn  8168:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 8169:     return $env{$cache_str}='';
1.31      www      8170: }
                   8171: 
                   8172: # ---------------------------------------------------------- Return random seed
                   8173: 
1.32      www      8174: sub numval {
                   8175:     my $txt=shift;
                   8176:     $txt=~tr/A-J/0-9/;
                   8177:     $txt=~tr/a-j/0-9/;
                   8178:     $txt=~tr/K-T/0-9/;
                   8179:     $txt=~tr/k-t/0-9/;
                   8180:     $txt=~tr/U-Z/0-5/;
                   8181:     $txt=~tr/u-z/0-5/;
                   8182:     $txt=~s/\D//g;
1.564     albertel 8183:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      8184:     return int($txt);
1.368     albertel 8185: }
                   8186: 
1.484     albertel 8187: sub numval2 {
                   8188:     my $txt=shift;
                   8189:     $txt=~tr/A-J/0-9/;
                   8190:     $txt=~tr/a-j/0-9/;
                   8191:     $txt=~tr/K-T/0-9/;
                   8192:     $txt=~tr/k-t/0-9/;
                   8193:     $txt=~tr/U-Z/0-5/;
                   8194:     $txt=~tr/u-z/0-5/;
                   8195:     $txt=~s/\D//g;
                   8196:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   8197:     my $total;
                   8198:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 8199:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 8200:     return int($total);
                   8201: }
                   8202: 
1.575     albertel 8203: sub numval3 {
                   8204:     use integer;
                   8205:     my $txt=shift;
                   8206:     $txt=~tr/A-J/0-9/;
                   8207:     $txt=~tr/a-j/0-9/;
                   8208:     $txt=~tr/K-T/0-9/;
                   8209:     $txt=~tr/k-t/0-9/;
                   8210:     $txt=~tr/U-Z/0-5/;
                   8211:     $txt=~tr/u-z/0-5/;
                   8212:     $txt=~s/\D//g;
                   8213:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   8214:     my $total;
                   8215:     foreach my $val (@txts) { $total+=$val; }
                   8216:     if ($_64bit) { $total=(($total<<32)>>32); }
                   8217:     return $total;
                   8218: }
                   8219: 
1.675     albertel 8220: sub digest {
                   8221:     my ($data)=@_;
                   8222:     my $digest=&Digest::MD5::md5($data);
                   8223:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   8224:     my ($e,$f);
                   8225:     {
                   8226:         use integer;
                   8227:         $e=($a+$b);
                   8228:         $f=($c+$d);
                   8229:         if ($_64bit) {
                   8230:             $e=(($e<<32)>>32);
                   8231:             $f=(($f<<32)>>32);
                   8232:         }
                   8233:     }
                   8234:     if (wantarray) {
                   8235: 	return ($e,$f);
                   8236:     } else {
                   8237: 	my $g;
                   8238: 	{
                   8239: 	    use integer;
                   8240: 	    $g=($e+$f);
                   8241: 	    if ($_64bit) {
                   8242: 		$g=(($g<<32)>>32);
                   8243: 	    }
                   8244: 	}
                   8245: 	return $g;
                   8246:     }
                   8247: }
                   8248: 
1.368     albertel 8249: sub latest_rnd_algorithm_id {
1.675     albertel 8250:     return '64bit5';
1.366     albertel 8251: }
1.32      www      8252: 
1.503     albertel 8253: sub get_rand_alg {
                   8254:     my ($courseid)=@_;
1.790     albertel 8255:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 8256:     if ($courseid) {
1.620     albertel 8257: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 8258:     }
                   8259:     return &latest_rnd_algorithm_id();
                   8260: }
                   8261: 
1.562     albertel 8262: sub validCODE {
                   8263:     my ($CODE)=@_;
                   8264:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   8265:     return 0;
                   8266: }
                   8267: 
1.491     albertel 8268: sub getCODE {
1.620     albertel 8269:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 8270:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   8271: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   8272: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 8273: 	return $Apache::lonhomework::history{'resource.CODE'};
                   8274:     }
                   8275:     return undef;
                   8276: }
                   8277: 
1.31      www      8278: sub rndseed {
1.155     albertel 8279:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 8280:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 8281:     if (!defined($symb)) {
1.366     albertel 8282: 	unless ($symb=$wsymb) { return time; }
                   8283:     }
                   8284:     if (!$courseid) { $courseid=$wcourseid; }
                   8285:     if (!$domain) { $domain=$wdomain; }
                   8286:     if (!$username) { $username=$wusername }
1.503     albertel 8287:     my $which=&get_rand_alg();
1.803     albertel 8288: 
1.491     albertel 8289:     if (defined(&getCODE())) {
1.675     albertel 8290: 	if ($which eq '64bit5') {
                   8291: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   8292: 	} elsif ($which eq '64bit4') {
1.575     albertel 8293: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   8294: 	} else {
                   8295: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   8296: 	}
1.675     albertel 8297:     } elsif ($which eq '64bit5') {
                   8298: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 8299:     } elsif ($which eq '64bit4') {
                   8300: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 8301:     } elsif ($which eq '64bit3') {
                   8302: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 8303:     } elsif ($which eq '64bit2') {
                   8304: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 8305:     } elsif ($which eq '64bit') {
                   8306: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   8307:     }
                   8308:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   8309: }
                   8310: 
                   8311: sub rndseed_32bit {
                   8312:     my ($symb,$courseid,$domain,$username)=@_;
                   8313:     {
                   8314: 	use integer;
                   8315: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   8316: 	my $symbseed=numval($symb) << 22;
                   8317: 	my $namechck=unpack("%32C*",$username) << 17;
                   8318: 	my $nameseed=numval($username) << 12;
                   8319: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   8320: 	my $courseseed=unpack("%32C*",$courseid);
                   8321: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 8322: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8323: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8324: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 8325: 	return $num;
                   8326:     }
                   8327: }
                   8328: 
                   8329: sub rndseed_64bit {
                   8330:     my ($symb,$courseid,$domain,$username)=@_;
                   8331:     {
                   8332: 	use integer;
                   8333: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   8334: 	my $symbseed=numval($symb) << 10;
                   8335: 	my $namechck=unpack("%32S*",$username);
                   8336: 	
                   8337: 	my $nameseed=numval($username) << 21;
                   8338: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   8339: 	my $courseseed=unpack("%32S*",$courseid);
                   8340: 	
                   8341: 	my $num1=$symbchck+$symbseed+$namechck;
                   8342: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8343: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8344: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8345: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 8346: 	return "$num1,$num2";
1.155     albertel 8347:     }
1.366     albertel 8348: }
                   8349: 
1.443     albertel 8350: sub rndseed_64bit2 {
                   8351:     my ($symb,$courseid,$domain,$username)=@_;
                   8352:     {
                   8353: 	use integer;
                   8354: 	# strings need to be an even # of cahracters long, it it is odd the
                   8355:         # last characters gets thrown away
                   8356: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8357: 	my $symbseed=numval($symb) << 10;
                   8358: 	my $namechck=unpack("%32S*",$username.' ');
                   8359: 	
                   8360: 	my $nameseed=numval($username) << 21;
1.501     albertel 8361: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8362: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8363: 	
                   8364: 	my $num1=$symbchck+$symbseed+$namechck;
                   8365: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8366: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8367: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 8368: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 8369: 	return "$num1,$num2";
                   8370:     }
                   8371: }
                   8372: 
                   8373: sub rndseed_64bit3 {
                   8374:     my ($symb,$courseid,$domain,$username)=@_;
                   8375:     {
                   8376: 	use integer;
                   8377: 	# strings need to be an even # of cahracters long, it it is odd the
                   8378:         # last characters gets thrown away
                   8379: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8380: 	my $symbseed=numval2($symb) << 10;
                   8381: 	my $namechck=unpack("%32S*",$username.' ');
                   8382: 	
                   8383: 	my $nameseed=numval2($username) << 21;
1.443     albertel 8384: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8385: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8386: 	
                   8387: 	my $num1=$symbchck+$symbseed+$namechck;
                   8388: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8389: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8390: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 8391: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8392: 	
1.503     albertel 8393: 	return "$num1:$num2";
1.443     albertel 8394:     }
                   8395: }
                   8396: 
1.575     albertel 8397: sub rndseed_64bit4 {
                   8398:     my ($symb,$courseid,$domain,$username)=@_;
                   8399:     {
                   8400: 	use integer;
                   8401: 	# strings need to be an even # of cahracters long, it it is odd the
                   8402:         # last characters gets thrown away
                   8403: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8404: 	my $symbseed=numval3($symb) << 10;
                   8405: 	my $namechck=unpack("%32S*",$username.' ');
                   8406: 	
                   8407: 	my $nameseed=numval3($username) << 21;
                   8408: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8409: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8410: 	
                   8411: 	my $num1=$symbchck+$symbseed+$namechck;
                   8412: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8413: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8414: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 8415: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8416: 	
                   8417: 	return "$num1:$num2";
                   8418:     }
                   8419: }
                   8420: 
1.675     albertel 8421: sub rndseed_64bit5 {
                   8422:     my ($symb,$courseid,$domain,$username)=@_;
                   8423:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   8424:     return "$num1:$num2";
                   8425: }
                   8426: 
1.366     albertel 8427: sub rndseed_CODE_64bit {
                   8428:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 8429:     {
1.366     albertel 8430: 	use integer;
1.443     albertel 8431: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 8432: 	my $symbseed=numval2($symb);
1.491     albertel 8433: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8434: 	my $CODEseed=numval(&getCODE());
1.443     albertel 8435: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 8436: 	my $num1=$symbseed+$CODEchck;
                   8437: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8438: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8439: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 8440: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8441: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 8442: 	return "$num1:$num2";
1.366     albertel 8443:     }
                   8444: }
                   8445: 
1.575     albertel 8446: sub rndseed_CODE_64bit4 {
                   8447:     my ($symb,$courseid,$domain,$username)=@_;
                   8448:     {
                   8449: 	use integer;
                   8450: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   8451: 	my $symbseed=numval3($symb);
                   8452: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8453: 	my $CODEseed=numval3(&getCODE());
                   8454: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8455: 	my $num1=$symbseed+$CODEchck;
                   8456: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8457: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8458: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 8459: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8460: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   8461: 	return "$num1:$num2";
                   8462:     }
                   8463: }
                   8464: 
1.675     albertel 8465: sub rndseed_CODE_64bit5 {
                   8466:     my ($symb,$courseid,$domain,$username)=@_;
                   8467:     my $code = &getCODE();
                   8468:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   8469:     return "$num1:$num2";
                   8470: }
                   8471: 
1.366     albertel 8472: sub setup_random_from_rndseed {
                   8473:     my ($rndseed)=@_;
1.503     albertel 8474:     if ($rndseed =~/([,:])/) {
                   8475: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 8476: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   8477:     } else {
                   8478: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 8479:     }
1.36      albertel 8480: }
                   8481: 
1.474     albertel 8482: sub latest_receipt_algorithm_id {
1.835     albertel 8483:     return 'receipt3';
1.474     albertel 8484: }
                   8485: 
1.480     www      8486: sub recunique {
                   8487:     my $fucourseid=shift;
                   8488:     my $unique;
1.835     albertel 8489:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   8490: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8491: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      8492:     } else {
                   8493: 	$unique=$perlvar{'lonReceipt'};
                   8494:     }
                   8495:     return unpack("%32C*",$unique);
                   8496: }
                   8497: 
                   8498: sub recprefix {
                   8499:     my $fucourseid=shift;
                   8500:     my $prefix;
1.835     albertel 8501:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   8502: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8503: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      8504:     } else {
                   8505: 	$prefix=$perlvar{'lonHostID'};
                   8506:     }
                   8507:     return unpack("%32C*",$prefix);
                   8508: }
                   8509: 
1.76      www      8510: sub ireceipt {
1.474     albertel 8511:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 8512: 
                   8513:     my $return =&recprefix($fucourseid).'-';
                   8514: 
                   8515:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   8516: 	$env{'request.state'} eq 'construct') {
                   8517: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   8518: 	return $return;
                   8519:     }
                   8520: 
1.76      www      8521:     my $cuname=unpack("%32C*",$funame);
                   8522:     my $cudom=unpack("%32C*",$fudom);
                   8523:     my $cucourseid=unpack("%32C*",$fucourseid);
                   8524:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      8525:     my $cunique=&recunique($fucourseid);
1.474     albertel 8526:     my $cpart=unpack("%32S*",$part);
1.835     albertel 8527:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   8528: 
1.790     albertel 8529: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 8530: 			       
                   8531: 	$return.= ($cunique%$cuname+
                   8532: 		   $cunique%$cudom+
                   8533: 		   $cusymb%$cuname+
                   8534: 		   $cusymb%$cudom+
                   8535: 		   $cucourseid%$cuname+
                   8536: 		   $cucourseid%$cudom+
                   8537: 		   $cpart%$cuname+
                   8538: 		   $cpart%$cudom);
                   8539:     } else {
                   8540: 	$return.= ($cunique%$cuname+
                   8541: 		   $cunique%$cudom+
                   8542: 		   $cusymb%$cuname+
                   8543: 		   $cusymb%$cudom+
                   8544: 		   $cucourseid%$cuname+
                   8545: 		   $cucourseid%$cudom);
                   8546:     }
                   8547:     return $return;
1.76      www      8548: }
                   8549: 
                   8550: sub receipt {
1.474     albertel 8551:     my ($part)=@_;
1.790     albertel 8552:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 8553:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      8554: }
1.260     ng       8555: 
1.790     albertel 8556: sub whichuser {
                   8557:     my ($passedsymb)=@_;
                   8558:     my ($symb,$courseid,$domain,$name,$publicuser);
                   8559:     if (defined($env{'form.grade_symb'})) {
                   8560: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   8561: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   8562: 	if (!$allowed &&
                   8563: 	    exists($env{'request.course.sec'}) &&
                   8564: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   8565: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   8566: 			      '/'.$env{'request.course.sec'});
                   8567: 	}
                   8568: 	if ($allowed) {
                   8569: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   8570: 	    $courseid=$tmp_courseid;
                   8571: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   8572: 	    ($name)=&get_env_multiple('form.grade_username');
                   8573: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   8574: 	}
                   8575:     }
                   8576:     if (!$passedsymb) {
                   8577: 	$symb=&symbread();
                   8578:     } else {
                   8579: 	$symb=$passedsymb;
                   8580:     }
                   8581:     $courseid=$env{'request.course.id'};
                   8582:     $domain=$env{'user.domain'};
                   8583:     $name=$env{'user.name'};
                   8584:     if ($name eq 'public' && $domain eq 'public') {
                   8585: 	if (!defined($env{'form.username'})) {
                   8586: 	    $env{'form.username'}.=time.rand(10000000);
                   8587: 	}
                   8588: 	$name.=$env{'form.username'};
                   8589:     }
                   8590:     return ($symb,$courseid,$domain,$name,$publicuser);
                   8591: 
                   8592: }
                   8593: 
1.36      albertel 8594: # ------------------------------------------------------------ Serves up a file
1.472     albertel 8595: # returns either the contents of the file or 
                   8596: # -1 if the file doesn't exist
1.481     raeburn  8597: #
                   8598: # if the target is a file that was uploaded via DOCS, 
                   8599: # a check will be made to see if a current copy exists on the local server,
                   8600: # if it does this will be served, otherwise a copy will be retrieved from
                   8601: # the home server for the course and stored in /home/httpd/html/userfiles on
                   8602: # the local server.   
1.472     albertel 8603: 
1.36      albertel 8604: sub getfile {
1.538     albertel 8605:     my ($file) = @_;
1.609     banghart 8606:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 8607:     &repcopy($file);
                   8608:     return &readfile($file);
                   8609: }
                   8610: 
                   8611: sub repcopy_userfile {
                   8612:     my ($file)=@_;
1.609     banghart 8613:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 8614:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 8615:     my ($cdom,$cnum,$filename) = 
1.811     albertel 8616: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 8617:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   8618:     if (-e "$file") {
1.828     www      8619: # we already have a local copy, check it out
1.538     albertel 8620: 	my @fileinfo = stat($file);
1.828     www      8621: 	my $rtncode;
                   8622: 	my $info;
1.538     albertel 8623: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 8624: 	if ($lwpresp ne 'ok') {
1.828     www      8625: # there is no such file anymore, even though we had a local copy
1.482     albertel 8626: 	    if ($rtncode eq '404') {
1.538     albertel 8627: 		unlink($file);
1.482     albertel 8628: 	    }
                   8629: 	    return -1;
                   8630: 	}
                   8631: 	if ($info < $fileinfo[9]) {
1.828     www      8632: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  8633: 	    return 'ok';
1.828     www      8634: 	} else {
                   8635: # the file is outdated, get rid of it
                   8636: 	    unlink($file);
1.482     albertel 8637: 	}
1.828     www      8638:     }
                   8639: # one way or the other, at this point, we don't have the file
                   8640: # construct the correct path for the file
                   8641:     my @parts = ($cdom,$cnum); 
                   8642:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   8643: 	push @parts, split(/\//,$1);
                   8644:     }
                   8645:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   8646:     foreach my $part (@parts) {
                   8647: 	$path .= '/'.$part;
                   8648: 	if (!-e $path) {
                   8649: 	    mkdir($path,0770);
1.482     albertel 8650: 	}
                   8651:     }
1.828     www      8652: # now the path exists for sure
                   8653: # get a user agent
                   8654:     my $ua=new LWP::UserAgent;
                   8655:     my $transferfile=$file.'.in.transfer';
                   8656: # FIXME: this should flock
                   8657:     if (-e $transferfile) { return 'ok'; }
                   8658:     my $request;
                   8659:     $uri=~s/^\///;
1.980     raeburn  8660:     my $homeserver = &homeserver($cnum,$cdom);
                   8661:     my $protocol = $protocol{$homeserver};
                   8662:     $protocol = 'http' if ($protocol ne 'https');
                   8663:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      8664:     my $response=$ua->request($request,$transferfile);
                   8665: # did it work?
                   8666:     if ($response->is_error()) {
                   8667: 	unlink($transferfile);
                   8668: 	&logthis("Userfile repcopy failed for $uri");
                   8669: 	return -1;
                   8670:     }
                   8671: # worked, rename the transfer file
                   8672:     rename($transferfile,$file);
1.607     raeburn  8673:     return 'ok';
1.481     raeburn  8674: }
                   8675: 
1.517     albertel 8676: sub tokenwrapper {
                   8677:     my $uri=shift;
1.980     raeburn  8678:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 8679:     $uri=~s|^/||;
1.620     albertel 8680:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8681:     my $token=$1;
1.552     albertel 8682:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8683:     if ($udom && $uname && $file) {
                   8684: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8685:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  8686:         my $homeserver = &homeserver($uname,$udom);
                   8687:         my $protocol = $protocol{$homeserver};
                   8688:         $protocol = 'http' if ($protocol ne 'https');
                   8689:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 8690:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8691:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8692:     } else {
                   8693:         return '/adm/notfound.html';
                   8694:     }
                   8695: }
                   8696: 
1.828     www      8697: # call with reqtype HEAD: get last modification time
                   8698: # call with reqtype GET: get the file contents
                   8699: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8700: #
1.481     raeburn  8701: sub getuploaded {
                   8702:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8703:     $uri=~s/^\///;
1.980     raeburn  8704:     my $homeserver = &homeserver($cnum,$cdom);
                   8705:     my $protocol = $protocol{$homeserver};
                   8706:     $protocol = 'http' if ($protocol ne 'https');
                   8707:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  8708:     my $ua=new LWP::UserAgent;
                   8709:     my $request=new HTTP::Request($reqtype,$uri);
                   8710:     my $response=$ua->request($request);
                   8711:     $$rtncode = $response->code;
1.482     albertel 8712:     if (! $response->is_success()) {
                   8713: 	return 'failed';
                   8714:     }      
                   8715:     if ($reqtype eq 'HEAD') {
1.486     www      8716: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8717:     } elsif ($reqtype eq 'GET') {
                   8718: 	$$info = $response->content;
1.472     albertel 8719:     }
1.482     albertel 8720:     return 'ok';
1.36      albertel 8721: }
                   8722: 
1.481     raeburn  8723: sub readfile {
                   8724:     my $file = shift;
                   8725:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8726:     my $fh;
                   8727:     open($fh,"<$file");
                   8728:     my $a='';
1.800     albertel 8729:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8730:     return $a;
                   8731: }
                   8732: 
1.36      albertel 8733: sub filelocation {
1.590     banghart 8734:     my ($dir,$file) = @_;
                   8735:     my $location;
                   8736:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8737: 
                   8738:     if ($file =~ m-^/adm/-) {
                   8739: 	$file=~s-^/adm/wrapper/-/-;
                   8740: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8741:     }
1.882     albertel 8742: 
1.590     banghart 8743:     if ($file=~m:^/~:) { # is a contruction space reference
                   8744:         $location = $file;
                   8745:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8746:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8747: 	# is a correct contruction space reference
                   8748:         $location = $file;
1.956     raeburn  8749:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   8750:         $location = $file;
1.609     banghart 8751:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8752:         my ($udom,$uname,$filename)=
1.811     albertel 8753:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8754:         my $home=&homeserver($uname,$udom);
                   8755:         my $is_me=0;
                   8756:         my @ids=&current_machine_ids();
                   8757:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8758:         if ($is_me) {
1.955     raeburn  8759:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 8760:         } else {
                   8761:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8762:   	      $udom.'/'.$uname.'/'.$filename;
                   8763:         }
1.882     albertel 8764:     } elsif ($file =~ m-^/adm/-) {
                   8765: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8766:     } else {
                   8767:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8768:         $file=~s:^/res/:/:;
                   8769:         if ( !( $file =~ m:^/:) ) {
                   8770:             $location = $dir. '/'.$file;
                   8771:         } else {
                   8772:             $location = '/home/httpd/html/res'.$file;
                   8773:         }
1.59      albertel 8774:     }
1.590     banghart 8775:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8776:     while ($location=~m{/\.\./}) {
                   8777: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8778: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8779: 	} else {
                   8780: 	    $location=~ s{/\.\./}{/}g;
                   8781: 	}
                   8782:     } #remove dir/..
1.590     banghart 8783:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8784:     return $location;
1.46      www      8785: }
1.36      albertel 8786: 
1.46      www      8787: sub hreflocation {
                   8788:     my ($dir,$file)=@_;
1.980     raeburn  8789:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 8790: 	$file=filelocation($dir,$file);
1.700     albertel 8791:     } elsif ($file=~m-^/adm/-) {
                   8792: 	$file=~s-^/adm/wrapper/-/-;
                   8793: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8794:     }
                   8795:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8796: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8797:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8798: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8799:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8800: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8801: 	    -/uploaded/$1/$2/-x;
1.46      www      8802:     }
1.913     albertel 8803:     if ($file=~ m{^/userfiles/}) {
                   8804: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8805:     }
1.462     albertel 8806:     return $file;
1.465     albertel 8807: }
                   8808: 
                   8809: sub current_machine_domains {
1.853     albertel 8810:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8811: }
                   8812: 
                   8813: sub machine_domains {
                   8814:     my ($hostname) = @_;
1.465     albertel 8815:     my @domains;
1.838     albertel 8816:     my %hostname = &all_hostnames();
1.465     albertel 8817:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8818: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8819: 	if ($hostname eq $name) {
1.844     albertel 8820: 	    push(@domains,&host_domain($id));
1.465     albertel 8821: 	}
                   8822:     }
                   8823:     return @domains;
                   8824: }
                   8825: 
                   8826: sub current_machine_ids {
1.853     albertel 8827:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8828: }
                   8829: 
                   8830: sub machine_ids {
                   8831:     my ($hostname) = @_;
                   8832:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8833:     my @ids;
1.888     albertel 8834:     my %name_to_host = &all_names();
1.889     albertel 8835:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8836: 	return @{ $name_to_host{$hostname} };
                   8837:     }
                   8838:     return;
1.31      www      8839: }
                   8840: 
1.824     raeburn  8841: sub additional_machine_domains {
                   8842:     my @domains;
                   8843:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8844:     while( my $line = <$fh>) {
                   8845:         $line =~ s/\s//g;
                   8846:         push(@domains,$line);
                   8847:     }
                   8848:     return @domains;
                   8849: }
                   8850: 
                   8851: sub default_login_domain {
                   8852:     my $domain = $perlvar{'lonDefDomain'};
                   8853:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8854:     foreach my $posdom (&current_machine_domains(),
                   8855:                         &additional_machine_domains()) {
                   8856:         if (lc($posdom) eq lc($testdomain)) {
                   8857:             $domain=$posdom;
                   8858:             last;
                   8859:         }
                   8860:     }
                   8861:     return $domain;
                   8862: }
                   8863: 
1.31      www      8864: # ------------------------------------------------------------- Declutters URLs
                   8865: 
                   8866: sub declutter {
                   8867:     my $thisfn=shift;
1.569     albertel 8868:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8869:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8870:     $thisfn=~s/^\///;
1.697     albertel 8871:     $thisfn=~s|^adm/wrapper/||;
                   8872:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8873:     $thisfn=~s/^res\///;
1.235     www      8874:     $thisfn=~s/\?.+$//;
1.268     www      8875:     return $thisfn;
                   8876: }
                   8877: 
                   8878: # ------------------------------------------------------------- Clutter up URLs
                   8879: 
                   8880: sub clutter {
                   8881:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8882:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8883: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8884:        $thisfn='/res'.$thisfn; 
                   8885:     }
1.694     albertel 8886:     if ($thisfn !~m|/adm|) {
1.695     albertel 8887: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8888: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8889: 	} else {
                   8890: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8891: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8892: 	    if ($embstyle eq 'ssi'
                   8893: 		|| ($embstyle eq 'hdn')
                   8894: 		|| ($embstyle eq 'rat')
                   8895: 		|| ($embstyle eq 'prv')
                   8896: 		|| ($embstyle eq 'ign')) {
                   8897: 		#do nothing with these
                   8898: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8899: 		|| ($embstyle eq 'emb')
                   8900: 		|| ($embstyle eq 'wrp')) {
                   8901: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8902: 	    } elsif ($embstyle eq 'unk'
                   8903: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8904: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8905: 	    } else {
1.718     www      8906: #		&logthis("Got a blank emb style");
1.695     albertel 8907: 	    }
1.694     albertel 8908: 	}
                   8909:     }
1.31      www      8910:     return $thisfn;
1.12      www      8911: }
                   8912: 
1.787     albertel 8913: sub clutter_with_no_wrapper {
                   8914:     my $uri = &clutter(shift);
                   8915:     if ($uri =~ m-^/adm/-) {
                   8916: 	$uri =~ s-^/adm/wrapper/-/-;
                   8917: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8918:     }
                   8919:     return $uri;
                   8920: }
                   8921: 
1.557     albertel 8922: sub freeze_escape {
                   8923:     my ($value)=@_;
                   8924:     if (ref($value)) {
                   8925: 	$value=&nfreeze($value);
                   8926: 	return '__FROZEN__'.&escape($value);
                   8927:     }
                   8928:     return &escape($value);
                   8929: }
                   8930: 
1.11      www      8931: 
1.557     albertel 8932: sub thaw_unescape {
                   8933:     my ($value)=@_;
                   8934:     if ($value =~ /^__FROZEN__/) {
                   8935: 	substr($value,0,10,undef);
                   8936: 	$value=&unescape($value);
                   8937: 	return &thaw($value);
                   8938:     }
                   8939:     return &unescape($value);
                   8940: }
                   8941: 
1.436     albertel 8942: sub correct_line_ends {
                   8943:     my ($result)=@_;
                   8944:     $$result =~s/\r\n/\n/mg;
                   8945:     $$result =~s/\r/\n/mg;
1.415     albertel 8946: }
1.1       albertel 8947: # ================================================================ Main Program
                   8948: 
1.184     www      8949: sub goodbye {
1.204     albertel 8950:    &logthis("Starting Shut down");
1.443     albertel 8951: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8952:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8953: #converted
1.599     albertel 8954: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8955:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8956: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8957: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8958: #1.1 only
1.870     albertel 8959: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8960: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8961: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8962: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8963:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8964:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8965:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8966:    &flushcourselogs();
                   8967:    &logthis("Shutting down");
                   8968: }
                   8969: 
1.852     albertel 8970: sub get_dns {
1.869     albertel 8971:     my ($url,$func,$ignore_cache) = @_;
                   8972:     if (!$ignore_cache) {
                   8973: 	my ($content,$cached)=
                   8974: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8975: 	if ($cached) {
                   8976: 	    &$func($content);
                   8977: 	    return;
                   8978: 	}
                   8979:     }
                   8980: 
                   8981:     my %alldns;
1.852     albertel 8982:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8983:     foreach my $dns (<$config>) {
                   8984: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  8985:         my $line = $1;
                   8986:         my ($host,$protocol) = split(/:/,$line);
                   8987:         if ($protocol ne 'https') {
                   8988:             $protocol = 'http';
                   8989:         }
                   8990: 	$alldns{$host} = $protocol;
1.869     albertel 8991:     }
                   8992:     while (%alldns) {
                   8993: 	my ($dns) = keys(%alldns);
1.852     albertel 8994: 	my $ua=new LWP::UserAgent;
1.979     raeburn  8995: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 8996: 	my $response=$ua->request($request);
1.979     raeburn  8997:         delete($alldns{$dns});
1.852     albertel 8998: 	next if ($response->is_error());
                   8999: 	my @content = split("\n",$response->content);
1.869     albertel 9000: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 9001: 	&$func(\@content);
1.869     albertel 9002: 	return;
1.852     albertel 9003:     }
                   9004:     close($config);
1.871     albertel 9005:     my $which = (split('/',$url))[3];
                   9006:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   9007:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 9008:     my @content = <$config>;
                   9009:     &$func(\@content);
                   9010:     return;
1.852     albertel 9011: }
1.327     albertel 9012: # ------------------------------------------------------------ Read domain file
                   9013: {
1.852     albertel 9014:     my $loaded;
1.846     albertel 9015:     my %domain;
                   9016: 
1.852     albertel 9017:     sub parse_domain_tab {
                   9018: 	my ($lines) = @_;
                   9019: 	foreach my $line (@$lines) {
                   9020: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      9021: 
1.846     albertel 9022: 	    chomp($line);
1.852     albertel 9023: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 9024: 	    my %this_domain;
                   9025: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   9026: 			       'lang_def', 'city', 'longi', 'lati',
                   9027: 			       'primary') {
                   9028: 		$this_domain{$field} = shift(@elements);
                   9029: 	    }
                   9030: 	    $domain{$name} = \%this_domain;
1.852     albertel 9031: 	}
                   9032:     }
1.864     albertel 9033: 
                   9034:     sub reset_domain_info {
                   9035: 	undef($loaded);
                   9036: 	undef(%domain);
                   9037:     }
                   9038: 
1.852     albertel 9039:     sub load_domain_tab {
1.869     albertel 9040: 	my ($ignore_cache) = @_;
                   9041: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 9042: 	my $fh;
                   9043: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   9044: 	    my @lines = <$fh>;
                   9045: 	    &parse_domain_tab(\@lines);
1.448     albertel 9046: 	}
1.852     albertel 9047: 	close($fh);
                   9048: 	$loaded = 1;
1.327     albertel 9049:     }
1.846     albertel 9050: 
                   9051:     sub domain {
1.852     albertel 9052: 	&load_domain_tab() if (!$loaded);
                   9053: 
1.846     albertel 9054: 	my ($name,$what) = @_;
                   9055: 	return if ( !exists($domain{$name}) );
                   9056: 
                   9057: 	if (!$what) {
                   9058: 	    return $domain{$name}{'description'};
                   9059: 	}
                   9060: 	return $domain{$name}{$what};
                   9061:     }
1.974     raeburn  9062: 
                   9063:     sub domain_info {
                   9064:         &load_domain_tab() if (!$loaded);
                   9065:         return %domain;
                   9066:     }
                   9067: 
1.327     albertel 9068: }
                   9069: 
                   9070: 
1.1       albertel 9071: # ------------------------------------------------------------- Read hosts file
                   9072: {
1.838     albertel 9073:     my %hostname;
1.844     albertel 9074:     my %hostdom;
1.845     albertel 9075:     my %libserv;
1.852     albertel 9076:     my $loaded;
1.888     albertel 9077:     my %name_to_host;
1.852     albertel 9078: 
                   9079:     sub parse_hosts_tab {
                   9080: 	my ($file) = @_;
                   9081: 	foreach my $configline (@$file) {
                   9082: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   9083: 	    next if ($configline =~ /^\^/);
                   9084: 	    chomp($configline);
1.968     raeburn  9085: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852     albertel 9086: 	    $name=~s/\s//g;
                   9087: 	    if ($id && $domain && $role && $name) {
                   9088: 		$hostname{$id}=$name;
1.888     albertel 9089: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 9090: 		$hostdom{$id}=$domain;
                   9091: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  9092:                 if (defined($protocol)) {
                   9093:                     if ($protocol eq 'https') {
                   9094:                         $protocol{$id} = $protocol;
                   9095:                     } else {
                   9096:                         $protocol{$id} = 'http'; 
                   9097:                     }
1.968     raeburn  9098:                 } else {
1.969     raeburn  9099:                     $protocol{$id} = 'http';
1.968     raeburn  9100:                 }
1.852     albertel 9101: 	    }
                   9102: 	}
                   9103:     }
1.864     albertel 9104:     
                   9105:     sub reset_hosts_info {
1.897     albertel 9106: 	&purge_remembered();
1.864     albertel 9107: 	&reset_domain_info();
                   9108: 	&reset_hosts_ip_info();
1.892     albertel 9109: 	undef(%name_to_host);
1.864     albertel 9110: 	undef(%hostname);
                   9111: 	undef(%hostdom);
                   9112: 	undef(%libserv);
                   9113: 	undef($loaded);
                   9114:     }
1.1       albertel 9115: 
1.852     albertel 9116:     sub load_hosts_tab {
1.869     albertel 9117: 	my ($ignore_cache) = @_;
                   9118: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 9119: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9120: 	my @config = <$config>;
                   9121: 	&parse_hosts_tab(\@config);
                   9122: 	close($config);
                   9123: 	$loaded=1;
1.1       albertel 9124:     }
1.852     albertel 9125: 
1.838     albertel 9126:     sub hostname {
1.852     albertel 9127: 	&load_hosts_tab() if (!$loaded);
                   9128: 
1.838     albertel 9129: 	my ($lonid) = @_;
                   9130: 	return $hostname{$lonid};
                   9131:     }
1.845     albertel 9132: 
1.838     albertel 9133:     sub all_hostnames {
1.852     albertel 9134: 	&load_hosts_tab() if (!$loaded);
                   9135: 
1.838     albertel 9136: 	return %hostname;
                   9137:     }
1.845     albertel 9138: 
1.888     albertel 9139:     sub all_names {
                   9140: 	&load_hosts_tab() if (!$loaded);
                   9141: 
                   9142: 	return %name_to_host;
                   9143:     }
                   9144: 
1.974     raeburn  9145:     sub all_host_domain {
                   9146:         &load_hosts_tab() if (!$loaded);
                   9147:         return %hostdom;
                   9148:     }
                   9149: 
1.845     albertel 9150:     sub is_library {
1.852     albertel 9151: 	&load_hosts_tab() if (!$loaded);
                   9152: 
1.845     albertel 9153: 	return exists($libserv{$_[0]});
                   9154:     }
                   9155: 
                   9156:     sub all_library {
1.852     albertel 9157: 	&load_hosts_tab() if (!$loaded);
                   9158: 
1.845     albertel 9159: 	return %libserv;
                   9160:     }
                   9161: 
1.841     albertel 9162:     sub get_servers {
1.852     albertel 9163: 	&load_hosts_tab() if (!$loaded);
                   9164: 
1.841     albertel 9165: 	my ($domain,$type) = @_;
                   9166: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   9167: 	                                          : %hostname;
                   9168: 	my %result;
1.842     albertel 9169: 	if (ref($domain) eq 'ARRAY') {
                   9170: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 9171: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 9172: 		    $result{$host} = $hostname;
                   9173: 		}
                   9174: 	    }
                   9175: 	} else {
                   9176: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   9177: 		if ($hostdom{$host} eq $domain) {
                   9178: 		    $result{$host} = $hostname;
                   9179: 		}
1.841     albertel 9180: 	    }
                   9181: 	}
                   9182: 	return %result;
                   9183:     }
1.845     albertel 9184: 
1.844     albertel 9185:     sub host_domain {
1.852     albertel 9186: 	&load_hosts_tab() if (!$loaded);
                   9187: 
1.844     albertel 9188: 	my ($lonid) = @_;
                   9189: 	return $hostdom{$lonid};
                   9190:     }
                   9191: 
1.841     albertel 9192:     sub all_domains {
1.852     albertel 9193: 	&load_hosts_tab() if (!$loaded);
                   9194: 
1.841     albertel 9195: 	my %seen;
                   9196: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   9197: 	return @uniq;
                   9198:     }
1.1       albertel 9199: }
                   9200: 
1.847     albertel 9201: { 
                   9202:     my %iphost;
1.856     albertel 9203:     my %name_to_ip;
                   9204:     my %lonid_to_ip;
1.869     albertel 9205: 
1.847     albertel 9206:     sub get_hosts_from_ip {
                   9207: 	my ($ip) = @_;
                   9208: 	my %iphosts = &get_iphost();
                   9209: 	if (ref($iphosts{$ip})) {
                   9210: 	    return @{$iphosts{$ip}};
                   9211: 	}
                   9212: 	return;
1.839     albertel 9213:     }
1.864     albertel 9214:     
                   9215:     sub reset_hosts_ip_info {
                   9216: 	undef(%iphost);
                   9217: 	undef(%name_to_ip);
                   9218: 	undef(%lonid_to_ip);
                   9219:     }
1.856     albertel 9220: 
                   9221:     sub get_host_ip {
                   9222: 	my ($lonid) = @_;
                   9223: 	if (exists($lonid_to_ip{$lonid})) {
                   9224: 	    return $lonid_to_ip{$lonid};
                   9225: 	}
                   9226: 	my $name=&hostname($lonid);
                   9227:    	my $ip = gethostbyname($name);
                   9228: 	return if (!$ip || length($ip) ne 4);
                   9229: 	$ip=inet_ntoa($ip);
                   9230: 	$name_to_ip{$name}   = $ip;
                   9231: 	$lonid_to_ip{$lonid} = $ip;
                   9232: 	return $ip;
                   9233:     }
1.847     albertel 9234:     
                   9235:     sub get_iphost {
1.869     albertel 9236: 	my ($ignore_cache) = @_;
1.894     albertel 9237: 
1.869     albertel 9238: 	if (!$ignore_cache) {
                   9239: 	    if (%iphost) {
                   9240: 		return %iphost;
                   9241: 	    }
                   9242: 	    my ($ip_info,$cached)=
                   9243: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   9244: 	    if ($cached) {
                   9245: 		%iphost      = %{$ip_info->[0]};
                   9246: 		%name_to_ip  = %{$ip_info->[1]};
                   9247: 		%lonid_to_ip = %{$ip_info->[2]};
                   9248: 		return %iphost;
                   9249: 	    }
                   9250: 	}
1.894     albertel 9251: 
                   9252: 	# get yesterday's info for fallback
                   9253: 	my %old_name_to_ip;
                   9254: 	my ($ip_info,$cached)=
                   9255: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   9256: 	if ($cached) {
                   9257: 	    %old_name_to_ip = %{$ip_info->[1]};
                   9258: 	}
                   9259: 
1.888     albertel 9260: 	my %name_to_host = &all_names();
                   9261: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 9262: 	    my $ip;
                   9263: 	    if (!exists($name_to_ip{$name})) {
                   9264: 		$ip = gethostbyname($name);
                   9265: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 9266: 		    if (defined($old_name_to_ip{$name})) {
                   9267: 			$ip = $old_name_to_ip{$name};
                   9268: 			&logthis("Can't find $name defaulting to old $ip");
                   9269: 		    } else {
                   9270: 			&logthis("Name $name no IP found");
                   9271: 			next;
                   9272: 		    }
                   9273: 		} else {
                   9274: 		    $ip=inet_ntoa($ip);
1.847     albertel 9275: 		}
                   9276: 		$name_to_ip{$name} = $ip;
                   9277: 	    } else {
                   9278: 		$ip = $name_to_ip{$name};
1.653     albertel 9279: 	    }
1.888     albertel 9280: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   9281: 		$lonid_to_ip{$id} = $ip;
                   9282: 	    }
                   9283: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 9284: 	}
1.869     albertel 9285: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   9286: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 9287: 				      48*60*60);
1.869     albertel 9288: 
1.847     albertel 9289: 	return %iphost;
1.598     albertel 9290:     }
                   9291: 
1.992     raeburn  9292:     #
                   9293:     #  Given a DNS returns the loncapa host name for that DNS 
                   9294:     # 
                   9295:     sub host_from_dns {
                   9296:         my ($dns) = @_;
                   9297:         my @hosts;
                   9298:         my $ip;
                   9299: 
1.993     raeburn  9300:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  9301:             $ip = $name_to_ip{$dns};
                   9302:         }
                   9303:         if (!$ip) {
                   9304:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   9305:             if (length($ip) == 4) { 
                   9306: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   9307:             }
                   9308:         }
                   9309:         if ($ip) {
                   9310: 	    @hosts = get_hosts_from_ip($ip);
                   9311: 	    return $hosts[0];
                   9312:         }
                   9313:         return undef;
1.986     foxr     9314:     }
1.992     raeburn  9315: 
1.986     foxr     9316: }
                   9317: 
1.862     albertel 9318: BEGIN {
                   9319: 
                   9320: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   9321:     unless ($readit) {
                   9322: {
                   9323:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   9324:     %perlvar = (%perlvar,%{$configvars});
                   9325: }
                   9326: 
                   9327: 
1.1       albertel 9328: # ------------------------------------------------------ Read spare server file
                   9329: {
1.448     albertel 9330:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 9331: 
                   9332:     while (my $configline=<$config>) {
                   9333:        chomp($configline);
1.284     matthew  9334:        if ($configline) {
1.784     albertel 9335: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 9336: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 9337: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 9338:        }
                   9339:     }
1.448     albertel 9340:     close($config);
1.1       albertel 9341: }
1.11      www      9342: # ------------------------------------------------------------ Read permissions
                   9343: {
1.448     albertel 9344:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      9345: 
                   9346:     while (my $configline=<$config>) {
1.448     albertel 9347: 	chomp($configline);
                   9348: 	if ($configline) {
                   9349: 	    my ($role,$perm)=split(/ /,$configline);
                   9350: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   9351: 	}
1.11      www      9352:     }
1.448     albertel 9353:     close($config);
1.11      www      9354: }
                   9355: 
                   9356: # -------------------------------------------- Read plain texts for permissions
                   9357: {
1.448     albertel 9358:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      9359: 
                   9360:     while (my $configline=<$config>) {
1.448     albertel 9361: 	chomp($configline);
                   9362: 	if ($configline) {
1.742     raeburn  9363: 	    my ($short,@plain)=split(/:/,$configline);
                   9364:             %{$prp{$short}} = ();
                   9365: 	    if (@plain > 0) {
                   9366:                 $prp{$short}{'std'} = $plain[0];
                   9367:                 for (my $i=1; $i<@plain; $i++) {
                   9368:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   9369:                 }
                   9370:             }
1.448     albertel 9371: 	}
1.135     www      9372:     }
1.448     albertel 9373:     close($config);
1.135     www      9374: }
                   9375: 
                   9376: # ---------------------------------------------------------- Read package table
                   9377: {
1.448     albertel 9378:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      9379: 
                   9380:     while (my $configline=<$config>) {
1.483     albertel 9381: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 9382: 	chomp($configline);
                   9383: 	my ($short,$plain)=split(/:/,$configline);
                   9384: 	my ($pack,$name)=split(/\&/,$short);
                   9385: 	if ($plain ne '') {
                   9386: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   9387: 	    $packagetab{$short}=$plain; 
                   9388: 	}
1.11      www      9389:     }
1.448     albertel 9390:     close($config);
1.329     matthew  9391: }
                   9392: 
                   9393: # ------------- set up temporary directory
                   9394: {
                   9395:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   9396: 
1.11      www      9397: }
                   9398: 
1.794     albertel 9399: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   9400: 				'compress_threshold'=> 20_000,
                   9401:  			        });
1.185     www      9402: 
1.281     www      9403: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      9404: $dumpcount=0;
1.958     www      9405: $locknum=0;
1.22      www      9406: 
1.163     harris41 9407: &logtouch();
1.672     albertel 9408: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      9409: $readit=1;
1.564     albertel 9410:     {
                   9411: 	use integer;
                   9412: 	my $test=(2**32)+1;
1.568     albertel 9413: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 9414: 	&logthis(" Detected 64bit platform ($_64bit)");
                   9415:     }
1.195     www      9416: }
1.1       albertel 9417: }
1.179     www      9418: 
1.1       albertel 9419: 1;
1.191     harris41 9420: __END__
                   9421: 
1.243     albertel 9422: =pod
                   9423: 
1.191     harris41 9424: =head1 NAME
                   9425: 
1.243     albertel 9426: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 9427: 
                   9428: =head1 SYNOPSIS
                   9429: 
1.243     albertel 9430: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 9431: 
                   9432:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   9433: 
1.243     albertel 9434: Common parameters:
                   9435: 
                   9436: =over 4
                   9437: 
                   9438: =item *
                   9439: 
                   9440: $uname : an internal username (if $cname expecting a course Id specifically)
                   9441: 
                   9442: =item *
                   9443: 
                   9444: $udom : a domain (if $cdom expecting a course's domain specifically)
                   9445: 
                   9446: =item *
                   9447: 
                   9448: $symb : a resource instance identifier
                   9449: 
                   9450: =item *
                   9451: 
                   9452: $namespace : the name of a .db file that contains the data needed or
                   9453: being set.
                   9454: 
                   9455: =back
                   9456: 
1.394     bowersj2 9457: =head1 OVERVIEW
1.191     harris41 9458: 
1.394     bowersj2 9459: lonnet provides subroutines which interact with the
                   9460: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   9461: about classes, users, and resources.
1.243     albertel 9462: 
                   9463: For many of these objects you can also use this to store data about
                   9464: them or modify them in various ways.
1.191     harris41 9465: 
1.394     bowersj2 9466: =head2 Symbs
1.191     harris41 9467: 
1.394     bowersj2 9468: To identify a specific instance of a resource, LON-CAPA uses symbols
                   9469: or "symbs"X<symb>. These identifiers are built from the URL of the
                   9470: map, the resource number of the resource in the map, and the URL of
                   9471: the resource itself. The latter is somewhat redundant, but might help
                   9472: if maps change.
                   9473: 
                   9474: An example is
                   9475: 
                   9476:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   9477: 
                   9478: The respective map entry is
                   9479: 
                   9480:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   9481:   title="Problem 2">
                   9482:  </resource>
                   9483: 
                   9484: Symbs are used by the random number generator, as well as to store and
                   9485: restore data specific to a certain instance of for example a problem.
                   9486: 
                   9487: =head2 Storing And Retrieving Data
                   9488: 
                   9489: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   9490: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   9491: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   9492: is is the non-critical message twin of cstore. These functions are for
                   9493: handlers to store a perl hash to a user's permanent data space in an
                   9494: easy manner, and to retrieve it again on another call. It is expected
                   9495: that a handler would use this once at the beginning to retrieve data,
                   9496: and then again once at the end to send only the new data back.
                   9497: 
                   9498: The data is stored in the user's data directory on the user's
                   9499: homeserver under the ID of the course.
                   9500: 
                   9501: The hash that is returned by restore will have all of the previous
                   9502: value for all of the elements of the hash.
                   9503: 
                   9504: Example:
                   9505: 
                   9506:  #creating a hash
                   9507:  my %hash;
                   9508:  $hash{'foo'}='bar';
                   9509: 
                   9510:  #storing it
                   9511:  &Apache::lonnet::cstore(\%hash);
                   9512: 
                   9513:  #changing a value
                   9514:  $hash{'foo'}='notbar';
                   9515: 
                   9516:  #adding a new value
                   9517:  $hash{'bar'}='foo';
                   9518:  &Apache::lonnet::cstore(\%hash);
                   9519: 
                   9520:  #retrieving the hash
                   9521:  my %history=&Apache::lonnet::restore();
                   9522: 
                   9523:  #print the hash
                   9524:  foreach my $key (sort(keys(%history))) {
                   9525:    print("\%history{$key} = $history{$key}");
                   9526:  }
                   9527: 
                   9528: Will print out:
1.191     harris41 9529: 
1.394     bowersj2 9530:  %history{1:foo} = bar
                   9531:  %history{1:keys} = foo:timestamp
                   9532:  %history{1:timestamp} = 990455579
                   9533:  %history{2:bar} = foo
                   9534:  %history{2:foo} = notbar
                   9535:  %history{2:keys} = foo:bar:timestamp
                   9536:  %history{2:timestamp} = 990455580
                   9537:  %history{bar} = foo
                   9538:  %history{foo} = notbar
                   9539:  %history{timestamp} = 990455580
                   9540:  %history{version} = 2
                   9541: 
                   9542: Note that the special hash entries C<keys>, C<version> and
                   9543: C<timestamp> were added to the hash. C<version> will be equal to the
                   9544: total number of versions of the data that have been stored. The
                   9545: C<timestamp> attribute will be the UNIX time the hash was
                   9546: stored. C<keys> is available in every historical section to list which
                   9547: keys were added or changed at a specific historical revision of a
                   9548: hash.
                   9549: 
                   9550: B<Warning>: do not store the hash that restore returns directly. This
                   9551: will cause a mess since it will restore the historical keys as if the
                   9552: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 9553: 
1.394     bowersj2 9554: Calling convention:
1.191     harris41 9555: 
1.394     bowersj2 9556:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   9557:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 9558: 
1.394     bowersj2 9559: For more detailed information, see lonnet specific documentation.
1.191     harris41 9560: 
1.394     bowersj2 9561: =head1 RETURN MESSAGES
1.191     harris41 9562: 
1.394     bowersj2 9563: =over 4
1.191     harris41 9564: 
1.394     bowersj2 9565: =item * B<con_lost>: unable to contact remote host
1.191     harris41 9566: 
1.394     bowersj2 9567: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   9568: when the connection is brought back up
1.191     harris41 9569: 
1.394     bowersj2 9570: =item * B<con_failed>: unable to contact remote host and unable to save message
                   9571: for later delivery
1.191     harris41 9572: 
1.967     bisitz   9573: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 9574: 
1.394     bowersj2 9575: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 9576: that was requested
1.191     harris41 9577: 
1.243     albertel 9578: =back
1.191     harris41 9579: 
1.243     albertel 9580: =head1 PUBLIC SUBROUTINES
1.191     harris41 9581: 
1.243     albertel 9582: =head2 Session Environment Functions
1.191     harris41 9583: 
1.243     albertel 9584: =over 4
1.191     harris41 9585: 
1.394     bowersj2 9586: =item * 
                   9587: X<appenv()>
1.949     raeburn  9588: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 9589: the user envirnoment file, and will be restored for each access this
1.620     albertel 9590: user makes during this session, also modifies the %env for the current
1.949     raeburn  9591: process. Optional rolesarrayref - if defined contains a reference to an array
                   9592: of roles which are exempt from the restriction on modifying user.role entries 
                   9593: in the user's environment.db and in %env.    
1.191     harris41 9594: 
                   9595: =item *
1.394     bowersj2 9596: X<delenv()>
1.987     raeburn  9597: B<delenv($delthis,$regexp)>: removes all items from the session
                   9598: environment file that begin with $delthis. If the 
                   9599: optional second arg - $regexp - is true, $delthis is treated as a 
                   9600: regular expression, otherwise \Q$delthis\E is used. 
                   9601: The values are also deleted from the current processes %env.
1.191     harris41 9602: 
1.795     albertel 9603: =item * get_env_multiple($name) 
                   9604: 
                   9605: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   9606: values may be defined and end up as an array ref.
                   9607: 
                   9608: returns an array of values
                   9609: 
1.243     albertel 9610: =back
                   9611: 
                   9612: =head2 User Information
1.191     harris41 9613: 
1.243     albertel 9614: =over 4
1.191     harris41 9615: 
                   9616: =item *
1.394     bowersj2 9617: X<queryauthenticate()>
                   9618: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 9619: authentication scheme
                   9620: 
                   9621: =item *
1.394     bowersj2 9622: X<authenticate()>
                   9623: B<authenticate($uname,$upass,$udom)>: try to
                   9624: authenticate user from domain's lib servers (first use the current
                   9625: one). C<$upass> should be the users password.
1.191     harris41 9626: 
                   9627: =item *
1.394     bowersj2 9628: X<homeserver()>
                   9629: B<homeserver($uname,$udom)>: find the server which has
                   9630: the user's directory and files (there must be only one), this caches
                   9631: the answer, and also caches if there is a borken connection.
1.191     harris41 9632: 
                   9633: =item *
1.394     bowersj2 9634: X<idget()>
                   9635: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   9636: (IDs are a unique resource in a domain, there must be only 1 ID per
                   9637: username, and only 1 username per ID in a specific domain) (returns
                   9638: hash: id=>name,id=>name)
1.191     harris41 9639: 
                   9640: =item *
1.394     bowersj2 9641: X<idrget()>
                   9642: B<idrget($udom,@unames)>: find the IDs behind a list of
                   9643: usernames (returns hash: name=>id,name=>id)
1.191     harris41 9644: 
                   9645: =item *
1.394     bowersj2 9646: X<idput()>
                   9647: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 9648: 
                   9649: =item *
1.394     bowersj2 9650: X<rolesinit()>
                   9651: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 9652: 
                   9653: =item *
1.551     albertel 9654: X<getsection()>
                   9655: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 9656: course $cname, return section name/number or '' for "not in course"
                   9657: and '-1' for "no section"
                   9658: 
                   9659: =item *
1.394     bowersj2 9660: X<userenvironment()>
                   9661: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 9662: passed in @what from the requested user's environment, returns a hash
                   9663: 
1.858     raeburn  9664: =item * 
                   9665: X<userlog_query()>
1.859     albertel 9666: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   9667: activity.log file. %filters defines filters applied when parsing the
                   9668: log file. These can be start or end timestamps, or the type of action
                   9669: - log to look for Login or Logout events, check for Checkin or
                   9670: Checkout, role for role selection. The response is in the form
                   9671: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   9672: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  9673: 
1.243     albertel 9674: =back
                   9675: 
                   9676: =head2 User Roles
                   9677: 
                   9678: =over 4
                   9679: 
                   9680: =item *
                   9681: 
1.810     raeburn  9682: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 9683:  F: full access
                   9684:  U,I,K: authentication modes (cxx only)
                   9685:  '': forbidden
                   9686:  1: user needs to choose course
                   9687:  2: browse allowed
1.766     albertel 9688:  A: passphrase authentication needed
1.243     albertel 9689: 
                   9690: =item *
                   9691: 
                   9692: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   9693: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   9694: and course level
                   9695: 
                   9696: =item *
                   9697: 
1.988     raeburn  9698: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   9699: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  9700: $type is Course (default) or Community.
1.988     raeburn  9701: If $forcedefault evaluates to true, text returned will be default 
                   9702: text for $type. Otherwise, if this is a course, the text returned 
                   9703: will be a custom name for the role (if defined in the course's 
                   9704: environment).  If no custom name is defined the default is returned.
                   9705:    
1.832     raeburn  9706: =item *
                   9707: 
1.935     raeburn  9708: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  9709: All arguments are optional. Returns a hash of a roles, either for
                   9710: co-author/assistant author roles for a user's Construction Space
1.906     albertel 9711: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  9712: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   9713: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   9714: For each key, value is set to colon-separated start and end times for
                   9715: the role.  If no username and domain are specified, will default to
1.934     raeburn  9716: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  9717: of role statuses (active, future or previous), roles 
                   9718: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   9719: to restrict the list of roles reported. If no array ref is 
                   9720: provided for types, will default to return only active roles.
1.834     albertel 9721: 
1.243     albertel 9722: =back
                   9723: 
                   9724: =head2 User Modification
                   9725: 
                   9726: =over 4
                   9727: 
                   9728: =item *
                   9729: 
1.957     raeburn  9730: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 9731: user for the level given by URL.  Optional start and end dates (leave empty
                   9732: string or zero for "no date")
1.191     harris41 9733: 
                   9734: =item *
                   9735: 
1.243     albertel 9736: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   9737: change a users, password, possible return values are: ok,
                   9738: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   9739: refused
1.191     harris41 9740: 
                   9741: =item *
                   9742: 
1.243     albertel 9743: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9744: 
                   9745: =item *
                   9746: 
1.963     raeburn  9747: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
                   9748:            $forceid,$desiredhome,$email,$inststatus) : 
1.243     albertel 9749: modify user
1.191     harris41 9750: 
                   9751: =item *
                   9752: 
1.286     matthew  9753: modifystudent
                   9754: 
1.957     raeburn  9755: modify a student's enrollment and identification information.
1.286     matthew  9756: The course id is resolved based on the current users environment.  
                   9757: This means the envoking user must be a course coordinator or otherwise
                   9758: associated with a course.
                   9759: 
1.297     matthew  9760: This call is essentially a wrapper for lonnet::modifyuser and
                   9761: lonnet::modify_student_enrollment
1.286     matthew  9762: 
                   9763: Inputs: 
                   9764: 
                   9765: =over 4
                   9766: 
1.957     raeburn  9767: =item B<$udom> Student's loncapa domain
1.286     matthew  9768: 
1.957     raeburn  9769: =item B<$uname> Student's loncapa login name
1.286     matthew  9770: 
1.964     bisitz   9771: =item B<$uid> Student/Employee ID
1.286     matthew  9772: 
1.957     raeburn  9773: =item B<$umode> Student's authentication mode
1.286     matthew  9774: 
1.957     raeburn  9775: =item B<$upass> Student's password
1.286     matthew  9776: 
1.957     raeburn  9777: =item B<$first> Student's first name
1.286     matthew  9778: 
1.957     raeburn  9779: =item B<$middle> Student's middle name
1.286     matthew  9780: 
1.957     raeburn  9781: =item B<$last> Student's last name
1.286     matthew  9782: 
1.957     raeburn  9783: =item B<$gene> Student's generation
1.286     matthew  9784: 
1.957     raeburn  9785: =item B<$usec> Student's section in course
1.286     matthew  9786: 
                   9787: =item B<$end> Unix time of the roles expiration
                   9788: 
                   9789: =item B<$start> Unix time of the roles start date
                   9790: 
                   9791: =item B<$forceid> If defined, allow $uid to be changed
                   9792: 
                   9793: =item B<$desiredhome> server to use as home server for student
                   9794: 
1.957     raeburn  9795: =item B<$email> Student's permanent e-mail address
                   9796: 
                   9797: =item B<$type> Type of enrollment (auto or manual)
                   9798: 
1.963     raeburn  9799: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   9800: 
                   9801: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  9802: 
1.963     raeburn  9803: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  9804: 
1.963     raeburn  9805: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  9806: 
1.963     raeburn  9807: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  9808: 
1.286     matthew  9809: =back
1.297     matthew  9810: 
                   9811: =item *
                   9812: 
                   9813: modify_student_enrollment
                   9814: 
                   9815: Change a students enrollment status in a class.  The environment variable
                   9816: 'role.request.course' must be defined for this function to proceed.
                   9817: 
                   9818: Inputs:
                   9819: 
                   9820: =over 4
                   9821: 
                   9822: =item $udom, students domain
                   9823: 
                   9824: =item $uname, students name
                   9825: 
                   9826: =item $uid, students user id
                   9827: 
                   9828: =item $first, students first name
                   9829: 
                   9830: =item $middle
                   9831: 
                   9832: =item $last
                   9833: 
                   9834: =item $gene
                   9835: 
                   9836: =item $usec
                   9837: 
                   9838: =item $end
                   9839: 
                   9840: =item $start
                   9841: 
1.957     raeburn  9842: =item $type
                   9843: 
                   9844: =item $locktype
                   9845: 
                   9846: =item $cid
                   9847: 
                   9848: =item $selfenroll
                   9849: 
                   9850: =item $context
                   9851: 
1.297     matthew  9852: =back
                   9853: 
1.191     harris41 9854: 
                   9855: =item *
                   9856: 
1.243     albertel 9857: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9858: custom role; give a custom role to a user for the level given by URL.  Specify
                   9859: name and domain of role author, and role name
1.191     harris41 9860: 
                   9861: =item *
                   9862: 
1.243     albertel 9863: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9864: 
                   9865: =item *
                   9866: 
1.243     albertel 9867: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9868: 
                   9869: =back
                   9870: 
                   9871: =head2 Course Infomation
                   9872: 
                   9873: =over 4
1.191     harris41 9874: 
                   9875: =item *
                   9876: 
1.631     albertel 9877: coursedescription($courseid) : returns a hash of information about the
                   9878: specified course id, including all environment settings for the
                   9879: course, the description of the course will be in the hash under the
                   9880: key 'description'
1.191     harris41 9881: 
                   9882: =item *
                   9883: 
1.624     albertel 9884: resdata($name,$domain,$type,@which) : request for current parameter
                   9885: setting for a specific $type, where $type is either 'course' or 'user',
                   9886: @what should be a list of parameters to ask about. This routine caches
                   9887: answers for 5 minutes.
1.243     albertel 9888: 
1.877     foxr     9889: =item *
                   9890: 
                   9891: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9892: data base, returning a hash that is keyed by the resource name and has
                   9893: values that are the resource value.  I believe that the timestamps and
                   9894: versions are also returned.
                   9895: 
                   9896: 
1.243     albertel 9897: =back
                   9898: 
                   9899: =head2 Course Modification
                   9900: 
                   9901: =over 4
1.191     harris41 9902: 
                   9903: =item *
                   9904: 
1.243     albertel 9905: writecoursepref($courseid,%prefs) : write preferences (environment
                   9906: database) for a course
1.191     harris41 9907: 
                   9908: =item *
                   9909: 
1.243     albertel 9910: createcourse($udom,$description,$url) : make/modify course
                   9911: 
                   9912: =back
                   9913: 
                   9914: =head2 Resource Subroutines
                   9915: 
                   9916: =over 4
1.191     harris41 9917: 
                   9918: =item *
                   9919: 
1.243     albertel 9920: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9921: 
                   9922: =item *
                   9923: 
1.243     albertel 9924: repcopy($filename) : subscribes to the requested file, and attempts to
                   9925: replicate from the owning library server, Might return
1.607     raeburn  9926: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9927: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9928: resource. Expects the local filesystem pathname
                   9929: (/home/httpd/html/res/....)
                   9930: 
                   9931: =back
                   9932: 
                   9933: =head2 Resource Information
                   9934: 
                   9935: =over 4
1.191     harris41 9936: 
                   9937: =item *
                   9938: 
1.243     albertel 9939: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9940: a vairety of different possible values, $varname should be a request
                   9941: string, and the other parameters can be used to specify who and what
                   9942: one is asking about.
                   9943: 
                   9944: Possible values for $varname are environment.lastname (or other item
                   9945: from the envirnment hash), user.name (or someother aspect about the
                   9946: user), resource.0.maxtries (or some other part and parameter of a
                   9947: resource)
1.204     albertel 9948: 
                   9949: =item *
                   9950: 
1.243     albertel 9951: directcondval($number) : get current value of a condition; reads from a state
                   9952: string
1.204     albertel 9953: 
                   9954: =item *
                   9955: 
1.243     albertel 9956: condval($condidx) : value of condition index based on state
1.204     albertel 9957: 
                   9958: =item *
                   9959: 
1.243     albertel 9960: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9961: resource's metadata, $what should be either a specific key, or either
                   9962: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9963: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9964: 
                   9965: this function automatically caches all requests
1.191     harris41 9966: 
                   9967: =item *
                   9968: 
1.243     albertel 9969: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9970: network of library servers; returns file handle of where SQL and regex results
                   9971: will be stored for query
1.191     harris41 9972: 
                   9973: =item *
                   9974: 
1.243     albertel 9975: symbread($filename) : return symbolic list entry (filename argument optional);
                   9976: returns the data handle
1.191     harris41 9977: 
                   9978: =item *
                   9979: 
1.243     albertel 9980: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9981: a possible symb for the URL in $thisfn, and if is an encryypted
                   9982: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9983: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9984: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9985: 
1.191     harris41 9986: 
                   9987: =item *
                   9988: 
1.243     albertel 9989: symbclean($symb) : removes versions numbers from a symb, returns the
                   9990: cleaned symb
1.191     harris41 9991: 
                   9992: =item *
                   9993: 
1.243     albertel 9994: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9995: course map, user must be in a course for it to work.
1.191     harris41 9996: 
                   9997: =item *
                   9998: 
1.243     albertel 9999: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 10000: 
                   10001: =item *
                   10002: 
1.243     albertel 10003: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   10004: a random seed, all arguments are optional, if they aren't sent it uses the
                   10005: environment to derive them. Note: if symb isn't sent and it can't get one
                   10006: from &symbread it will use the current time as its return value
1.191     harris41 10007: 
                   10008: =item *
                   10009: 
1.243     albertel 10010: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   10011: unfakeable, receipt
1.191     harris41 10012: 
                   10013: =item *
                   10014: 
1.620     albertel 10015: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 10016: 
                   10017: =item *
                   10018: 
1.243     albertel 10019: countacc($url) : count the number of accesses to a given URL
1.191     harris41 10020: 
                   10021: =item *
                   10022: 
1.243     albertel 10023: 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 10024: 
                   10025: =item *
                   10026: 
1.243     albertel 10027: 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 10028: 
                   10029: =item *
                   10030: 
1.243     albertel 10031: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 10032: 
                   10033: =item *
                   10034: 
1.243     albertel 10035: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   10036: forcing spreadsheet to reevaluate the resource scores next time.
                   10037: 
                   10038: =back
                   10039: 
                   10040: =head2 Storing/Retreiving Data
                   10041: 
                   10042: =over 4
1.191     harris41 10043: 
                   10044: =item *
                   10045: 
1.243     albertel 10046: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   10047: for this url; hashref needs to be given and should be a \%hashname; the
                   10048: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 10049: be derived from the env
1.191     harris41 10050: 
                   10051: =item *
                   10052: 
1.243     albertel 10053: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   10054: uses critical subroutine
1.191     harris41 10055: 
                   10056: =item *
                   10057: 
1.243     albertel 10058: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   10059: all args are optional
1.191     harris41 10060: 
                   10061: =item *
                   10062: 
1.717     albertel 10063: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   10064: dumps the complete (or key matching regexp) namespace into a hash
                   10065: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   10066: normally &store()ed into
                   10067: 
                   10068: $range should be either an integer '100' (give me the first 100
                   10069:                                            matching records)
                   10070:               or be  two integers sperated by a - with no spaces
                   10071:                  '30-50' (give me the 30th through the 50th matching
                   10072:                           records)
                   10073: 
                   10074: 
                   10075: =item *
                   10076: 
                   10077: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   10078: replaces a &store() version of data with a replacement set of data
                   10079: for a particular resource in a namespace passed in the $storehash hash 
                   10080: reference
                   10081: 
                   10082: =item *
                   10083: 
1.243     albertel 10084: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   10085: works very similar to store/cstore, but all data is stored in a
                   10086: temporary location and can be reset using tmpreset, $storehash should
                   10087: be a hash reference, returns nothing on success
1.191     harris41 10088: 
                   10089: =item *
                   10090: 
1.243     albertel 10091: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   10092: similar to restore, but all data is stored in a temporary location and
                   10093: can be reset using tmpreset. Returns a hash of values on success,
                   10094: error string otherwise.
1.191     harris41 10095: 
                   10096: =item *
                   10097: 
1.243     albertel 10098: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   10099: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 10100: 
                   10101: =item *
                   10102: 
1.243     albertel 10103: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   10104: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 10105: 
                   10106: =item *
                   10107: 
1.243     albertel 10108: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   10109: namesp ($udom and $uname are optional)
1.191     harris41 10110: 
                   10111: =item *
                   10112: 
1.702     albertel 10113: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 10114: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 10115: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  10116: 
1.702     albertel 10117: $range should be either an integer '100' (give me the first 100
                   10118:                                            matching records)
                   10119:               or be  two integers sperated by a - with no spaces
                   10120:                  '30-50' (give me the 30th through the 50th matching
                   10121:                           records)
1.449     matthew  10122: =item *
                   10123: 
                   10124: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   10125: $store can be a scalar, an array reference, or if the amount to be 
                   10126: incremented is > 1, a hash reference.
                   10127: 
                   10128: ($udom and $uname are optional)
1.191     harris41 10129: 
                   10130: =item *
                   10131: 
1.243     albertel 10132: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   10133: ($udom and $uname are optional)
1.191     harris41 10134: 
                   10135: =item *
                   10136: 
1.243     albertel 10137: cput($namespace,$storehash,$udom,$uname) : critical put
                   10138: ($udom and $uname are optional)
1.191     harris41 10139: 
                   10140: =item *
                   10141: 
1.748     albertel 10142: newput($namespace,$storehash,$udom,$uname) :
                   10143: 
                   10144: Attempts to store the items in the $storehash, but only if they don't
                   10145: currently exist, if this succeeds you can be certain that you have 
                   10146: successfully created a new key value pair in the $namespace db.
                   10147: 
                   10148: 
                   10149: Args:
                   10150:  $namespace: name of database to store values to
                   10151:  $storehash: hashref to store to the db
                   10152:  $udom: (optional) domain of user containing the db
                   10153:  $uname: (optional) name of user caontaining the db
                   10154: 
                   10155: Returns:
                   10156:  'ok' -> succeeded in storing all keys of $storehash
                   10157:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   10158:                         least <key> already existed in the db (other
                   10159:                         requested keys may also already exist)
1.967     bisitz   10160:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 10161:  'con_lost' -> unable to contact request server
                   10162:  'refused' -> action was not allowed by remote machine
                   10163: 
                   10164: 
                   10165: =item *
                   10166: 
1.243     albertel 10167: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   10168: reference filled in from namesp (encrypts the return communication)
                   10169: ($udom and $uname are optional)
1.191     harris41 10170: 
                   10171: =item *
                   10172: 
1.243     albertel 10173: log($udom,$name,$home,$message) : write to permanent log for user; use
                   10174: critical subroutine
                   10175: 
1.806     raeburn  10176: =item *
                   10177: 
1.860     raeburn  10178: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   10179: array reference filled in from namespace found in domain level on either
                   10180: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  10181: 
                   10182: =item *
                   10183: 
1.860     raeburn  10184: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   10185: domain level either on specified domain server ($uhome) or primary domain 
                   10186: server ($udom and $uhome are optional)
1.806     raeburn  10187: 
1.943     raeburn  10188: =item * 
                   10189: 
                   10190: get_domain_defaults($target_domain) : returns hash with defaults for
                   10191: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   10192: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   10193: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   10194: Values are retrieved from cache (if current), or from domain's configuration.db
                   10195: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   10196: or lonTabs/domain.tab. 
                   10197: 
                   10198: %domdefaults = &get_auth_defaults($target_domain);
                   10199: 
1.243     albertel 10200: =back
                   10201: 
                   10202: =head2 Network Status Functions
                   10203: 
                   10204: =over 4
1.191     harris41 10205: 
                   10206: =item *
                   10207: 
                   10208: dirlist($uri) : return directory list based on URI
                   10209: 
                   10210: =item *
                   10211: 
1.243     albertel 10212: spareserver() : find server with least workload from spare.tab
                   10213: 
1.986     foxr     10214: 
                   10215: =item *
                   10216: 
                   10217: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   10218: if there is no corresponding loncapa host.
                   10219: 
1.243     albertel 10220: =back
                   10221: 
1.986     foxr     10222: 
1.243     albertel 10223: =head2 Apache Request
                   10224: 
                   10225: =over 4
1.191     harris41 10226: 
                   10227: =item *
                   10228: 
1.243     albertel 10229: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   10230: localhost, posts hash
                   10231: 
                   10232: =back
                   10233: 
                   10234: =head2 Data to String to Data
                   10235: 
                   10236: =over 4
1.191     harris41 10237: 
                   10238: =item *
                   10239: 
1.243     albertel 10240: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   10241: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 10242: 
                   10243: =item *
                   10244: 
1.243     albertel 10245: hashref2str($hashref) : convert a hashref into a string complete with
                   10246: escaping and '=' and '&' separators, supports elements that are
                   10247: arrayrefs and hashrefs
1.191     harris41 10248: 
                   10249: =item *
                   10250: 
1.243     albertel 10251: arrayref2str($arrayref) : convert an arrayref into a string complete
                   10252: with escaping and '&' separators, supports elements that are arrayrefs
                   10253: and hashrefs
1.191     harris41 10254: 
                   10255: =item *
                   10256: 
1.243     albertel 10257: str2hash($string) : convert string to hash using unescaping and
                   10258: splitting on '=' and '&', supports elements that are arrayrefs and
                   10259: hashrefs
1.191     harris41 10260: 
                   10261: =item *
                   10262: 
1.243     albertel 10263: str2array($string) : convert string to hash using unescaping and
                   10264: splitting on '&', supports elements that are arrayrefs and hashrefs
                   10265: 
                   10266: =back
                   10267: 
                   10268: =head2 Logging Routines
                   10269: 
                   10270: =over 4
                   10271: 
                   10272: These routines allow one to make log messages in the lonnet.log and
                   10273: lonnet.perm logfiles.
1.191     harris41 10274: 
                   10275: =item *
                   10276: 
1.243     albertel 10277: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 10278: 
                   10279: =item *
                   10280: 
1.243     albertel 10281: logthis() : append message to the normal lonnet.log file, it gets
                   10282: preiodically rolled over and deleted.
1.191     harris41 10283: 
                   10284: =item *
                   10285: 
1.243     albertel 10286: logperm() : append a permanent message to lonnet.perm.log, this log
                   10287: file never gets deleted by any automated portion of the system, only
                   10288: messages of critical importance should go in here.
                   10289: 
                   10290: =back
                   10291: 
                   10292: =head2 General File Helper Routines
                   10293: 
                   10294: =over 4
1.191     harris41 10295: 
                   10296: =item *
                   10297: 
1.481     raeburn  10298: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   10299: (a) files in /uploaded
                   10300:   (i) If a local copy of the file exists - 
                   10301:       compares modification date of local copy with last-modified date for 
                   10302:       definitive version stored on home server for course. If local copy is 
                   10303:       stale, requests a new version from the home server and stores it. 
                   10304:       If the original has been removed from the home server, then local copy 
                   10305:       is unlinked.
                   10306:   (ii) If local copy does not exist -
                   10307:       requests the file from the home server and stores it. 
                   10308:   
                   10309:   If $caller is 'uploadrep':  
                   10310:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   10311:     for request for files originally uploaded via DOCS. 
                   10312:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   10313:   
                   10314:   Otherwise:
                   10315:      This indicates a call from the content generation phase of the request.
                   10316:      -  returns the entire contents of the file or -1.
                   10317:      
                   10318: (b) files in /res
                   10319:    - returns the entire contents of a file or -1; 
                   10320:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 10321: 
1.712     albertel 10322: 
                   10323: =item *
                   10324: 
                   10325: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   10326:                   reference
                   10327: 
                   10328: returns either a stat() list of data about the file or an empty list
                   10329: if the file doesn't exist or couldn't find out about it (connection
                   10330: problems or user unknown)
                   10331: 
1.191     harris41 10332: =item *
                   10333: 
1.243     albertel 10334: filelocation($dir,$file) : returns file system location of a file
                   10335: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   10336: directory that relative $file lookups are to looked in ($dir of /a/dir
                   10337: and a file of ../bob will become /a/bob)
1.191     harris41 10338: 
                   10339: =item *
                   10340: 
                   10341: hreflocation($dir,$file) : returns file system location or a URL; same as
                   10342: filelocation except for hrefs
                   10343: 
                   10344: =item *
                   10345: 
                   10346: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   10347: 
1.243     albertel 10348: =back
                   10349: 
1.608     albertel 10350: =head2 Usererfile file routines (/uploaded*)
                   10351: 
                   10352: =over 4
                   10353: 
                   10354: =item *
                   10355: 
                   10356: userfileupload(): main rotine for putting a file in a user or course's
                   10357:                   filespace, arguments are,
                   10358: 
1.620     albertel 10359:  formname - required - this is the name of the element in $env where the
1.608     albertel 10360:            filename, and the contents of the file to create/modifed exist
1.620     albertel 10361:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   10362:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 10363:  coursedoc - if true, store the file in the course of the active role
                   10364:              of the current user
                   10365:  subdir - required - subdirectory to put the file in under ../userfiles/
                   10366:          if undefined, it will be placed in "unknown"
                   10367: 
                   10368:  (This routine calls clean_filename() to remove any dangerous
                   10369:  characters from the filename, and then calls finuserfileupload() to
                   10370:  complete the transaction)
                   10371: 
                   10372:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10373:  and /adm/notfound.html if unsuccessful
                   10374: 
                   10375: =item *
                   10376: 
                   10377: clean_filename(): routine for cleaing a filename up for storage in
                   10378:                  userfile space, argument is:
                   10379: 
                   10380:  filename - proposed filename
                   10381: 
                   10382: returns: the new clean filename
                   10383: 
                   10384: =item *
                   10385: 
                   10386: finishuserfileupload(): routine that creaes and sends the file to
                   10387: userspace, probably shouldn't be called directly
                   10388: 
                   10389:   docuname: username or courseid of destination for the file
                   10390:   docudom: domain of user/course of destination for the file
                   10391:   formname: same as for userfileupload()
                   10392:   fname: filename (inculding subdirectories) for the file
                   10393: 
                   10394:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10395:  and /adm/notfound.html if unsuccessful
                   10396: 
                   10397: =item *
                   10398: 
                   10399: renameuserfile(): renames an existing userfile to a new name
                   10400: 
                   10401:   Args:
                   10402:    docuname: username or courseid of destination for the file
                   10403:    docudom: domain of user/course of destination for the file
                   10404:    old: current file name (including any subdirs under userfiles)
                   10405:    new: desired file name (including any subdirs under userfiles)
                   10406: 
                   10407: =item *
                   10408: 
                   10409: mkdiruserfile(): creates a directory is a userfiles dir
                   10410: 
                   10411:   Args:
                   10412:    docuname: username or courseid of destination for the file
                   10413:    docudom: domain of user/course of destination for the file
                   10414:    dir: dir to create (including any subdirs under userfiles)
                   10415: 
                   10416: =item *
                   10417: 
                   10418: removeuserfile(): removes a file that exists in userfiles
                   10419: 
                   10420:   Args:
                   10421:    docuname: username or courseid of destination for the file
                   10422:    docudom: domain of user/course of destination for the file
                   10423:    fname: filname to delete (including any subdirs under userfiles)
                   10424: 
                   10425: =item *
                   10426: 
                   10427: removeuploadedurl(): convience function for removeuserfile()
                   10428: 
                   10429:   Args:
                   10430:    url:  a full /uploaded/... url to delete
                   10431: 
1.747     albertel 10432: =item * 
                   10433: 
                   10434: get_portfile_permissions():
                   10435:   Args:
                   10436:     domain: domain of user or course contain the portfolio files
                   10437:     user: name of user or num of course contain the portfolio files
                   10438:   Returns:
                   10439:     hashref of a dump of the proper file_permissions.db
                   10440:    
                   10441: 
                   10442: =item * 
                   10443: 
                   10444: get_access_controls():
                   10445: 
                   10446: Args:
                   10447:   current_permissions: the hash ref returned from get_portfile_permissions()
                   10448:   group: (optional) the group you want the files associated with
                   10449:   file: (optional) the file you want access info on
                   10450: 
                   10451: Returns:
1.749     raeburn  10452:     a hash (keys are file names) of hashes containing
                   10453:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   10454:         values are XML containing access control settings (see below) 
1.747     albertel 10455: 
                   10456: Internal notes:
                   10457: 
1.749     raeburn  10458:  access controls are stored in file_permissions.db as key=value pairs.
                   10459:     key -> path to file/file_name\0uniqueID:scope_end_start
                   10460:         where scope -> public,guest,course,group,domains or users.
                   10461:               end -> UNIX time for end of access (0 -> no end date)
                   10462:               start -> UNIX time for start of access
                   10463: 
                   10464:     value -> XML description of access control
                   10465:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   10466:             <start></start>
                   10467:             <end></end>
                   10468: 
                   10469:             <password></password>  for scope type = guest
                   10470: 
                   10471:             <domain></domain>     for scope type = course or group
                   10472:             <number></number>
                   10473:             <roles id="">
                   10474:              <role></role>
                   10475:              <access></access>
                   10476:              <section></section>
                   10477:              <group></group>
                   10478:             </roles>
                   10479: 
                   10480:             <dom></dom>         for scope type = domains
                   10481: 
                   10482:             <users>             for scope type = users
                   10483:              <user>
                   10484:               <uname></uname>
                   10485:               <udom></udom>
                   10486:              </user>
                   10487:             </users>
                   10488:            </scope> 
                   10489:               
                   10490:  Access data is also aggregated for each file in an additional key=value pair:
                   10491:  key -> path to file/file_name\0accesscontrol 
                   10492:  value -> reference to hash
                   10493:           hash contains key = value pairs
                   10494:           where key = uniqueID:scope_end_start
                   10495:                 value = UNIX time record was last updated
                   10496: 
                   10497:           Used to improve speed of look-ups of access controls for each file.  
                   10498:  
                   10499:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   10500: 
                   10501: modify_access_controls():
                   10502: 
                   10503: Modifies access controls for a portfolio file
                   10504: Args
                   10505: 1. file name
                   10506: 2. reference to hash of required changes,
                   10507: 3. domain
                   10508: 4. username
                   10509:   where domain,username are the domain of the portfolio owner 
                   10510:   (either a user or a course) 
                   10511: 
                   10512: Returns:
                   10513: 1. result of additions or updates ('ok' or 'error', with error message). 
                   10514: 2. result of deletions ('ok' or 'error', with error message).
                   10515: 3. reference to hash of any new or updated access controls.
                   10516: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   10517:    key = integer (inbound ID)
                   10518:    value = uniqueID  
1.747     albertel 10519: 
1.608     albertel 10520: =back
                   10521: 
1.243     albertel 10522: =head2 HTTP Helper Routines
                   10523: 
                   10524: =over 4
                   10525: 
1.191     harris41 10526: =item *
                   10527: 
                   10528: escape() : unpack non-word characters into CGI-compatible hex codes
                   10529: 
                   10530: =item *
                   10531: 
                   10532: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   10533: 
1.243     albertel 10534: =back
                   10535: 
                   10536: =head1 PRIVATE SUBROUTINES
                   10537: 
                   10538: =head2 Underlying communication routines (Shouldn't call)
                   10539: 
                   10540: =over 4
                   10541: 
                   10542: =item *
                   10543: 
                   10544: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   10545: 
                   10546: =item *
                   10547: 
                   10548: reply() : uses subreply to send a message to remote machine, logs all failures
                   10549: 
                   10550: =item *
                   10551: 
                   10552: critical() : passes a critical message to another server; if cannot
                   10553: get through then place message in connection buffer directory and
                   10554: returns con_delayed, if incapable of saving message, returns
                   10555: con_failed
                   10556: 
                   10557: =item *
                   10558: 
                   10559: reconlonc() : tries to reconnect lonc client processes.
                   10560: 
                   10561: =back
                   10562: 
                   10563: =head2 Resource Access Logging
                   10564: 
                   10565: =over 4
                   10566: 
                   10567: =item *
                   10568: 
                   10569: flushcourselogs() : flush (save) buffer logs and access logs
                   10570: 
                   10571: =item *
                   10572: 
                   10573: courselog($what) : save message for course in hash
                   10574: 
                   10575: =item *
                   10576: 
                   10577: courseacclog($what) : save message for course using &courselog().  Perform
                   10578: special processing for specific resource types (problems, exams, quizzes, etc).
                   10579: 
1.191     harris41 10580: =item *
                   10581: 
                   10582: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   10583: as a PerlChildExitHandler
1.243     albertel 10584: 
                   10585: =back
                   10586: 
                   10587: =head2 Other
                   10588: 
                   10589: =over 4
                   10590: 
                   10591: =item *
                   10592: 
                   10593: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 10594: 
                   10595: =back
                   10596: 
                   10597: =cut
1.877     foxr     10598: 

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