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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1006  ! raeburn     4: # $Id: lonnet.pm,v 1.1005 2009/07/20 23:33:11 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
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=();
                   1668:     my @answer=split(/\&/,
1.976     raeburn  1669:                 &reply('get:'.$udom.':'.$unam.':environment:'.$items,
1.70      www      1670:                       &homeserver($unam,$udom)));
                   1671:     my $i;
                   1672:     for ($i=0;$i<=$#what;$i++) {
                   1673: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1674:     }
                   1675:     return %returnhash;
1.1       albertel 1676: }
                   1677: 
1.617     albertel 1678: # ---------------------------------------------------------- Get a studentphoto
                   1679: sub studentphoto {
                   1680:     my ($udom,$unam,$ext) = @_;
                   1681:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1682:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1683:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1684:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1685:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1686:             } else {
                   1687:                 my ($result,$perm_reqd)=
1.707     albertel 1688: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1689:                 if ($result eq 'ok') {
                   1690:                     if (!($perm_reqd eq 'yes')) {
                   1691:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1692:                     }
                   1693:                 }
                   1694:             }
                   1695:         }
                   1696:     } else {
                   1697:         my ($result,$perm_reqd) = 
1.707     albertel 1698: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1699:         if ($result eq 'ok') {
                   1700:             if (!($perm_reqd eq 'yes')) {
                   1701:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1702:             }
                   1703:         }
                   1704:     }
                   1705:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1706: }
                   1707: 
                   1708: sub retrievestudentphoto {
                   1709:     my ($udom,$unam,$ext,$type) = @_;
                   1710:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1711:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1712:     if ($ret eq 'ok') {
                   1713:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1714:         if ($type eq 'thumbnail') {
                   1715:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1716:         }
                   1717:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1718:         return $tokenurl;
                   1719:     } else {
                   1720:         if ($type eq 'thumbnail') {
                   1721:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1722:         } else { 
                   1723:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1724:         }
1.617     albertel 1725:     }
                   1726: }
                   1727: 
1.263     www      1728: # -------------------------------------------------------------------- New chat
                   1729: 
                   1730: sub chatsend {
1.724     raeburn  1731:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1732:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1733:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1734:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1735:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1736: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1737: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1738: }
                   1739: 
                   1740: # ------------------------------------------ Find current version of a resource
                   1741: 
                   1742: sub getversion {
                   1743:     my $fname=&clutter(shift);
                   1744:     unless ($fname=~/^\/res\//) { return -1; }
                   1745:     return &currentversion(&filelocation('',$fname));
                   1746: }
                   1747: 
                   1748: sub currentversion {
                   1749:     my $fname=shift;
1.599     albertel 1750:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1751:     if (defined($cached)) { return $result; }
1.292     www      1752:     my $author=$fname;
                   1753:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1754:     my ($udom,$uname)=split(/\//,$author);
                   1755:     my $home=homeserver($uname,$udom);
                   1756:     if ($home eq 'no_host') { 
                   1757:         return -1; 
                   1758:     }
                   1759:     my $answer=reply("currentversion:$fname",$home);
                   1760:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1761: 	return -1;
                   1762:     }
1.599     albertel 1763:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1764: }
                   1765: 
1.1       albertel 1766: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1767: 
1.1       albertel 1768: sub subscribe {
                   1769:     my $fname=shift;
1.761     raeburn  1770:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1771:     $fname=~s/[\n\r]//g;
1.1       albertel 1772:     my $author=$fname;
                   1773:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1774:     my ($udom,$uname)=split(/\//,$author);
                   1775:     my $home=homeserver($uname,$udom);
1.335     albertel 1776:     if ($home eq 'no_host') {
                   1777:         return 'not_found';
1.1       albertel 1778:     }
                   1779:     my $answer=reply("sub:$fname",$home);
1.64      www      1780:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1781: 	$answer.=' by '.$home;
                   1782:     }
1.1       albertel 1783:     return $answer;
                   1784: }
                   1785:     
1.8       www      1786: # -------------------------------------------------------------- Replicate file
                   1787: 
                   1788: sub repcopy {
                   1789:     my $filename=shift;
1.23      www      1790:     $filename=~s/\/+/\//g;
1.607     raeburn  1791:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1792:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1793:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1794: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1795: 	return &repcopy_userfile($filename);
                   1796:     }
1.532     albertel 1797:     $filename=~s/[\n\r]//g;
1.8       www      1798:     my $transname="$filename.in.transfer";
1.828     www      1799: # FIXME: this should flock
1.607     raeburn  1800:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1801:     my $remoteurl=subscribe($filename);
1.64      www      1802:     if ($remoteurl =~ /^con_lost by/) {
                   1803: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1804:            return 'unavailable';
1.8       www      1805:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1806: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1807: 	   return 'not_found';
1.64      www      1808:     } elsif ($remoteurl =~ /^rejected by/) {
                   1809: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1810:            return 'forbidden';
1.20      www      1811:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1812:            return 'ok';
1.8       www      1813:     } else {
1.290     www      1814:         my $author=$filename;
                   1815:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1816:         my ($udom,$uname)=split(/\//,$author);
                   1817:         my $home=homeserver($uname,$udom);
                   1818:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1819:            my @parts=split(/\//,$filename);
                   1820:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1821:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1822:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1823: 	       return 'bad_request';
1.8       www      1824:            }
                   1825:            my $count;
                   1826:            for ($count=5;$count<$#parts;$count++) {
                   1827:                $path.="/$parts[$count]";
                   1828:                if ((-e $path)!=1) {
                   1829: 		   mkdir($path,0777);
                   1830:                }
                   1831:            }
                   1832:            my $ua=new LWP::UserAgent;
                   1833:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1834:            my $response=$ua->request($request,$transname);
                   1835:            if ($response->is_error()) {
                   1836: 	       unlink($transname);
                   1837:                my $message=$response->status_line;
1.672     albertel 1838:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1839:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1840:                return 'unavailable';
1.8       www      1841:            } else {
1.16      www      1842: 	       if ($remoteurl!~/\.meta$/) {
                   1843:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1844:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1845:                   if ($mresponse->is_error()) {
                   1846: 		      unlink($filename.'.meta');
                   1847:                       &logthis(
1.672     albertel 1848:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1849:                   }
                   1850: 	       }
1.8       www      1851:                rename($transname,$filename);
1.607     raeburn  1852:                return 'ok';
1.8       www      1853:            }
1.290     www      1854:        }
1.8       www      1855:     }
1.330     www      1856: }
                   1857: 
                   1858: # ------------------------------------------------ Get server side include body
                   1859: sub ssi_body {
1.381     albertel 1860:     my ($filelink,%form)=@_;
1.606     matthew  1861:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1862:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1863:     }
1.953     www      1864:     my $output='';
                   1865:     my $response;
1.980     raeburn  1866:     if ($filelink=~/^https?\:/) {
1.954     raeburn  1867:        ($output,$response)=&externalssi($filelink);
1.953     www      1868:     } else {
1.1004    droeschl 1869:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   1870:        $filelink .= 'inhibitmenu=yes';
1.953     www      1871:        ($output,$response)=&ssi($filelink,%form);
                   1872:     }
1.778     albertel 1873:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1874:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 1875:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      1876:     if (wantarray) {
                   1877:         return ($output, $response);
                   1878:     } else {
                   1879:         return $output;
                   1880:     }
1.8       www      1881: }
                   1882: 
1.15      www      1883: # --------------------------------------------------------- Server Side Include
                   1884: 
1.782     albertel 1885: sub absolute_url {
                   1886:     my ($host_name) = @_;
                   1887:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1888:     if ($host_name eq '') {
                   1889: 	$host_name = $ENV{'SERVER_NAME'};
                   1890:     }
                   1891:     return $protocol.$host_name;
                   1892: }
                   1893: 
1.942     foxr     1894: #
                   1895: #   Server side include.
                   1896: # Parameters:
                   1897: #  fn     Possibly encrypted resource name/id.
                   1898: #  form   Hash that describes how the rendering should be done
                   1899: #         and other things.
1.944     foxr     1900: # Returns:
1.950     raeburn  1901: #   Scalar context: The content of the response.
                   1902: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     1903: #     
1.15      www      1904: sub ssi {
                   1905: 
1.944     foxr     1906:     my ($fn,%form)=@_;
1.15      www      1907:     my $ua=new LWP::UserAgent;
1.23      www      1908:     my $request;
1.711     albertel 1909: 
                   1910:     $form{'no_update_last_known'}=1;
1.895     albertel 1911:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1912:     if (%form) {
1.782     albertel 1913:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  1914:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      1915:     } else {
1.782     albertel 1916:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1917:     }
                   1918: 
1.15      www      1919:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1920:     my $response=$ua->request($request);
                   1921: 
1.944     foxr     1922:     if (wantarray) {
                   1923: 	return ($response->content, $response);
                   1924:     } else {
                   1925: 	return $response->content;
1.942     foxr     1926:     }
1.324     www      1927: }
                   1928: 
                   1929: sub externalssi {
                   1930:     my ($url)=@_;
                   1931:     my $ua=new LWP::UserAgent;
                   1932:     my $request=new HTTP::Request('GET',$url);
                   1933:     my $response=$ua->request($request);
1.954     raeburn  1934:     if (wantarray) {
                   1935:         return ($response->content, $response);
                   1936:     } else {
                   1937:         return $response->content;
                   1938:     }
1.15      www      1939: }
1.254     www      1940: 
1.492     albertel 1941: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1942: 
                   1943: sub allowuploaded {
                   1944:     my ($srcurl,$url)=@_;
                   1945:     $url=&clutter(&declutter($url));
                   1946:     my $dir=$url;
                   1947:     $dir=~s/\/[^\/]+$//;
                   1948:     my %httpref=();
                   1949:     my $httpurl=&hreflocation('',$url);
                   1950:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  1951:     &Apache::lonnet::appenv(\%httpref);
1.254     www      1952: }
1.477     raeburn  1953: 
1.478     albertel 1954: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1955: # input: action, courseID, current domain, intended
1.637     raeburn  1956: #        path to file, source of file, instruction to parse file for objects,
                   1957: #        ref to hash for embedded objects,
                   1958: #        ref to hash for codebase of java objects.
                   1959: #
1.485     raeburn  1960: # output: url to file (if action was uploaddoc), 
                   1961: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1962: #
1.478     albertel 1963: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1964: # course.
1.477     raeburn  1965: #
1.478     albertel 1966: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1967: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1968: #          course's home server.
1.477     raeburn  1969: #
1.478     albertel 1970: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1971: #          be copied from $source (current location) to 
                   1972: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1973: #         and will then be copied to
                   1974: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1975: #         course's home server.
1.485     raeburn  1976: #
1.481     raeburn  1977: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1978: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1979: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1980: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1981: #         in course's home server.
1.637     raeburn  1982: #
1.477     raeburn  1983: 
                   1984: sub process_coursefile {
1.638     albertel 1985:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1986:     my $fetchresult;
1.638     albertel 1987:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1988:     if ($action eq 'propagate') {
1.638     albertel 1989:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1990: 			     $home);
1.481     raeburn  1991:     } else {
1.477     raeburn  1992:         my $fpath = '';
                   1993:         my $fname = $file;
1.478     albertel 1994:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1995:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1996:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1997:         if ($action eq 'copy') {
                   1998:             if ($source eq '') {
                   1999:                 $fetchresult = 'no source file';
                   2000:                 return $fetchresult;
                   2001:             } else {
                   2002:                 my $destination = $filepath.'/'.$fname;
                   2003:                 rename($source,$destination);
                   2004:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2005:                                  $home);
1.481     raeburn  2006:             }
                   2007:         } elsif ($action eq 'uploaddoc') {
                   2008:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2009:             print $fh $env{'form.'.$source};
1.481     raeburn  2010:             close($fh);
1.637     raeburn  2011:             if ($parser eq 'parse') {
1.961     raeburn  2012:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
1.637     raeburn  2013:                 unless ($parse_result eq 'ok') {
                   2014:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2015:                 }
                   2016:             }
1.477     raeburn  2017:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2018:                                  $home);
1.481     raeburn  2019:             if ($fetchresult eq 'ok') {
                   2020:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2021:             } else {
                   2022:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2023:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2024:                 return '/adm/notfound.html';
                   2025:             }
1.477     raeburn  2026:         }
                   2027:     }
1.485     raeburn  2028:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2029:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2030:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2031:     }
                   2032:     return $fetchresult;
                   2033: }
                   2034: 
1.637     raeburn  2035: sub build_filepath {
                   2036:     my ($fpath) = @_;
                   2037:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2038:     unless ($fpath eq '') {
                   2039:         my @parts=split('/',$fpath);
                   2040:         foreach my $part (@parts) {
                   2041:             $filepath.= '/'.$part;
                   2042:             if ((-e $filepath)!=1) {
                   2043:                 mkdir($filepath,0777);
                   2044:             }
                   2045:         }
                   2046:     }
                   2047:     return $filepath;
                   2048: }
                   2049: 
                   2050: sub store_edited_file {
1.638     albertel 2051:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2052:     my $file = $primary_url;
                   2053:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2054:     my $fpath = '';
                   2055:     my $fname = $file;
                   2056:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2057:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2058:     my $filepath = &build_filepath($fpath);
                   2059:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2060:     print $fh $content;
                   2061:     close($fh);
1.638     albertel 2062:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2063:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2064: 			  $home);
1.637     raeburn  2065:     if ($$fetchresult eq 'ok') {
                   2066:         return '/uploaded/'.$fpath.'/'.$fname;
                   2067:     } else {
1.638     albertel 2068:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2069: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2070:         return '/adm/notfound.html';
                   2071:     }
                   2072: }
                   2073: 
1.531     albertel 2074: sub clean_filename {
1.831     albertel 2075:     my ($fname,$args)=@_;
1.315     www      2076: # Replace Windows backslashes by forward slashes
1.257     www      2077:     $fname=~s/\\/\//g;
1.831     albertel 2078:     if (!$args->{'keep_path'}) {
                   2079:         # Get rid of everything but the actual filename
                   2080: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2081:     }
1.315     www      2082: # Replace spaces by underscores
                   2083:     $fname=~s/\s+/\_/g;
                   2084: # Replace all other weird characters by nothing
1.831     albertel 2085:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2086: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2087: # numbers
                   2088:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2089:     return $fname;
                   2090: }
1.984     neumanie 2091: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
                   2092: sub resizeImage {
                   2093: 	my($img_url) = @_;	
                   2094: 	my $ima = Image::Magick->new;                       
                   2095:         $ima->Read($img_url);
                   2096: 	if($ima->Get('width') > 400)
                   2097: 	{
                   2098: 		my $factor = $ima->Get('width')/400;
                   2099:              	$ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
                   2100: 	}
                   2101: 	if($ima->Get('height') > 500)
                   2102:         {
                   2103:         	my $factor = $ima->Get('height')/500;
                   2104:                 $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
                   2105:         } 
                   2106: 		
                   2107: 	$ima->Write($img_url);
                   2108: }
1.531     albertel 2109: 
1.977     amueller 2110: #Wrapper function for userphotoupload
                   2111: sub userphotoupload
                   2112: {
                   2113: 	my($formname,$subdir) = @_;
                   2114: 	$upload_photo_form = 1;
                   2115: 	return &userfileupload($formname,undef,$subdir);
                   2116: }
                   2117: 
1.608     albertel 2118: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2119: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 2120: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 2121: #        $coursedoc - if true up to the current course
                   2122: #                     if false
                   2123: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2124: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2125: #        $allfiles - reference to hash for embedded objects
                   2126: #        $codebase - reference to hash for codebase of java objects
                   2127: #        $desuname - username for permanent storage of uploaded file
                   2128: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2129: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2130: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  2131: # 
1.686     albertel 2132: # output: url of file in userspace, or error: <message> 
                   2133: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2134: 
                   2135: 
1.531     albertel 2136: sub userfileupload {
1.860     raeburn  2137:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   2138:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 2139:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2140:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2141:     $fname=&clean_filename($fname);
1.315     www      2142: # See if there is anything left
1.257     www      2143:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2144:     chop($env{'form.'.$formname});
1.523     raeburn  2145:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2146:         my $now = time;
                   2147:         my $filepath = 'tmp/helprequests/'.$now;
                   2148:         my @parts=split(/\//,$filepath);
                   2149:         my $fullpath = $perlvar{'lonDaemons'};
                   2150:         for (my $i=0;$i<@parts;$i++) {
                   2151:             $fullpath .= '/'.$parts[$i];
                   2152:             if ((-e $fullpath)!=1) {
                   2153:                 mkdir($fullpath,0777);
                   2154:             }
                   2155:         }
                   2156:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2157:         print $fh $env{'form.'.$formname};
1.523     raeburn  2158:         close($fh);
1.741     raeburn  2159:         return $fullpath.'/'.$fname;
                   2160:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2161:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2162:                        '_'.$env{'user.domain'}.'/pending';
                   2163:         my @parts=split(/\//,$filepath);
                   2164:         my $fullpath = $perlvar{'lonDaemons'};
                   2165:         for (my $i=0;$i<@parts;$i++) {
                   2166:             $fullpath .= '/'.$parts[$i];
                   2167:             if ((-e $fullpath)!=1) {
                   2168:                 mkdir($fullpath,0777);
                   2169:             }
                   2170:         }
                   2171:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2172:         print $fh $env{'form.'.$formname};
                   2173:         close($fh);
                   2174:         return $fullpath.'/'.$fname;
1.523     raeburn  2175:     }
1.995     raeburn  2176:     if ($subdir eq 'scantron') {
                   2177:         $fname = 'scantron_orig_'.$fname;
                   2178:     } else {   
1.258     www      2179: # Create the directory if not present
1.995     raeburn  2180:         $fname="$subdir/$fname";
                   2181:     }
1.259     www      2182:     if ($coursedoc) {
1.638     albertel 2183: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2184: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2185:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2186:             return &finishuserfileupload($docuname,$docudom,
                   2187: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  2188: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  2189:         } else {
1.620     albertel 2190:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2191:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2192: 				       $fname,$formname,$parser,
                   2193: 				       $allfiles,$codebase);
1.481     raeburn  2194:         }
1.719     banghart 2195:     } elsif (defined($destuname)) {
                   2196:         my $docuname=$destuname;
                   2197:         my $docudom=$destudom;
1.860     raeburn  2198: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2199: 				     $parser,$allfiles,$codebase,
                   2200:                                      $thumbwidth,$thumbheight);
1.719     banghart 2201:         
1.259     www      2202:     } else {
1.638     albertel 2203:         my $docuname=$env{'user.name'};
                   2204:         my $docudom=$env{'user.domain'};
1.714     raeburn  2205:         if (exists($env{'form.group'})) {
                   2206:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2207:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2208:         }
1.860     raeburn  2209: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2210: 				     $parser,$allfiles,$codebase,
                   2211:                                      $thumbwidth,$thumbheight);
1.259     www      2212:     }
1.271     www      2213: }
                   2214: 
                   2215: sub finishuserfileupload {
1.860     raeburn  2216:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   2217:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  2218:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2219:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2220:   
1.860     raeburn  2221:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2222:     $file=$fname;
                   2223:     if ($fname=~m|/|) {
                   2224:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2225: 	$path.=$fnamepath.'/';
                   2226:     }
1.259     www      2227:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2228:     my $count;
                   2229:     for ($count=4;$count<=$#parts;$count++) {
                   2230:         $filepath.="/$parts[$count]";
                   2231:         if ((-e $filepath)!=1) {
                   2232: 	    mkdir($filepath,0777);
                   2233:         }
                   2234:     }
1.984     neumanie 2235: 
1.258     www      2236: # Save the file
                   2237:     {
1.701     albertel 2238: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2239: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2240: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2241: 	    return '/adm/notfound.html';
                   2242: 	}
                   2243: 	if (!print FH ($env{'form.'.$formname})) {
                   2244: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2245: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2246: 	    return '/adm/notfound.html';
                   2247: 	}
1.570     albertel 2248: 	close(FH);
1.977     amueller 2249: 	if($upload_photo_form==1)
                   2250: 	{
1.984     neumanie 2251: 		resizeImage($filepath.'/'.$file);		
1.977     amueller 2252: 		$upload_photo_form = 0;
                   2253: 	}
1.258     www      2254:     }
1.637     raeburn  2255:     if ($parser eq 'parse') {
1.961     raeburn  2256:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
1.638     albertel 2257: 						   $codebase);
1.637     raeburn  2258:         unless ($parse_result eq 'ok') {
1.638     albertel 2259:             &logthis('Failed to parse '.$filepath.$file.
                   2260: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  2261:         }
                   2262:     }
1.860     raeburn  2263:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2264:         my $input = $filepath.'/'.$file;
                   2265:         my $output = $filepath.'/'.'tn-'.$file;
                   2266:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2267:         system("convert -sample $thumbsize $input $output");
                   2268:         if (-e $filepath.'/'.'tn-'.$file) {
                   2269:             $fetchthumb  = 1; 
                   2270:         }
                   2271:     }
1.858     raeburn  2272:  
1.259     www      2273: # Notify homeserver to grep it
                   2274: #
1.984     neumanie 2275:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2276:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2277:     if ($fetchresult eq 'ok') {
1.860     raeburn  2278:         if ($fetchthumb) {
                   2279:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2280:             if ($thumbresult ne 'ok') {
                   2281:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2282:                          $docuhome.': '.$thumbresult);
                   2283:             }
                   2284:         }
1.259     www      2285: #
1.258     www      2286: # Return the URL to it
1.494     albertel 2287:         return '/uploaded/'.$path.$file;
1.263     www      2288:     } else {
1.494     albertel 2289:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2290: 		 ': '.$fetchresult);
1.263     www      2291:         return '/adm/notfound.html';
1.858     raeburn  2292:     }
1.493     albertel 2293: }
                   2294: 
1.637     raeburn  2295: sub extract_embedded_items {
1.961     raeburn  2296:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2297:     my @state = ();
                   2298:     my %javafiles = (
                   2299:                       codebase => '',
                   2300:                       code => '',
                   2301:                       archive => ''
                   2302:                     );
                   2303:     my %mediafiles = (
                   2304:                       src => '',
                   2305:                       movie => '',
                   2306:                      );
1.648     raeburn  2307:     my $p;
                   2308:     if ($content) {
                   2309:         $p = HTML::LCParser->new($content);
                   2310:     } else {
1.961     raeburn  2311:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2312:     }
1.641     albertel 2313:     while (my $t=$p->get_token()) {
1.640     albertel 2314: 	if ($t->[0] eq 'S') {
                   2315: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2316: 	    push(@state, $tagname);
1.648     raeburn  2317:             if (lc($tagname) eq 'allow') {
                   2318:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2319:             }
1.640     albertel 2320: 	    if (lc($tagname) eq 'img') {
                   2321: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2322: 	    }
1.886     albertel 2323: 	    if (lc($tagname) eq 'a') {
                   2324: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2325: 	    }
1.645     raeburn  2326:             if (lc($tagname) eq 'script') {
                   2327:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2328:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2329:                 } else {
                   2330:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2331:                 }
                   2332:             }
                   2333:             if (lc($tagname) eq 'link') {
                   2334:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2335:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2336:                 }
                   2337:             }
1.640     albertel 2338: 	    if (lc($tagname) eq 'object' ||
                   2339: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2340: 		foreach my $item (keys(%javafiles)) {
                   2341: 		    $javafiles{$item} = '';
                   2342: 		}
                   2343: 	    }
                   2344: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2345: 		my $name = lc($attr->{'name'});
                   2346: 		foreach my $item (keys(%javafiles)) {
                   2347: 		    if ($name eq $item) {
                   2348: 			$javafiles{$item} = $attr->{'value'};
                   2349: 			last;
                   2350: 		    }
                   2351: 		}
                   2352: 		foreach my $item (keys(%mediafiles)) {
                   2353: 		    if ($name eq $item) {
                   2354: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2355: 			last;
                   2356: 		    }
                   2357: 		}
                   2358: 	    }
                   2359: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2360: 		foreach my $item (keys(%javafiles)) {
                   2361: 		    if ($attr->{$item}) {
                   2362: 			$javafiles{$item} = $attr->{$item};
                   2363: 			last;
                   2364: 		    }
                   2365: 		}
                   2366: 		foreach my $item (keys(%mediafiles)) {
                   2367: 		    if ($attr->{$item}) {
                   2368: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2369: 			last;
                   2370: 		    }
                   2371: 		}
                   2372: 	    }
                   2373: 	} elsif ($t->[0] eq 'E') {
                   2374: 	    my ($tagname) = ($t->[1]);
                   2375: 	    if ($javafiles{'codebase'} ne '') {
                   2376: 		$javafiles{'codebase'} .= '/';
                   2377: 	    }  
                   2378: 	    if (lc($tagname) eq 'applet' ||
                   2379: 		lc($tagname) eq 'object' ||
                   2380: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2381: 		) {
                   2382: 		foreach my $item (keys(%javafiles)) {
                   2383: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2384: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2385: 			&add_filetype($allfiles,$file,$item);
                   2386: 		    }
                   2387: 		}
                   2388: 	    } 
                   2389: 	    pop @state;
                   2390: 	}
                   2391:     }
1.637     raeburn  2392:     return 'ok';
                   2393: }
                   2394: 
1.639     albertel 2395: sub add_filetype {
                   2396:     my ($allfiles,$file,$type)=@_;
                   2397:     if (exists($allfiles->{$file})) {
                   2398: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2399: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2400: 	}
                   2401:     } else {
                   2402: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2403:     }
                   2404: }
                   2405: 
1.493     albertel 2406: sub removeuploadedurl {
1.984     neumanie 2407:     my ($url)=@_;	
                   2408:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2409:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2410: }
                   2411: 
                   2412: sub removeuserfile {
                   2413:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2414:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2415:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2416:     if ($result eq 'ok') {	
1.798     raeburn  2417:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2418:             my $metafile = $fname.'.meta';
                   2419:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2420: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2421:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2422:             my $sqlresult = 
1.823     albertel 2423:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2424:                                         'portfolio_metadata',$group,
                   2425:                                         'delete');
1.798     raeburn  2426:         }
                   2427:     }
                   2428:     return $result;
1.257     www      2429: }
1.15      www      2430: 
1.530     albertel 2431: sub mkdiruserfile {
                   2432:     my ($docuname,$docudom,$dir)=@_;
                   2433:     my $home=&homeserver($docuname,$docudom);
                   2434:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2435: }
                   2436: 
1.531     albertel 2437: sub renameuserfile {
                   2438:     my ($docuname,$docudom,$old,$new)=@_;
                   2439:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2440:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2441:                         &escape("$old").':'.&escape("$new"),$home);
                   2442:     if ($result eq 'ok') {
                   2443:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2444:             my $oldmeta = $old.'.meta';
                   2445:             my $newmeta = $new.'.meta';
                   2446:             my $metaresult = 
                   2447:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2448: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2449:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2450:             my $sqlresult = 
1.823     albertel 2451:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2452:                                         'portfolio_metadata',$group,
                   2453:                                         'delete');
1.798     raeburn  2454:         }
                   2455:     }
                   2456:     return $result;
1.531     albertel 2457: }
                   2458: 
1.14      www      2459: # ------------------------------------------------------------------------- Log
                   2460: 
                   2461: sub log {
                   2462:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2463:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2464: }
                   2465: 
                   2466: # ------------------------------------------------------------------ Course Log
1.352     www      2467: #
                   2468: # This routine flushes several buffers of non-mission-critical nature
                   2469: #
1.157     www      2470: 
                   2471: sub flushcourselogs {
1.352     www      2472:     &logthis('Flushing log buffers');
                   2473: #
                   2474: # course logs
                   2475: # This is a log of all transactions in a course, which can be used
                   2476: # for data mining purposes
                   2477: #
                   2478: # It also collects the courseid database, which lists last transaction
                   2479: # times and course titles for all courseids
                   2480: #
                   2481:     my %courseidbuffer=();
1.921     raeburn  2482:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2483:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2484: 		          &escape($courselogs{$crsid}),
                   2485: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2486: 	    delete $courselogs{$crsid};
                   2487:         } else {
                   2488:             &logthis('Failed to flush log buffer for '.$crsid);
                   2489:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2490:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2491:                         " exceeded maximum size, deleting.</font>");
                   2492:                delete $courselogs{$crsid};
                   2493:             }
1.352     www      2494:         }
1.920     raeburn  2495:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2496:             'description' => $coursedescrbuf{$crsid},
                   2497:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2498:             'type'        => $coursetypebuf{$crsid},
                   2499:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2500:         };
1.191     harris41 2501:     }
1.352     www      2502: #
                   2503: # Write course id database (reverse lookup) to homeserver of courses 
                   2504: # Is used in pickcourse
                   2505: #
1.840     albertel 2506:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2507:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2508:                                     $courseidbuffer{$crs_home},
                   2509:                                     $crs_home,'timeonly');
1.352     www      2510:     }
                   2511: #
                   2512: # File accesses
                   2513: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2514: #
1.449     matthew  2515:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2516:         if ($entry =~ /___count$/) {
                   2517:             my ($dom,$name);
1.807     albertel 2518:             ($dom,$name,undef)=
1.811     albertel 2519: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2520:             if (! defined($dom) || $dom eq '' || 
                   2521:                 ! defined($name) || $name eq '') {
1.620     albertel 2522:                 my $cid = $env{'request.course.id'};
                   2523:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2524:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2525:             }
1.450     matthew  2526:             my $value = $accesshash{$entry};
                   2527:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2528:             my %temphash=($url => $value);
1.449     matthew  2529:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2530:             if ($result eq 'ok') {
                   2531:                 delete $accesshash{$entry};
                   2532:             } elsif ($result eq 'unknown_cmd') {
                   2533:                 # Target server has old code running on it.
1.450     matthew  2534:                 my %temphash=($entry => $value);
1.449     matthew  2535:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2536:                     delete $accesshash{$entry};
                   2537:                 }
                   2538:             }
                   2539:         } else {
1.811     albertel 2540:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2541:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2542:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2543:                 delete $accesshash{$entry};
                   2544:             }
1.185     www      2545:         }
1.191     harris41 2546:     }
1.352     www      2547: #
                   2548: # Roles
                   2549: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2550: #
1.800     albertel 2551:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2552:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2553: 	    split(/\:/,$entry);
                   2554:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2555:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2556:                 $rudom,$runame) eq 'ok') {
                   2557: 	    delete $userrolehash{$entry};
                   2558:         }
                   2559:     }
1.662     raeburn  2560: #
                   2561: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2562: #
                   2563:     my %domrolebuffer = ();
1.1000    raeburn  2564:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 2565:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2566:         if ($domrolebuffer{$rudom}) {
                   2567:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2568:                       '='.&escape($domainrolehash{$entry});
                   2569:         } else {
                   2570:             $domrolebuffer{$rudom}.=&escape($entry).
                   2571:                       '='.&escape($domainrolehash{$entry});
                   2572:         }
                   2573:         delete $domainrolehash{$entry};
                   2574:     }
                   2575:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2576: 	my %servers = &get_servers($dom,'library');
                   2577: 	foreach my $tryserver (keys(%servers)) {
                   2578: 	    unless (&reply('domroleput:'.$dom.':'.
                   2579: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2580: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2581: 	    }
1.662     raeburn  2582:         }
                   2583:     }
1.186     www      2584:     $dumpcount++;
1.157     www      2585: }
                   2586: 
                   2587: sub courselog {
                   2588:     my $what=shift;
1.158     www      2589:     $what=time.':'.$what;
1.620     albertel 2590:     unless ($env{'request.course.id'}) { return ''; }
                   2591:     $coursedombuf{$env{'request.course.id'}}=
                   2592:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2593:     $coursenumbuf{$env{'request.course.id'}}=
                   2594:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2595:     $coursehombuf{$env{'request.course.id'}}=
                   2596:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2597:     $coursedescrbuf{$env{'request.course.id'}}=
                   2598:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2599:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2600:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2601:     $courseownerbuf{$env{'request.course.id'}}=
                   2602:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2603:     $coursetypebuf{$env{'request.course.id'}}=
                   2604:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2605:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2606: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2607:     } else {
1.620     albertel 2608: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2609:     }
1.620     albertel 2610:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2611: 	&flushcourselogs();
                   2612:     }
1.158     www      2613: }
                   2614: 
                   2615: sub courseacclog {
                   2616:     my $fnsymb=shift;
1.620     albertel 2617:     unless ($env{'request.course.id'}) { return ''; }
                   2618:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2619:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2620:         $what.=':POST';
1.583     matthew  2621:         # FIXME: Probably ought to escape things....
1.800     albertel 2622: 	foreach my $key (keys(%env)) {
                   2623:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2624:                 my $formitem = $1;
                   2625:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2626:                     $what.=':'.$formitem.'='.$env{$key};
                   2627:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2628:                     $what.=':'.$formitem.'='.$env{$key};
                   2629:                 }
1.158     www      2630:             }
1.191     harris41 2631:         }
1.583     matthew  2632:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2633:         # FIXME: We should not be depending on a form parameter that someone
                   2634:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2635:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2636:             $what.= ':POST';
                   2637:             # FIXME: Probably ought to escape things....
                   2638:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2639:                                  'crsdiscuss') {
1.620     albertel 2640:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2641:             }
                   2642:         }
1.158     www      2643:     }
                   2644:     &courselog($what);
1.149     www      2645: }
                   2646: 
1.185     www      2647: sub countacc {
                   2648:     my $url=&declutter(shift);
1.458     matthew  2649:     return if (! defined($url) || $url eq '');
1.620     albertel 2650:     unless ($env{'request.course.id'}) { return ''; }
                   2651:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2652:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2653:     $accesshash{$key}++;
1.185     www      2654: }
1.349     www      2655: 
1.361     www      2656: sub linklog {
                   2657:     my ($from,$to)=@_;
                   2658:     $from=&declutter($from);
                   2659:     $to=&declutter($to);
                   2660:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2661:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2662: }
                   2663:   
1.349     www      2664: sub userrolelog {
                   2665:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2666:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2667:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2668:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2669:         ($trole=~/^ta/)) {
1.350     www      2670:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2671:        $userrolehash
                   2672:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2673:                     =$tend.':'.$tstart;
1.662     raeburn  2674:     }
1.898     albertel 2675:     if (($env{'request.role'} =~ /dc\./) &&
                   2676: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2677: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2678: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2679:        $userrolehash
                   2680:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2681:                     =$tend.':'.$tstart;
                   2682:     }
1.662     raeburn  2683:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2684:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2685:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2686:         ($trole=~/^sc/)) {
                   2687:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2688:        $domainrolehash
                   2689:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2690:                     = $tend.':'.$tstart;
                   2691:     }
1.351     www      2692: }
                   2693: 
1.957     raeburn  2694: sub courserolelog {
                   2695:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2696:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2697:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2698:         ($trole eq 'ta') || ($trole eq 'st') ||
                   2699:         ($trole=~/^cr/) || ($trole eq 'gr')) {
                   2700:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2701:             my $cdom = $1;
                   2702:             my $cnum = $2;
                   2703:             my $sec = $3;
                   2704:             my $namespace = 'rolelog';
                   2705:             my %storehash = (
                   2706:                                role    => $trole,
                   2707:                                start   => $tstart,
                   2708:                                end     => $tend,
                   2709:                                selfenroll => $selfenroll,
                   2710:                                context    => $context,
                   2711:                             );
                   2712:             if ($trole eq 'gr') {
                   2713:                 $namespace = 'groupslog';
                   2714:                 $storehash{'group'} = $sec;
                   2715:             } else {
                   2716:                 $storehash{'section'} = $sec;
                   2717:             }
                   2718:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  2719:             if (($trole ne 'st') || ($sec ne '')) {
                   2720:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   2721:             }
1.957     raeburn  2722:         }
                   2723:     }
                   2724:     return;
                   2725: }
                   2726: 
1.351     www      2727: sub get_course_adv_roles {
1.948     raeburn  2728:     my ($cid,$codes) = @_;
1.620     albertel 2729:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2730:     my %coursehash=&coursedescription($cid);
1.988     raeburn  2731:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      2732:     my %nothide=();
1.800     albertel 2733:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2734:         if ($user !~ /:/) {
                   2735: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2736:         } else {
                   2737:             $nothide{$user}=1;
                   2738:         }
1.470     www      2739:     }
1.351     www      2740:     my %returnhash=();
                   2741:     my %dumphash=
                   2742:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2743:     my $now=time;
1.997     raeburn  2744:     my %privileged;
1.1000    raeburn  2745:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 2746: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2747:         if (($tstart) && ($tstart<0)) { next; }
                   2748:         if (($tend) && ($tend<$now)) { next; }
                   2749:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2750:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2751: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  2752:         unless (ref($privileged{$domain}) eq 'HASH') {
                   2753:             my %dompersonnel =
1.998     raeburn  2754:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  2755:             $privileged{$domain} = {};
                   2756:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  2757:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  2758:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   2759:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   2760:                         $privileged{$udom}{$uname} = 1;
                   2761:                     }
                   2762:                 }
                   2763:             }
                   2764:         }
                   2765:         if ((exists($privileged{$domain}{$username})) && 
                   2766:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2767: 	if ($role eq 'cr') { next; }
1.948     raeburn  2768:         if ($codes) {
                   2769:             if ($section) { $role .= ':'.$section; }
                   2770:             if ($returnhash{$role}) {
                   2771:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2772:             } else {
                   2773:                 $returnhash{$role}=$username.':'.$domain;
                   2774:             }
1.351     www      2775:         } else {
1.988     raeburn  2776:             my $key=&plaintext($role,$crstype);
1.973     bisitz   2777:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  2778:             if ($returnhash{$key}) {
                   2779: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2780:             } else {
                   2781:                 $returnhash{$key}=$username.':'.$domain;
                   2782:             }
1.351     www      2783:         }
1.948     raeburn  2784:     }
1.400     www      2785:     return %returnhash;
                   2786: }
                   2787: 
                   2788: sub get_my_roles {
1.937     raeburn  2789:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2790:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2791:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2792:     my (%dumphash,%nothide);
1.858     raeburn  2793:     if ($context eq 'userroles') { 
                   2794:         %dumphash = &dump('roles',$udom,$uname);
                   2795:     } else {
                   2796:         %dumphash=
1.400     www      2797:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2798:         if ($hidepriv) {
                   2799:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2800:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2801:                 if ($user !~ /:/) {
                   2802:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2803:                 } else {
                   2804:                     $nothide{$user} = 1;
                   2805:                 }
                   2806:             }
                   2807:         }
1.858     raeburn  2808:     }
1.400     www      2809:     my %returnhash=();
                   2810:     my $now=time;
1.999     raeburn  2811:     my %privileged;
1.800     albertel 2812:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2813:         my ($role,$tend,$tstart);
                   2814:         if ($context eq 'userroles') {
                   2815: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2816:         } else {
                   2817:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2818:         }
1.400     www      2819:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2820:         my $status = 'active';
1.939     raeburn  2821:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2822:             $status = 'previous';
                   2823:         } 
                   2824:         if (($tstart) && ($now<$tstart)) {
                   2825:             $status = 'future';
                   2826:         }
                   2827:         if (ref($types) eq 'ARRAY') {
                   2828:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2829:                 next;
                   2830:             } 
                   2831:         } else {
                   2832:             if ($status ne 'active') {
                   2833:                 next;
                   2834:             }
                   2835:         }
1.867     raeburn  2836:         my ($rolecode,$username,$domain,$section,$area);
                   2837:         if ($context eq 'userroles') {
                   2838:             ($area,$rolecode) = split(/_/,$entry);
                   2839:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2840:         } else {
                   2841:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2842:         }
1.832     raeburn  2843:         if (ref($roledoms) eq 'ARRAY') {
                   2844:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2845:                 next;
                   2846:             }
                   2847:         }
                   2848:         if (ref($roles) eq 'ARRAY') {
                   2849:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2850:                 if ($role =~ /^cr\//) {
                   2851:                     if (!grep(/^cr$/,@{$roles})) {
                   2852:                         next;
                   2853:                     }
                   2854:                 } else {
                   2855:                     next;
                   2856:                 }
1.832     raeburn  2857:             }
1.867     raeburn  2858:         }
1.937     raeburn  2859:         if ($hidepriv) {
1.999     raeburn  2860:             if ($context eq 'userroles') {
                   2861:                 if ((&privileged($username,$domain)) &&
                   2862:                     (!$nothide{$username.':'.$domain})) {
                   2863:                     next;
                   2864:                 }
                   2865:             } else {
                   2866:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   2867:                     my %dompersonnel =
                   2868:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   2869:                     $privileged{$domain} = {};
                   2870:                     if (keys(%dompersonnel)) {
                   2871:                         foreach my $server (keys(%dompersonnel)) {
                   2872:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   2873:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   2874:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   2875:                                     $privileged{$udom}{$uname} = $trole;
                   2876:                                 }
                   2877:                             }
                   2878:                         }
                   2879:                     }
                   2880:                 }
                   2881:                 if (exists($privileged{$domain}{$username})) {
                   2882:                     if (!$nothide{$username.':'.$domain}) {
                   2883:                         next;
                   2884:                     }
                   2885:                 }
1.937     raeburn  2886:             }
                   2887:         }
1.933     raeburn  2888:         if ($withsec) {
                   2889:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2890:                 $tstart.':'.$tend;
                   2891:         } else {
                   2892:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2893:         }
1.832     raeburn  2894:     }
1.373     www      2895:     return %returnhash;
1.399     www      2896: }
                   2897: 
                   2898: # ----------------------------------------------------- Frontpage Announcements
                   2899: #
                   2900: #
                   2901: 
                   2902: sub postannounce {
                   2903:     my ($server,$text)=@_;
1.844     albertel 2904:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2905:     unless ($text=~/\w/) { $text=''; }
                   2906:     return &reply('setannounce:'.&escape($text),$server);
                   2907: }
                   2908: 
                   2909: sub getannounce {
1.448     albertel 2910: 
                   2911:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2912: 	my $announcement='';
1.800     albertel 2913: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2914: 	close($fh);
1.399     www      2915: 	if ($announcement=~/\w/) { 
                   2916: 	    return 
                   2917:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2918:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2919: 	} else {
                   2920: 	    return '';
                   2921: 	}
                   2922:     } else {
                   2923: 	return '';
                   2924:     }
1.351     www      2925: }
1.353     www      2926: 
                   2927: # ---------------------------------------------------------- Course ID routines
                   2928: # Deal with domain's nohist_courseid.db files
                   2929: #
                   2930: 
                   2931: sub courseidput {
1.921     raeburn  2932:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2933:     my $outcome;
                   2934:     if ($caller eq 'timeonly') {
                   2935:         my $cids = '';
                   2936:         foreach my $item (keys(%$storehash)) {
                   2937:             $cids.=&escape($item).'&';
                   2938:         }
                   2939:         $cids=~s/\&$//;
                   2940:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2941:                           $coursehome);       
                   2942:     } else {
                   2943:         my $items = '';
                   2944:         foreach my $item (keys(%$storehash)) {
                   2945:             $items.= &escape($item).'='.
                   2946:                      &freeze_escape($$storehash{$item}).'&';
                   2947:         }
                   2948:         $items=~s/\&$//;
                   2949:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2950:                           $coursehome);
1.918     raeburn  2951:     }
                   2952:     if ($outcome eq 'unknown_cmd') {
                   2953:         my $what;
                   2954:         foreach my $cid (keys(%$storehash)) {
                   2955:             $what .= &escape($cid).'=';
1.921     raeburn  2956:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2957:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2958:             }
                   2959:             $what =~ s/\:$/&/;
                   2960:         }
                   2961:         $what =~ s/\&$//;  
                   2962:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2963:     } else {
                   2964:         return $outcome;
                   2965:     }
1.353     www      2966: }
                   2967: 
                   2968: sub courseiddump {
1.921     raeburn  2969:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  2970:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.962     raeburn  2971:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
1.918     raeburn  2972:     my $as_hash = 1;
                   2973:     my %returnhash;
                   2974:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2975:     my %libserv = &all_library();
                   2976:     foreach my $tryserver (keys(%libserv)) {
                   2977:         if ( (  $hostidflag == 1 
                   2978: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2979: 	     || (!defined($hostidflag)) ) {
                   2980: 
1.918     raeburn  2981: 	    if (($domfilter eq '') ||
                   2982: 		(&host_domain($tryserver) eq $domfilter)) {
                   2983:                 my $rep = 
                   2984:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2985:                          $sincefilter.':'.&escape($descfilter).':'.
                   2986:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2987:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  2988:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  2989:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   2990:                          $showhidden.':'.$caller,$tryserver);
1.918     raeburn  2991:                 my @pairs=split(/\&/,$rep);
                   2992:                 foreach my $item (@pairs) {
                   2993:                     my ($key,$value)=split(/\=/,$item,2);
                   2994:                     $key = &unescape($key);
                   2995:                     next if ($key =~ /^error: 2 /);
                   2996:                     my $result = &thaw_unescape($value);
                   2997:                     if (ref($result) eq 'HASH') {
                   2998:                         $returnhash{$key}=$result;
                   2999:                     } else {
1.921     raeburn  3000:                         my @responses = split(/:/,$value);
                   3001:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3002:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3003:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3004:                         }
                   3005:                     } 
1.353     www      3006:                 }
                   3007:             }
                   3008:         }
                   3009:     }
                   3010:     return %returnhash;
                   3011: }
                   3012: 
1.658     raeburn  3013: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3014: 
                   3015: sub dcmailput {
1.685     raeburn  3016:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3017:     my $status = &Apache::lonnet::critical(
1.740     www      3018:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3019:        &escape($message),$server);
1.662     raeburn  3020:     return $status;
                   3021: }
                   3022: 
1.658     raeburn  3023: sub dcmaildump {
                   3024:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3025:     my %returnhash=();
1.846     albertel 3026: 
                   3027:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3028:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3029:                                                          &escape($enddate).':';
                   3030: 	my @esc_senders=map { &escape($_)} @$senders;
                   3031: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3032: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3033:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3034:             if (($key) && ($value)) {
                   3035:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3036:             }
                   3037:         }
                   3038:     }
                   3039:     return %returnhash;
                   3040: }
1.662     raeburn  3041: # ---------------------------------------------------------- Domain roles
                   3042: 
                   3043: sub get_domain_roles {
                   3044:     my ($dom,$roles,$startdate,$enddate)=@_;
                   3045:     if (undef($startdate) || $startdate eq '') {
                   3046:         $startdate = '.';
                   3047:     }
                   3048:     if (undef($enddate) || $enddate eq '') {
                   3049:         $enddate = '.';
                   3050:     }
1.922     raeburn  3051:     my $rolelist;
                   3052:     if (ref($roles) eq 'ARRAY') {
                   3053:         $rolelist = join(':',@{$roles});
                   3054:     }
1.662     raeburn  3055:     my %personnel = ();
1.841     albertel 3056: 
                   3057:     my %servers = &get_servers($dom,'library');
                   3058:     foreach my $tryserver (keys(%servers)) {
                   3059: 	%{$personnel{$tryserver}}=();
                   3060: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3061: 					    &escape($startdate).':'.
                   3062: 					    &escape($enddate).':'.
                   3063: 					    &escape($rolelist), $tryserver))) {
                   3064: 	    my ($key,$value) = split(/\=/,$line,2);
                   3065: 	    if (($key) && ($value)) {
                   3066: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3067: 	    }
                   3068: 	}
1.662     raeburn  3069:     }
                   3070:     return %personnel;
                   3071: }
1.658     raeburn  3072: 
1.149     www      3073: # ----------------------------------------------------------- Check out an item
                   3074: 
1.504     albertel 3075: sub get_first_access {
                   3076:     my ($type,$argsymb)=@_;
1.790     albertel 3077:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3078:     if ($argsymb) { $symb=$argsymb; }
                   3079:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3080:     if ($type eq 'course') {
                   3081: 	$res='course';
                   3082:     } elsif ($type eq 'map') {
1.588     albertel 3083: 	$res=&symbread($map);
                   3084:     } else {
                   3085: 	$res=$symb;
                   3086:     }
                   3087:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3088:     return $times{"$courseid\0$res"};
1.504     albertel 3089: }
                   3090: 
                   3091: sub set_first_access {
                   3092:     my ($type)=@_;
1.790     albertel 3093:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3094:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3095:     if ($type eq 'course') {
                   3096: 	$res='course';
                   3097:     } elsif ($type eq 'map') {
1.588     albertel 3098: 	$res=&symbread($map);
                   3099:     } else {
                   3100: 	$res=$symb;
                   3101:     }
                   3102:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3103:     if (!$firstaccess) {
1.588     albertel 3104: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3105:     }
                   3106:     return 'already_set';
1.504     albertel 3107: }
                   3108: 
1.149     www      3109: sub checkout {
                   3110:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   3111:     my $now=time;
                   3112:     my $lonhost=$perlvar{'lonHostID'};
                   3113:     my $infostr=&escape(
1.234     www      3114:                  'CHECKOUTTOKEN&'.
1.149     www      3115:                  $tuname.'&'.
                   3116:                  $tudom.'&'.
                   3117:                  $tcrsid.'&'.
                   3118:                  $symb.'&'.
                   3119: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   3120:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      3121:     if ($token=~/^error\:/) { 
1.672     albertel 3122:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3123:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3124:                  "</font>");
                   3125:         return ''; 
                   3126:     }
                   3127: 
1.149     www      3128:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   3129:     $token=~tr/a-z/A-Z/;
                   3130: 
1.153     www      3131:     my %infohash=('resource.0.outtoken' => $token,
                   3132:                   'resource.0.checkouttime' => $now,
                   3133:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      3134: 
                   3135:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3136:        return '';
1.151     www      3137:     } else {
1.672     albertel 3138:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3139:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3140:                  "</font>");
1.149     www      3141:     }    
                   3142: 
                   3143:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3144:                          &escape('Checkout '.$infostr.' - '.
                   3145:                                                  $token)) ne 'ok') {
                   3146: 	return '';
1.151     www      3147:     } else {
1.672     albertel 3148:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3149:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3150:                  "</font>");
1.149     www      3151:     }
1.151     www      3152:     return $token;
1.149     www      3153: }
                   3154: 
                   3155: # ------------------------------------------------------------ Check in an item
                   3156: 
                   3157: sub checkin {
                   3158:     my $token=shift;
1.150     www      3159:     my $now=time;
                   3160:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3161:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3162:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3163:     $dtoken=~s/\W/\_/g;
1.234     www      3164:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3165:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3166: 
1.154     www      3167:     unless (($tuname) && ($tudom)) {
                   3168:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3169:         return '';
                   3170:     }
                   3171:     
                   3172:     unless (&allowed('mgr',$tcrsid)) {
                   3173:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3174:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3175:         return '';
                   3176:     }
                   3177: 
1.153     www      3178:     my %infohash=('resource.0.intoken' => $token,
                   3179:                   'resource.0.checkintime' => $now,
                   3180:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3181: 
                   3182:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3183:        return '';
                   3184:     }    
                   3185: 
                   3186:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3187:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3188: 	return '';
                   3189:     }
                   3190: 
                   3191:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3192: }
                   3193: 
                   3194: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3195: 
                   3196: sub expirespread {
                   3197:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3198:     my $cid=$env{'request.course.id'}; 
1.110     www      3199:     if ($cid) {
                   3200:        my $now=time;
                   3201:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3202:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3203:                             $env{'course.'.$cid.'.num'}.
1.110     www      3204: 	        	    ':nohist_expirationdates:'.
                   3205:                             &escape($key).'='.$now,
1.620     albertel 3206:                             $env{'course.'.$cid.'.home'})
1.110     www      3207:     }
                   3208:     return 'ok';
1.14      www      3209: }
                   3210: 
1.109     www      3211: # ----------------------------------------------------- Devalidate Spreadsheets
                   3212: 
                   3213: sub devalidate {
1.325     www      3214:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3215:     my $cid=$env{'request.course.id'}; 
1.109     www      3216:     if ($cid) {
1.391     matthew  3217:         # delete the stored spreadsheets for
                   3218:         # - the student level sheet of this user in course's homespace
                   3219:         # - the assessment level sheet for this resource 
                   3220:         #   for this user in user's homespace
1.553     albertel 3221: 	# - current conditional state info
1.325     www      3222: 	my $key=$uname.':'.$udom.':';
1.109     www      3223:         my $status=
1.299     matthew  3224: 	    &del('nohist_calculatedsheets',
1.391     matthew  3225: 		 [$key.'studentcalc:'],
1.620     albertel 3226: 		 $env{'course.'.$cid.'.domain'},
                   3227: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3228: 		.' '.
                   3229: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3230: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3231:         unless ($status eq 'ok ok') {
                   3232:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3233:                     $uname.' at '.$udom.' for '.
1.109     www      3234: 		    $symb.': '.$status);
1.133     albertel 3235:         }
1.553     albertel 3236: 	&delenv('user.state.'.$cid);
1.109     www      3237:     }
                   3238: }
                   3239: 
1.265     albertel 3240: sub get_scalar {
                   3241:     my ($string,$end) = @_;
                   3242:     my $value;
                   3243:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3244: 	$value = $1;
                   3245:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3246: 	$value = $1;
                   3247:     }
                   3248:     return &unescape($value);
                   3249: }
                   3250: 
                   3251: sub array2str {
                   3252:   my (@array) = @_;
                   3253:   my $result=&arrayref2str(\@array);
                   3254:   $result=~s/^__ARRAY_REF__//;
                   3255:   $result=~s/__END_ARRAY_REF__$//;
                   3256:   return $result;
                   3257: }
                   3258: 
1.204     albertel 3259: sub arrayref2str {
                   3260:   my ($arrayref) = @_;
1.265     albertel 3261:   my $result='__ARRAY_REF__';
1.204     albertel 3262:   foreach my $elem (@$arrayref) {
1.265     albertel 3263:     if(ref($elem) eq 'ARRAY') {
                   3264:       $result.=&arrayref2str($elem).'&';
                   3265:     } elsif(ref($elem) eq 'HASH') {
                   3266:       $result.=&hashref2str($elem).'&';
                   3267:     } elsif(ref($elem)) {
                   3268:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3269:     } else {
                   3270:       $result.=&escape($elem).'&';
                   3271:     }
                   3272:   }
                   3273:   $result=~s/\&$//;
1.265     albertel 3274:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3275:   return $result;
                   3276: }
                   3277: 
1.168     albertel 3278: sub hash2str {
1.204     albertel 3279:   my (%hash) = @_;
                   3280:   my $result=&hashref2str(\%hash);
1.265     albertel 3281:   $result=~s/^__HASH_REF__//;
                   3282:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3283:   return $result;
                   3284: }
                   3285: 
                   3286: sub hashref2str {
                   3287:   my ($hashref)=@_;
1.265     albertel 3288:   my $result='__HASH_REF__';
1.800     albertel 3289:   foreach my $key (sort(keys(%$hashref))) {
                   3290:     if (ref($key) eq 'ARRAY') {
                   3291:       $result.=&arrayref2str($key).'=';
                   3292:     } elsif (ref($key) eq 'HASH') {
                   3293:       $result.=&hashref2str($key).'=';
                   3294:     } elsif (ref($key)) {
1.265     albertel 3295:       $result.='=';
1.800     albertel 3296:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3297:     } else {
1.800     albertel 3298: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3299:     }
                   3300: 
1.800     albertel 3301:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3302:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3303:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3304:       $result.=&hashref2str($hashref->{$key}).'&';
                   3305:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3306:        $result.='&';
1.800     albertel 3307:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3308:     } else {
1.800     albertel 3309:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3310:     }
                   3311:   }
1.168     albertel 3312:   $result=~s/\&$//;
1.265     albertel 3313:   $result .= '__END_HASH_REF__';
1.168     albertel 3314:   return $result;
                   3315: }
                   3316: 
                   3317: sub str2hash {
1.265     albertel 3318:     my ($string)=@_;
                   3319:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3320:     return %$hash;
                   3321: }
                   3322: 
                   3323: sub str2hashref {
1.168     albertel 3324:   my ($string) = @_;
1.265     albertel 3325: 
                   3326:   my %hash;
                   3327: 
                   3328:   if($string !~ /^__HASH_REF__/) {
                   3329:       if (! ($string eq '' || !defined($string))) {
                   3330: 	  $hash{'error'}='Not hash reference';
                   3331:       }
                   3332:       return (\%hash, $string);
                   3333:   }
                   3334: 
                   3335:   $string =~ s/^__HASH_REF__//;
                   3336: 
                   3337:   while($string !~ /^__END_HASH_REF__/) {
                   3338:       #key
                   3339:       my $key='';
                   3340:       if($string =~ /^__HASH_REF__/) {
                   3341:           ($key, $string)=&str2hashref($string);
                   3342:           if(defined($key->{'error'})) {
                   3343:               $hash{'error'}='Bad data';
                   3344:               return (\%hash, $string);
                   3345:           }
                   3346:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3347:           ($key, $string)=&str2arrayref($string);
                   3348:           if($key->[0] eq 'Array reference error') {
                   3349:               $hash{'error'}='Bad data';
                   3350:               return (\%hash, $string);
                   3351:           }
                   3352:       } else {
                   3353:           $string =~ s/^(.*?)=//;
1.267     albertel 3354: 	  $key=&unescape($1);
1.265     albertel 3355:       }
                   3356:       $string =~ s/^=//;
                   3357: 
                   3358:       #value
                   3359:       my $value='';
                   3360:       if($string =~ /^__HASH_REF__/) {
                   3361:           ($value, $string)=&str2hashref($string);
                   3362:           if(defined($value->{'error'})) {
                   3363:               $hash{'error'}='Bad data';
                   3364:               return (\%hash, $string);
                   3365:           }
                   3366:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3367:           ($value, $string)=&str2arrayref($string);
                   3368:           if($value->[0] eq 'Array reference error') {
                   3369:               $hash{'error'}='Bad data';
                   3370:               return (\%hash, $string);
                   3371:           }
                   3372:       } else {
                   3373: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3374:       }
                   3375:       $string =~ s/^&//;
                   3376: 
                   3377:       $hash{$key}=$value;
1.204     albertel 3378:   }
1.265     albertel 3379: 
                   3380:   $string =~ s/^__END_HASH_REF__//;
                   3381: 
                   3382:   return (\%hash, $string);
1.204     albertel 3383: }
                   3384: 
                   3385: sub str2array {
1.265     albertel 3386:     my ($string)=@_;
                   3387:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3388:     return @$array;
                   3389: }
                   3390: 
                   3391: sub str2arrayref {
1.204     albertel 3392:   my ($string) = @_;
1.265     albertel 3393:   my @array;
                   3394: 
                   3395:   if($string !~ /^__ARRAY_REF__/) {
                   3396:       if (! ($string eq '' || !defined($string))) {
                   3397: 	  $array[0]='Array reference error';
                   3398:       }
                   3399:       return (\@array, $string);
                   3400:   }
                   3401: 
                   3402:   $string =~ s/^__ARRAY_REF__//;
                   3403: 
                   3404:   while($string !~ /^__END_ARRAY_REF__/) {
                   3405:       my $value='';
                   3406:       if($string =~ /^__HASH_REF__/) {
                   3407:           ($value, $string)=&str2hashref($string);
                   3408:           if(defined($value->{'error'})) {
                   3409:               $array[0] ='Array reference error';
                   3410:               return (\@array, $string);
                   3411:           }
                   3412:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3413:           ($value, $string)=&str2arrayref($string);
                   3414:           if($value->[0] eq 'Array reference error') {
                   3415:               $array[0] ='Array reference error';
                   3416:               return (\@array, $string);
                   3417:           }
                   3418:       } else {
                   3419: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3420:       }
                   3421:       $string =~ s/^&//;
                   3422: 
                   3423:       push(@array, $value);
1.191     harris41 3424:   }
1.265     albertel 3425: 
                   3426:   $string =~ s/^__END_ARRAY_REF__//;
                   3427: 
                   3428:   return (\@array, $string);
1.168     albertel 3429: }
                   3430: 
1.167     albertel 3431: # -------------------------------------------------------------------Temp Store
                   3432: 
1.168     albertel 3433: sub tmpreset {
                   3434:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3435:   if (!$symb) {
                   3436:     $symb=&symbread();
1.620     albertel 3437:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3438:   }
                   3439:   $symb=escape($symb);
                   3440: 
1.620     albertel 3441:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3442:   $namespace=~s/\//\_/g;
                   3443:   $namespace=~s/\W//g;
                   3444: 
1.620     albertel 3445:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3446:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3447:   if ($domain eq 'public' && $stuname eq 'public') {
                   3448:       $stuname=$ENV{'REMOTE_ADDR'};
                   3449:   }
1.168     albertel 3450:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3451:   my %hash;
                   3452:   if (tie(%hash,'GDBM_File',
                   3453: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3454: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3455:     foreach my $key (keys(%hash)) {
1.180     albertel 3456:       if ($key=~ /:$symb/) {
1.168     albertel 3457: 	delete($hash{$key});
                   3458:       }
                   3459:     }
                   3460:   }
                   3461: }
                   3462: 
1.167     albertel 3463: sub tmpstore {
1.168     albertel 3464:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3465: 
                   3466:   if (!$symb) {
                   3467:     $symb=&symbread();
1.620     albertel 3468:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3469:   }
                   3470:   $symb=escape($symb);
                   3471: 
                   3472:   if (!$namespace) {
                   3473:     # I don't think we would ever want to store this for a course.
                   3474:     # it seems this will only be used if we don't have a course.
1.620     albertel 3475:     #$namespace=$env{'request.course.id'};
1.168     albertel 3476:     #if (!$namespace) {
1.620     albertel 3477:       $namespace=$env{'request.state'};
1.168     albertel 3478:     #}
                   3479:   }
                   3480:   $namespace=~s/\//\_/g;
                   3481:   $namespace=~s/\W//g;
1.620     albertel 3482:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3483:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3484:   if ($domain eq 'public' && $stuname eq 'public') {
                   3485:       $stuname=$ENV{'REMOTE_ADDR'};
                   3486:   }
1.168     albertel 3487:   my $now=time;
                   3488:   my %hash;
                   3489:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3490:   if (tie(%hash,'GDBM_File',
                   3491: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3492: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3493:     $hash{"version:$symb"}++;
                   3494:     my $version=$hash{"version:$symb"};
                   3495:     my $allkeys=''; 
                   3496:     foreach my $key (keys(%$storehash)) {
                   3497:       $allkeys.=$key.':';
1.591     albertel 3498:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3499:     }
                   3500:     $hash{"$version:$symb:timestamp"}=$now;
                   3501:     $allkeys.='timestamp';
                   3502:     $hash{"$version:keys:$symb"}=$allkeys;
                   3503:     if (untie(%hash)) {
                   3504:       return 'ok';
                   3505:     } else {
                   3506:       return "error:$!";
                   3507:     }
                   3508:   } else {
                   3509:     return "error:$!";
                   3510:   }
                   3511: }
1.167     albertel 3512: 
1.168     albertel 3513: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3514: 
1.168     albertel 3515: sub tmprestore {
                   3516:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3517: 
1.168     albertel 3518:   if (!$symb) {
                   3519:     $symb=&symbread();
1.620     albertel 3520:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3521:   }
                   3522:   $symb=escape($symb);
                   3523: 
1.620     albertel 3524:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3525: 
1.620     albertel 3526:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3527:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3528:   if ($domain eq 'public' && $stuname eq 'public') {
                   3529:       $stuname=$ENV{'REMOTE_ADDR'};
                   3530:   }
1.168     albertel 3531:   my %returnhash;
                   3532:   $namespace=~s/\//\_/g;
                   3533:   $namespace=~s/\W//g;
                   3534:   my %hash;
                   3535:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3536:   if (tie(%hash,'GDBM_File',
                   3537: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3538: 	  &GDBM_READER(),0640)) {
1.168     albertel 3539:     my $version=$hash{"version:$symb"};
                   3540:     $returnhash{'version'}=$version;
                   3541:     my $scope;
                   3542:     for ($scope=1;$scope<=$version;$scope++) {
                   3543:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3544:       my @keys=split(/:/,$vkeys);
                   3545:       my $key;
                   3546:       $returnhash{"$scope:keys"}=$vkeys;
                   3547:       foreach $key (@keys) {
1.591     albertel 3548: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3549: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3550:       }
                   3551:     }
1.168     albertel 3552:     if (!(untie(%hash))) {
                   3553:       return "error:$!";
                   3554:     }
                   3555:   } else {
                   3556:     return "error:$!";
                   3557:   }
                   3558:   return %returnhash;
1.167     albertel 3559: }
                   3560: 
1.9       www      3561: # ----------------------------------------------------------------------- Store
                   3562: 
                   3563: sub store {
1.124     www      3564:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3565:     my $home='';
                   3566: 
1.168     albertel 3567:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3568: 
1.213     www      3569:     $symb=&symbclean($symb);
1.122     albertel 3570:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3571: 
1.620     albertel 3572:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3573:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3574: 
                   3575:     &devalidate($symb,$stuname,$domain);
1.109     www      3576: 
                   3577:     $symb=escape($symb);
1.187     www      3578:     if (!$namespace) { 
1.620     albertel 3579:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3580:           return ''; 
                   3581:        } 
                   3582:     }
1.620     albertel 3583:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3584: 
                   3585:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3586:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3587: 
1.12      www      3588:     my $namevalue='';
1.800     albertel 3589:     foreach my $key (keys(%$storehash)) {
                   3590:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3591:     }
1.12      www      3592:     $namevalue=~s/\&$//;
1.187     www      3593:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3594:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3595: }
                   3596: 
1.47      www      3597: # -------------------------------------------------------------- Critical Store
                   3598: 
                   3599: sub cstore {
1.124     www      3600:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3601:     my $home='';
                   3602: 
1.168     albertel 3603:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3604: 
1.213     www      3605:     $symb=&symbclean($symb);
1.122     albertel 3606:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3607: 
1.620     albertel 3608:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3609:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3610: 
                   3611:     &devalidate($symb,$stuname,$domain);
1.109     www      3612: 
                   3613:     $symb=escape($symb);
1.187     www      3614:     if (!$namespace) { 
1.620     albertel 3615:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3616:           return ''; 
                   3617:        } 
                   3618:     }
1.620     albertel 3619:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3620: 
                   3621:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3622:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3623: 
1.47      www      3624:     my $namevalue='';
1.800     albertel 3625:     foreach my $key (keys(%$storehash)) {
                   3626:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3627:     }
1.47      www      3628:     $namevalue=~s/\&$//;
1.187     www      3629:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3630:     return critical
                   3631:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3632: }
                   3633: 
1.9       www      3634: # --------------------------------------------------------------------- Restore
                   3635: 
                   3636: sub restore {
1.124     www      3637:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3638:     my $home='';
                   3639: 
1.168     albertel 3640:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3641: 
1.122     albertel 3642:     if (!$symb) {
                   3643:       unless ($symb=escape(&symbread())) { return ''; }
                   3644:     } else {
1.213     www      3645:       $symb=&escape(&symbclean($symb));
1.122     albertel 3646:     }
1.188     www      3647:     if (!$namespace) { 
1.620     albertel 3648:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3649:           return ''; 
                   3650:        } 
                   3651:     }
1.620     albertel 3652:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3653:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3654:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3655:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3656: 
1.12      www      3657:     my %returnhash=();
1.800     albertel 3658:     foreach my $line (split(/\&/,$answer)) {
                   3659: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3660:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3661:     }
1.75      www      3662:     my $version;
                   3663:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3664:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3665:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3666:        }
1.75      www      3667:     }
1.13      www      3668:     return %returnhash;
1.34      www      3669: }
                   3670: 
                   3671: # ---------------------------------------------------------- Course Description
                   3672: 
                   3673: sub coursedescription {
1.731     albertel 3674:     my ($courseid,$args)=@_;
1.34      www      3675:     $courseid=~s/^\///;
1.49      www      3676:     $courseid=~s/\_/\//g;
1.34      www      3677:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3678:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3679:     my $normalid=$cdomain.'_'.$cnum;
                   3680:     # need to always cache even if we get errors otherwise we keep 
                   3681:     # trying and trying and trying to get the course description.
                   3682:     my %envhash=();
                   3683:     my %returnhash=();
1.731     albertel 3684:     
                   3685:     my $expiretime=600;
                   3686:     if ($env{'request.course.id'} eq $normalid) {
                   3687: 	$expiretime=120;
                   3688:     }
                   3689: 
                   3690:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3691:     if (!$args->{'freshen_cache'}
                   3692: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3693: 	foreach my $key (keys(%env)) {
                   3694: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3695: 	    my ($setting) = $1;
                   3696: 	    $returnhash{$setting} = $env{$key};
                   3697: 	}
                   3698: 	return %returnhash;
                   3699:     }
                   3700: 
                   3701:     # get the data agin
                   3702:     if (!$args->{'one_time'}) {
                   3703: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3704:     }
1.811     albertel 3705: 
1.34      www      3706:     if ($chome ne 'no_host') {
1.302     albertel 3707:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3708:        if (!exists($returnhash{'con_lost'})) {
                   3709:            $returnhash{'home'}= $chome;
                   3710: 	   $returnhash{'domain'} = $cdomain;
                   3711: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3712:            if (!defined($returnhash{'type'})) {
                   3713:                $returnhash{'type'} = 'Course';
                   3714:            }
1.130     albertel 3715:            while (my ($name,$value) = each %returnhash) {
1.53      www      3716:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3717:            }
1.270     www      3718:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3719:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3720: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3721:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3722:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3723:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3724:        }
                   3725:     }
1.731     albertel 3726:     if (!$args->{'one_time'}) {
1.949     raeburn  3727: 	&appenv(\%envhash);
1.731     albertel 3728:     }
1.302     albertel 3729:     return %returnhash;
1.461     www      3730: }
                   3731: 
                   3732: # -------------------------------------------------See if a user is privileged
                   3733: 
                   3734: sub privileged {
                   3735:     my ($username,$domain)=@_;
                   3736:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3737: 			&homeserver($username,$domain));
                   3738:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3739:     my $now=time;
                   3740:     if ($rolesdump ne '') {
1.800     albertel 3741:         foreach my $entry (split(/&/,$rolesdump)) {
                   3742: 	    if ($entry!~/^rolesdef_/) {
                   3743: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3744: 		$area=~s/\_\w\w$//;
                   3745: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3746: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3747: 		    my $active=1;
                   3748: 		    if ($tend) {
                   3749: 			if ($tend<$now) { $active=0; }
                   3750: 		    }
                   3751: 		    if ($tstart) {
                   3752: 			if ($tstart>$now) { $active=0; }
                   3753: 		    }
                   3754: 		    if ($active) { return 1; }
                   3755: 		}
                   3756: 	    }
                   3757: 	}
                   3758:     }
                   3759:     return 0;
1.9       www      3760: }
1.1       albertel 3761: 
1.103     harris41 3762: # -------------------------------------------------------- Get user privileges
1.11      www      3763: 
                   3764: sub rolesinit {
                   3765:     my ($domain,$username,$authhost)=@_;
1.966     raeburn  3766:     my %userroles;
1.11      www      3767:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.966     raeburn  3768:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
1.11      www      3769:     my %allroles=();
1.678     raeburn  3770:     my %allgroups=();   
1.11      www      3771:     my $now=time;
1.966     raeburn  3772:     %userroles = ('user.login.time' => $now);
1.678     raeburn  3773:     my $group_privs;
1.11      www      3774: 
                   3775:     if ($rolesdump ne '') {
1.800     albertel 3776:         foreach my $entry (split(/&/,$rolesdump)) {
                   3777: 	  if ($entry!~/^rolesdef_/) {
                   3778:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3779: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3780:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3781: 	    if ($role=~/^cr/) { 
1.807     albertel 3782: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3783: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3784: 		    ($tend,$tstart)=split('_',$trest);
                   3785: 		} else {
                   3786: 		    $trole=$role;
                   3787: 		}
1.678     raeburn  3788:             } elsif ($role =~ m|^gr/|) {
                   3789:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3790:                 ($trole,$group_privs) = split(/\//,$trole);
                   3791:                 $group_privs = &unescape($group_privs);
1.587     albertel 3792: 	    } else {
                   3793: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3794: 	    }
1.743     albertel 3795: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3796: 					 $username);
                   3797: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3798:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3799:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3800:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3801: 		my $spec=$trole.'.'.$area;
                   3802: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3803: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3804:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3805:                 } elsif ($trole eq 'gr') {
                   3806:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3807: 		} else {
1.567     raeburn  3808:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3809: 		}
1.12      www      3810:             }
1.662     raeburn  3811:           }
1.191     harris41 3812:         }
1.743     albertel 3813:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3814:         $userroles{'user.adv'}    = $adv;
                   3815: 	$userroles{'user.author'} = $author;
1.620     albertel 3816:         $env{'user.adv'}=$adv;
1.11      www      3817:     }
1.743     albertel 3818:     return \%userroles;  
1.11      www      3819: }
                   3820: 
1.567     raeburn  3821: sub set_arearole {
                   3822:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3823: # log the associated role with the area
                   3824:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3825:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3826: }
                   3827: 
                   3828: sub custom_roleprivs {
                   3829:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3830:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3831:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3832:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3833:         my ($rdummy,$roledef)=
                   3834:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3835:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3836:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3837:             if (defined($syspriv)) {
                   3838:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3839:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3840:             }
                   3841:             if ($tdomain ne '') {
                   3842:                 if (defined($dompriv)) {
                   3843:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3844:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3845:                 }
                   3846:                 if (($trest ne '') && (defined($coursepriv))) {
                   3847:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3848:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3849:                 }
                   3850:             }
                   3851:         }
                   3852:     }
                   3853: }
                   3854: 
1.678     raeburn  3855: sub group_roleprivs {
                   3856:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3857:     my $access = 1;
                   3858:     my $now = time;
                   3859:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3860:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3861:     if ($access) {
1.811     albertel 3862:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3863:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3864:     }
                   3865: }
1.567     raeburn  3866: 
                   3867: sub standard_roleprivs {
                   3868:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3869:     if (defined($pr{$trole.':s'})) {
                   3870:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3871:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3872:     }
                   3873:     if ($tdomain ne '') {
                   3874:         if (defined($pr{$trole.':d'})) {
                   3875:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3876:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3877:         }
                   3878:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3879:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3880:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3881:         }
                   3882:     }
                   3883: }
                   3884: 
                   3885: sub set_userprivs {
1.678     raeburn  3886:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3887:     my $author=0;
                   3888:     my $adv=0;
1.678     raeburn  3889:     my %grouproles = ();
                   3890:     if (keys(%{$allgroups}) > 0) {
1.1000    raeburn  3891:         foreach my $role (keys(%{$allroles})) {
1.681     raeburn  3892:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3893:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3894:                 $trole = $1;
                   3895:                 $area = $2;
1.681     raeburn  3896:                 $sec = $3;
                   3897:                 $extendedarea = $area.$sec;
                   3898:                 if (exists($$allgroups{$area})) {
                   3899:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3900:                         my $spec = $trole.'.'.$extendedarea;
                   3901:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3902:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3903:                     }
                   3904:                 }
                   3905:             }
                   3906:         }
                   3907:     }
1.800     albertel 3908:     foreach my $group (keys(%grouproles)) {
                   3909:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3910:     }
1.800     albertel 3911:     foreach my $role (keys(%{$allroles})) {
                   3912:         my %thesepriv;
1.941     raeburn  3913:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3914:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3915:             if ($item ne '') {
                   3916:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3917:                 if ($restrictions eq '') {
                   3918:                     $thesepriv{$privilege}='F';
                   3919:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3920:                     $thesepriv{$privilege}.=$restrictions;
                   3921:                 }
                   3922:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3923:             }
                   3924:         }
                   3925:         my $thesestr='';
1.800     albertel 3926:         foreach my $priv (keys(%thesepriv)) {
                   3927: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3928: 	}
                   3929:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3930:     }
                   3931:     return ($author,$adv);
                   3932: }
                   3933: 
1.994     raeburn  3934: sub role_status {
1.1002    raeburn  3935:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  3936:     my @pwhere = ();
                   3937:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   3938:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   3939:         unless (!defined($$role) || $$role eq '') {
                   3940:             $$where=join('.',@pwhere);
                   3941:             $$trolecode=$$role.'.'.$$where;
                   3942:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   3943:             $$tstatus='is';
                   3944:             if ($$tstart && $$tstart>$then) {
                   3945:                 $$tstatus='future';
1.1002    raeburn  3946:                 if ($$tstart && $$tstart>$refresh) {
                   3947:                     if ($$tstart<$now) {
                   3948:                         if (($$where ne '') && ($$role ne '')) {
                   3949:                             my (%allroles,%allgroups,$group_privs);
                   3950:                             my %userroles = (
                   3951:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   3952:                             );
                   3953:                             my $spec=$$role.'.'.$$where;
                   3954:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   3955:                             if ($$role eq 'gr') {
                   3956:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   3957:                                                     $env{'user.name'})=@_;
                   3958:                                 my ($trole) = split('_',$role,1);
                   3959:                                 (undef,my $group_privs) = split(/\//,$trole);
                   3960:                                 $group_privs = &unescape($group_privs);
                   3961:                             }
                   3962:                             if ($$role =~ /^cr\//) {
                   3963:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
                   3964:                             } elsif ($$role eq 'gr') {
                   3965:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   3966:                                                     $env{'user.name'});
                   3967:                                 my $trole = split('_',$rolehash{$$where.'_'.$$role},1);
                   3968:                                 (undef,my $group_privs) = split(/\//,$trole);
                   3969:                                 $group_privs = &unescape($group_privs);
                   3970:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
                   3971:                             } else {
                   3972:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   3973:                             }
                   3974:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3975:                             &appenv(\%userroles,[$$role,'cm']);
                   3976:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   3977:                             $$tstatus = 'is';
                   3978:                         }
                   3979:                     }
                   3980:                 }
1.994     raeburn  3981:             }
                   3982:             if ($$tend) {
                   3983:                 if ($$tend<$then) {
                   3984:                     $$tstatus='expired';
                   3985:                 } elsif ($$tend<$now) {
                   3986:                     $$tstatus='will_not';
                   3987:                 }
                   3988:             }
                   3989:         }
                   3990:     }
                   3991: }
                   3992: 
                   3993: sub check_adhoc_privs {
1.1002    raeburn  3994:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
1.994     raeburn  3995:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   3996:     if ($env{$cckey}) {
                   3997:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002    raeburn  3998:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  3999:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
                   4000:             &set_adhoc_privileges($cdom,$cnum,$checkrole);
                   4001:         }
                   4002:     } else {
                   4003:         &set_adhoc_privileges($cdom,$cnum,$checkrole);
                   4004:     }
                   4005: }
                   4006: 
                   4007: sub set_adhoc_privileges {
                   4008: # role can be cc or ca
                   4009:     my ($dcdom,$pickedcourse,$role) = @_;
                   4010:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4011:     my $spec = $role.'.'.$area;
                   4012:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4013:                                   $env{'user.name'});
                   4014:     my %ccrole = ();
                   4015:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4016:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4017:     &appenv(\%userroles,[$role,'cm']);
                   4018:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4019:     &appenv( {'request.role'        => $spec,
                   4020:               'request.role.domain' => $dcdom,
                   4021:               'request.course.sec'  => ''
                   4022:              }
                   4023:            );
                   4024:     my $tadv=0;
                   4025:     if (&allowed('adv') eq 'F') { $tadv=1; }
                   4026:     &appenv({'request.role.adv'    => $tadv});
                   4027: }
                   4028: 
1.12      www      4029: # --------------------------------------------------------------- get interface
                   4030: 
                   4031: sub get {
1.131     albertel 4032:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4033:    my $items='';
1.800     albertel 4034:    foreach my $item (@$storearr) {
                   4035:        $items.=&escape($item).'&';
1.191     harris41 4036:    }
1.12      www      4037:    $items=~s/\&$//;
1.620     albertel 4038:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4039:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4040:    my $uhome=&homeserver($uname,$udomain);
                   4041: 
1.133     albertel 4042:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4043:    my @pairs=split(/\&/,$rep);
1.273     albertel 4044:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4045:      return @pairs;
                   4046:    }
1.15      www      4047:    my %returnhash=();
1.42      www      4048:    my $i=0;
1.800     albertel 4049:    foreach my $item (@$storearr) {
                   4050:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4051:       $i++;
1.191     harris41 4052:    }
1.15      www      4053:    return %returnhash;
1.27      www      4054: }
                   4055: 
                   4056: # --------------------------------------------------------------- del interface
                   4057: 
                   4058: sub del {
1.133     albertel 4059:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4060:    my $items='';
1.800     albertel 4061:    foreach my $item (@$storearr) {
                   4062:        $items.=&escape($item).'&';
1.191     harris41 4063:    }
1.984     neumanie 4064: 
1.27      www      4065:    $items=~s/\&$//;
1.620     albertel 4066:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4067:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4068:    my $uhome=&homeserver($uname,$udomain);
                   4069:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4070: }
                   4071: 
                   4072: # -------------------------------------------------------------- dump interface
                   4073: 
                   4074: sub dump {
1.755     albertel 4075:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   4076:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4077:     if (!$uname) { $uname=$env{'user.name'}; }
                   4078:     my $uhome=&homeserver($uname,$udomain);
                   4079:     if ($regexp) {
                   4080: 	$regexp=&escape($regexp);
                   4081:     } else {
                   4082: 	$regexp='.';
                   4083:     }
                   4084:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4085:     my @pairs=split(/\&/,$rep);
                   4086:     my %returnhash=();
                   4087:     foreach my $item (@pairs) {
                   4088: 	my ($key,$value)=split(/=/,$item,2);
                   4089: 	$key = &unescape($key);
                   4090: 	next if ($key =~ /^error: 2 /);
                   4091: 	$returnhash{$key}=&thaw_unescape($value);
                   4092:     }
                   4093:     return %returnhash;
1.407     www      4094: }
                   4095: 
1.717     albertel 4096: # --------------------------------------------------------- dumpstore interface
                   4097: 
                   4098: sub dumpstore {
                   4099:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4100:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4101:    if (!$uname) { $uname=$env{'user.name'}; }
                   4102:    my $uhome=&homeserver($uname,$udomain);
                   4103:    if ($regexp) {
                   4104:        $regexp=&escape($regexp);
                   4105:    } else {
                   4106:        $regexp='.';
                   4107:    }
                   4108:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4109:    my @pairs=split(/\&/,$rep);
                   4110:    my %returnhash=();
                   4111:    foreach my $item (@pairs) {
                   4112:        my ($key,$value)=split(/=/,$item,2);
                   4113:        next if ($key =~ /^error: 2 /);
                   4114:        $returnhash{$key}=&thaw_unescape($value);
                   4115:    }
                   4116:    return %returnhash;
1.717     albertel 4117: }
                   4118: 
1.407     www      4119: # -------------------------------------------------------------- keys interface
                   4120: 
                   4121: sub getkeys {
                   4122:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4123:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4124:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4125:    my $uhome=&homeserver($uname,$udomain);
                   4126:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4127:    my @keyarray=();
1.800     albertel 4128:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4129:       next if ($key =~ /^error: 2 /);
1.800     albertel 4130:       push(@keyarray,&unescape($key));
1.407     www      4131:    }
                   4132:    return @keyarray;
1.318     matthew  4133: }
                   4134: 
1.319     matthew  4135: # --------------------------------------------------------------- currentdump
                   4136: sub currentdump {
1.328     matthew  4137:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4138:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4139:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4140:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4141:    my $uhome = &homeserver($sname,$sdom);
                   4142:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4143:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4144:    #
1.318     matthew  4145:    my %returnhash=();
1.319     matthew  4146:    #
                   4147:    if ($rep eq "unknown_cmd") { 
                   4148:        # an old lond will not know currentdump
                   4149:        # Do a dump and make it look like a currentdump
1.822     albertel 4150:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4151:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4152:        my %hash = @tmp;
                   4153:        @tmp=();
1.424     matthew  4154:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4155:    } else {
                   4156:        my @pairs=split(/\&/,$rep);
1.800     albertel 4157:        foreach my $pair (@pairs) {
                   4158:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4159:            my ($symb,$param) = split(/:/,$key);
                   4160:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4161:                                                         &thaw_unescape($value);
1.319     matthew  4162:        }
1.191     harris41 4163:    }
1.12      www      4164:    return %returnhash;
1.424     matthew  4165: }
                   4166: 
                   4167: sub convert_dump_to_currentdump{
                   4168:     my %hash = %{shift()};
                   4169:     my %returnhash;
                   4170:     # Code ripped from lond, essentially.  The only difference
                   4171:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4172:     # we might run in to problems with parameter names =~ /^v\./
                   4173:     while (my ($key,$value) = each(%hash)) {
                   4174:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4175: 	$symb  = &unescape($symb);
                   4176: 	$param = &unescape($param);
1.424     matthew  4177:         next if ($v eq 'version' || $symb eq 'keys');
                   4178:         next if (exists($returnhash{$symb}) &&
                   4179:                  exists($returnhash{$symb}->{$param}) &&
                   4180:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4181:         $returnhash{$symb}->{$param}=$value;
                   4182:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4183:     }
                   4184:     #
                   4185:     # Remove all of the keys in the hashes which keep track of
                   4186:     # the version of the parameter.
                   4187:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4188:         # use a foreach because we are going to delete from the hash.
                   4189:         foreach my $key (keys(%$param_hash)) {
                   4190:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4191:         }
                   4192:     }
                   4193:     return \%returnhash;
1.12      www      4194: }
                   4195: 
1.627     albertel 4196: # ------------------------------------------------------ critical inc interface
                   4197: 
                   4198: sub cinc {
                   4199:     return &inc(@_,'critical');
                   4200: }
                   4201: 
1.449     matthew  4202: # --------------------------------------------------------------- inc interface
                   4203: 
                   4204: sub inc {
1.627     albertel 4205:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4206:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4207:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4208:     my $uhome=&homeserver($uname,$udomain);
                   4209:     my $items='';
                   4210:     if (! ref($store)) {
                   4211:         # got a single value, so use that instead
                   4212:         $items = &escape($store).'=&';
                   4213:     } elsif (ref($store) eq 'SCALAR') {
                   4214:         $items = &escape($$store).'=&';        
                   4215:     } elsif (ref($store) eq 'ARRAY') {
                   4216:         $items = join('=&',map {&escape($_);} @{$store});
                   4217:     } elsif (ref($store) eq 'HASH') {
                   4218:         while (my($key,$value) = each(%{$store})) {
                   4219:             $items.= &escape($key).'='.&escape($value).'&';
                   4220:         }
                   4221:     }
                   4222:     $items=~s/\&$//;
1.627     albertel 4223:     if ($critical) {
                   4224: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4225:     } else {
                   4226: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4227:     }
1.449     matthew  4228: }
                   4229: 
1.12      www      4230: # --------------------------------------------------------------- put interface
                   4231: 
                   4232: sub put {
1.134     albertel 4233:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4234:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4235:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4236:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4237:    my $items='';
1.800     albertel 4238:    foreach my $item (keys(%$storehash)) {
                   4239:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4240:    }
1.12      www      4241:    $items=~s/\&$//;
1.134     albertel 4242:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4243: }
                   4244: 
1.631     albertel 4245: # ------------------------------------------------------------ newput interface
                   4246: 
                   4247: sub newput {
                   4248:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4249:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4250:    if (!$uname) { $uname=$env{'user.name'}; }
                   4251:    my $uhome=&homeserver($uname,$udomain);
                   4252:    my $items='';
                   4253:    foreach my $key (keys(%$storehash)) {
                   4254:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4255:    }
                   4256:    $items=~s/\&$//;
                   4257:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4258: }
                   4259: 
                   4260: # ---------------------------------------------------------  putstore interface
                   4261: 
1.524     raeburn  4262: sub putstore {
1.715     albertel 4263:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4264:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4265:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4266:    my $uhome=&homeserver($uname,$udomain);
                   4267:    my $items='';
1.715     albertel 4268:    foreach my $key (keys(%$storehash)) {
                   4269:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4270:    }
1.715     albertel 4271:    $items=~s/\&$//;
1.716     albertel 4272:    my $esc_symb=&escape($symb);
                   4273:    my $esc_v=&escape($version);
1.715     albertel 4274:    my $reply =
1.716     albertel 4275:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4276: 	      $uhome);
                   4277:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4278:        # gfall back to way things use to be done
1.715     albertel 4279:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4280: 			    $uname);
1.524     raeburn  4281:    }
1.715     albertel 4282:    return $reply;
                   4283: }
                   4284: 
                   4285: sub old_putstore {
1.716     albertel 4286:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4287:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4288:     if (!$uname) { $uname=$env{'user.name'}; }
                   4289:     my $uhome=&homeserver($uname,$udomain);
                   4290:     my %newstorehash;
1.800     albertel 4291:     foreach my $item (keys(%$storehash)) {
                   4292: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4293: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4294:     }
                   4295:     my $items='';
                   4296:     my %allitems = ();
1.800     albertel 4297:     foreach my $item (keys(%newstorehash)) {
                   4298: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4299: 	    my $key = $1.':keys:'.$2;
                   4300: 	    $allitems{$key} .= $3.':';
                   4301: 	}
1.800     albertel 4302: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4303:     }
1.800     albertel 4304:     foreach my $item (keys(%allitems)) {
                   4305: 	$allitems{$item} =~ s/\:$//;
                   4306: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4307:     }
                   4308:     $items=~s/\&$//;
                   4309:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4310: }
                   4311: 
1.47      www      4312: # ------------------------------------------------------ critical put interface
                   4313: 
                   4314: sub cput {
1.134     albertel 4315:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4316:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4317:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4318:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4319:    my $items='';
1.800     albertel 4320:    foreach my $item (keys(%$storehash)) {
                   4321:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4322:    }
1.47      www      4323:    $items=~s/\&$//;
1.134     albertel 4324:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4325: }
                   4326: 
                   4327: # -------------------------------------------------------------- eget interface
                   4328: 
                   4329: sub eget {
1.133     albertel 4330:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4331:    my $items='';
1.800     albertel 4332:    foreach my $item (@$storearr) {
                   4333:        $items.=&escape($item).'&';
1.191     harris41 4334:    }
1.12      www      4335:    $items=~s/\&$//;
1.620     albertel 4336:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4337:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4338:    my $uhome=&homeserver($uname,$udomain);
                   4339:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4340:    my @pairs=split(/\&/,$rep);
                   4341:    my %returnhash=();
1.42      www      4342:    my $i=0;
1.800     albertel 4343:    foreach my $item (@$storearr) {
                   4344:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4345:       $i++;
1.191     harris41 4346:    }
1.12      www      4347:    return %returnhash;
                   4348: }
                   4349: 
1.667     albertel 4350: # ------------------------------------------------------------ tmpput interface
                   4351: sub tmpput {
1.802     raeburn  4352:     my ($storehash,$server,$context)=@_;
1.667     albertel 4353:     my $items='';
1.800     albertel 4354:     foreach my $item (keys(%$storehash)) {
                   4355: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4356:     }
                   4357:     $items=~s/\&$//;
1.802     raeburn  4358:     if (defined($context)) {
                   4359:         $items .= ':'.&escape($context);
                   4360:     }
1.667     albertel 4361:     return &reply("tmpput:$items",$server);
                   4362: }
                   4363: 
                   4364: # ------------------------------------------------------------ tmpget interface
                   4365: sub tmpget {
1.688     albertel 4366:     my ($token,$server)=@_;
                   4367:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4368:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4369:     my %returnhash;
                   4370:     foreach my $item (split(/\&/,$rep)) {
                   4371: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4372:         next if ($key =~ /^error: 2 /);
1.667     albertel 4373: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4374:     }
                   4375:     return %returnhash;
                   4376: }
                   4377: 
1.688     albertel 4378: # ------------------------------------------------------------ tmpget interface
                   4379: sub tmpdel {
                   4380:     my ($token,$server)=@_;
                   4381:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4382:     return &reply("tmpdel:$token",$server);
                   4383: }
                   4384: 
1.765     albertel 4385: # -------------------------------------------------- portfolio access checking
                   4386: 
                   4387: sub portfolio_access {
1.766     albertel 4388:     my ($requrl) = @_;
1.765     albertel 4389:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4390:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4391:     if ($result) {
                   4392:         my %setters;
                   4393:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4394:             my ($startblock,$endblock) =
                   4395:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4396:             if ($startblock && $endblock) {
                   4397:                 return 'B';
                   4398:             }
                   4399:         } else {
                   4400:             my ($startblock,$endblock) =
                   4401:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4402:             if ($startblock && $endblock) {
                   4403:                 return 'B';
                   4404:             }
                   4405:         }
                   4406:     }
1.765     albertel 4407:     if ($result eq 'ok') {
1.766     albertel 4408:        return 'F';
1.765     albertel 4409:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4410:        return 'A';
1.765     albertel 4411:     }
1.766     albertel 4412:     return '';
1.765     albertel 4413: }
                   4414: 
                   4415: sub get_portfolio_access {
1.767     albertel 4416:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4417: 
                   4418:     if (!ref($access_hash)) {
                   4419: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4420: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4421: 						   $file_name);
                   4422: 	$access_hash = $access_controls{$file_name};
                   4423:     }
                   4424: 
1.765     albertel 4425:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4426:     my $now = time;
                   4427:     if (ref($access_hash) eq 'HASH') {
                   4428:         foreach my $key (keys(%{$access_hash})) {
                   4429:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4430:             if ($start > $now) {
                   4431:                 next;
                   4432:             }
                   4433:             if ($end && $end<$now) {
                   4434:                 next;
                   4435:             }
                   4436:             if ($scope eq 'public') {
                   4437:                 $public = $key;
                   4438:                 last;
                   4439:             } elsif ($scope eq 'guest') {
                   4440:                 $guest = $key;
                   4441:             } elsif ($scope eq 'domains') {
                   4442:                 push(@domains,$key);
                   4443:             } elsif ($scope eq 'users') {
                   4444:                 push(@users,$key);
                   4445:             } elsif ($scope eq 'course') {
                   4446:                 push(@courses,$key);
                   4447:             } elsif ($scope eq 'group') {
                   4448:                 push(@groups,$key);
                   4449:             }
                   4450:         }
                   4451:         if ($public) {
                   4452:             return 'ok';
                   4453:         }
                   4454:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4455:             if ($guest) {
                   4456:                 return $guest;
                   4457:             }
                   4458:         } else {
                   4459:             if (@domains > 0) {
                   4460:                 foreach my $domkey (@domains) {
                   4461:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4462:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4463:                             return 'ok';
                   4464:                         }
                   4465:                     }
                   4466:                 }
                   4467:             }
                   4468:             if (@users > 0) {
                   4469:                 foreach my $userkey (@users) {
1.865     raeburn  4470:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4471:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4472:                             if (ref($item) eq 'HASH') {
                   4473:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4474:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4475:                                     return 'ok';
                   4476:                                 }
                   4477:                             }
                   4478:                         }
                   4479:                     } 
1.765     albertel 4480:                 }
                   4481:             }
                   4482:             my %roleshash;
                   4483:             my @courses_and_groups = @courses;
                   4484:             push(@courses_and_groups,@groups); 
                   4485:             if (@courses_and_groups > 0) {
                   4486:                 my (%allgroups,%allroles); 
                   4487:                 my ($start,$end,$role,$sec,$group);
                   4488:                 foreach my $envkey (%env) {
1.811     albertel 4489:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4490:                         my $cid = $2.'_'.$3; 
                   4491:                         if ($1 eq 'gr') {
                   4492:                             $group = $4;
                   4493:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4494:                         } else {
                   4495:                             if ($4 eq '') {
                   4496:                                 $sec = 'none';
                   4497:                             } else {
                   4498:                                 $sec = $4;
                   4499:                             }
                   4500:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4501:                         }
1.811     albertel 4502:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4503:                         my $cid = $2.'_'.$3;
                   4504:                         if ($4 eq '') {
                   4505:                             $sec = 'none';
                   4506:                         } else {
                   4507:                             $sec = $4;
                   4508:                         }
                   4509:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4510:                     }
                   4511:                 }
                   4512:                 if (keys(%allroles) == 0) {
                   4513:                     return;
                   4514:                 }
                   4515:                 foreach my $key (@courses_and_groups) {
                   4516:                     my %content = %{$$access_hash{$key}};
                   4517:                     my $cnum = $content{'number'};
                   4518:                     my $cdom = $content{'domain'};
                   4519:                     my $cid = $cdom.'_'.$cnum;
                   4520:                     if (!exists($allroles{$cid})) {
                   4521:                         next;
                   4522:                     }    
                   4523:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4524:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4525:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4526:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4527:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4528:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4529:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4530:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4531:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4532:                                         if (grep/^all$/,@sections) {
                   4533:                                             return 'ok';
                   4534:                                         } else {
                   4535:                                             if (grep/^$sec$/,@sections) {
                   4536:                                                 return 'ok';
                   4537:                                             }
                   4538:                                         }
                   4539:                                     }
                   4540:                                 }
                   4541:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4542:                                     if (grep/^none$/,@groups) {
                   4543:                                         return 'ok';
                   4544:                                     }
                   4545:                                 } else {
                   4546:                                     if (grep/^all$/,@groups) {
                   4547:                                         return 'ok';
                   4548:                                     } 
                   4549:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4550:                                         if (grep/^$group$/,@groups) {
                   4551:                                             return 'ok';
                   4552:                                         }
                   4553:                                     }
                   4554:                                 } 
                   4555:                             }
                   4556:                         }
                   4557:                     }
                   4558:                 }
                   4559:             }
                   4560:             if ($guest) {
                   4561:                 return $guest;
                   4562:             }
                   4563:         }
                   4564:     }
                   4565:     return;
                   4566: }
                   4567: 
                   4568: sub course_group_datechecker {
                   4569:     my ($dates,$now,$status) = @_;
                   4570:     my ($start,$end) = split(/\./,$dates);
                   4571:     if (!$start && !$end) {
                   4572:         return 'ok';
                   4573:     }
                   4574:     if (grep/^active$/,@{$status}) {
                   4575:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4576:             return 'ok';
                   4577:         }
                   4578:     }
                   4579:     if (grep/^previous$/,@{$status}) {
                   4580:         if ($end > $now ) {
                   4581:             return 'ok';
                   4582:         }
                   4583:     }
                   4584:     if (grep/^future$/,@{$status}) {
                   4585:         if ($start > $now) {
                   4586:             return 'ok';
                   4587:         }
                   4588:     }
                   4589:     return; 
                   4590: }
                   4591: 
                   4592: sub parse_portfolio_url {
                   4593:     my ($url) = @_;
                   4594: 
                   4595:     my ($type,$udom,$unum,$group,$file_name);
                   4596:     
1.823     albertel 4597:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4598: 	$type = 1;
                   4599:         $udom = $1;
                   4600:         $unum = $2;
                   4601:         $file_name = $3;
1.823     albertel 4602:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4603: 	$type = 2;
                   4604:         $udom = $1;
                   4605:         $unum = $2;
                   4606:         $group = $3;
                   4607:         $file_name = $3.'/'.$4;
                   4608:     }
                   4609:     if (wantarray) {
                   4610: 	return ($type,$udom,$unum,$file_name,$group);
                   4611:     }
                   4612:     return $type;
                   4613: }
                   4614: 
                   4615: sub is_portfolio_url {
                   4616:     my ($url) = @_;
                   4617:     return scalar(&parse_portfolio_url($url));
                   4618: }
                   4619: 
1.798     raeburn  4620: sub is_portfolio_file {
                   4621:     my ($file) = @_;
1.820     raeburn  4622:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4623:         return 1;
                   4624:     }
                   4625:     return;
                   4626: }
                   4627: 
1.976     raeburn  4628: sub usertools_access {
1.985     raeburn  4629:     my ($uname,$udom,$tool,$action,$context) = @_;
                   4630:     my ($access,%tools);
                   4631:     if ($context eq '') {
                   4632:         $context = 'tools';
                   4633:     }
                   4634:     if ($context eq 'requestcourses') {
                   4635:         %tools = (
                   4636:                       official   => 1,
                   4637:                       unofficial => 1,
1.1006  ! raeburn  4638:                       community  => 1,
1.985     raeburn  4639:                  );
                   4640:     } else {
                   4641:         %tools = (
                   4642:                       aboutme   => 1,
                   4643:                       blog      => 1,
                   4644:                       portfolio => 1,
                   4645:                  );
                   4646:     }
1.976     raeburn  4647:     return if (!defined($tools{$tool}));
                   4648: 
                   4649:     if ((!defined($udom)) || (!defined($uname))) {
                   4650:         $udom = $env{'user.domain'};
                   4651:         $uname = $env{'user.name'};
                   4652:     }
                   4653: 
1.978     raeburn  4654:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4655:         if ($action ne 'reload') {
1.985     raeburn  4656:             if ($context eq 'requestcourses') {
                   4657:                 return $env{'environment.canrequest.'.$tool};
                   4658:             } else {
                   4659:                 return $env{'environment.availabletools.'.$tool};
                   4660:             }
                   4661:         }
1.976     raeburn  4662:     }
                   4663: 
                   4664:     my ($toolstatus,$inststatus);
                   4665: 
1.985     raeburn  4666:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   4667:          ($action ne 'reload')) {
                   4668:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  4669:         $inststatus = $env{'environment.inststatus'};
                   4670:     } else {
1.985     raeburn  4671:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool);
                   4672:         $toolstatus = $userenv{$context.'.'.$tool};
1.976     raeburn  4673:         $inststatus = $userenv{'inststatus'};
                   4674:     }
                   4675: 
                   4676:     if ($toolstatus ne '') {
                   4677:         if ($toolstatus) {
                   4678:             $access = 1;
                   4679:         } else {
                   4680:             $access = 0;
                   4681:         }
                   4682:         return $access;
                   4683:     }
                   4684: 
                   4685:     my $is_adv = &is_advanced_user($udom,$uname);
                   4686:     my %domdef = &get_domain_defaults($udom);
                   4687:     if (ref($domdef{$tool}) eq 'HASH') {
                   4688:         if ($is_adv) {
                   4689:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   4690:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   4691:                     $access = 1;
                   4692:                 } else {
                   4693:                     $access = 0;
                   4694:                 }
                   4695:                 return $access;
                   4696:             }
                   4697:         }
                   4698:         if ($inststatus ne '') {
                   4699:             my ($hasaccess,$hasnoaccess);
                   4700:             foreach my $affiliation (split(/:/,$inststatus)) {
                   4701:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   4702:                     if ($domdef{$tool}{$affiliation}) {
                   4703:                         $hasaccess = 1;
                   4704:                     } else {
                   4705:                         $hasnoaccess = 1;
                   4706:                     }
                   4707:                 }
                   4708:             }
                   4709:             if ($hasaccess || $hasnoaccess) {
                   4710:                 if ($hasaccess) {
                   4711:                     $access = 1;
                   4712:                 } elsif ($hasnoaccess) {
                   4713:                     $access = 0; 
                   4714:                 }
                   4715:                 return $access;
                   4716:             }
                   4717:         } else {
                   4718:             if ($domdef{$tool}{'default'} ne '') {
                   4719:                 if ($domdef{$tool}{'default'}) {
                   4720:                     $access = 1;
                   4721:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   4722:                     $access = 0;
                   4723:                 }
                   4724:                 return $access;
                   4725:             }
                   4726:         }
                   4727:     } else {
1.985     raeburn  4728:         if ($context eq 'tools') {
                   4729:             $access = 1;
                   4730:         } else {
                   4731:             $access = 0;
                   4732:         }
1.976     raeburn  4733:         return $access;
                   4734:     }
                   4735: }
                   4736: 
                   4737: sub is_advanced_user {
                   4738:     my ($udom,$uname) = @_;
                   4739:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   4740:     my %allroles;
                   4741:     my $is_adv;
                   4742:     foreach my $role (keys(%roleshash)) {
                   4743:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   4744:         my $area = '/'.$tdomain.'/'.$trest;
                   4745:         if ($sec ne '') {
                   4746:             $area .= '/'.$sec;
                   4747:         }
                   4748:         if (($area ne '') && ($trole ne '')) {
                   4749:             my $spec=$trole.'.'.$area;
                   4750:             if ($trole =~ /^cr\//) {
                   4751:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4752:             } elsif ($trole ne 'gr') {
                   4753:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4754:             }
                   4755:         }
                   4756:     }
                   4757:     foreach my $role (keys(%allroles)) {
                   4758:         last if ($is_adv);
                   4759:         foreach my $item (split(/:/,$allroles{$role})) {
                   4760:             if ($item ne '') {
                   4761:                 my ($privilege,$restrictions)=split(/&/,$item);
                   4762:                 if ($privilege eq 'adv') {
                   4763:                     $is_adv = 1;
                   4764:                     last;
                   4765:                 }
                   4766:             }
                   4767:         }
                   4768:     }
                   4769:     return $is_adv;
                   4770: }
1.798     raeburn  4771: 
1.341     www      4772: # ---------------------------------------------- Custom access rule evaluation
                   4773: 
                   4774: sub customaccess {
                   4775:     my ($priv,$uri)=@_;
1.807     albertel 4776:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4777:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4778:     $udom = &LONCAPA::clean_domain($udom);
                   4779:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4780:     my $access=0;
1.800     albertel 4781:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4782: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4783: 	if ($type eq 'user') {
                   4784: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4785: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4786: 		if ($tdom) {
                   4787: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4788: 		}
1.896     albertel 4789: 		if ($tuname) {
                   4790: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4791: 		}
                   4792: 		$access=($effect eq 'allow');
                   4793: 		last;
                   4794: 	    }
                   4795: 	} else {
                   4796: 	    if ($role) {
                   4797: 		if ($role ne $urole) { next; }
                   4798: 	    }
                   4799: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4800: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4801: 		if ($tdom) {
                   4802: 		    if ($tdom ne $udom) { next; }
                   4803: 		}
                   4804: 		if ($tcrs) {
                   4805: 		    if ($tcrs ne $ucrs) { next; }
                   4806: 		}
                   4807: 		if ($tsec) {
                   4808: 		    if ($tsec ne $usec) { next; }
                   4809: 		}
                   4810: 		$access=($effect eq 'allow');
                   4811: 		last;
                   4812: 	    }
                   4813: 	    if ($realm eq '' && $role eq '') {
                   4814: 		$access=($effect eq 'allow');
                   4815: 	    }
1.402     bowersj2 4816: 	}
1.341     www      4817:     }
                   4818:     return $access;
                   4819: }
                   4820: 
1.103     harris41 4821: # ------------------------------------------------- Check for a user privilege
1.12      www      4822: 
                   4823: sub allowed {
1.810     raeburn  4824:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4825:     my $ver_orguri=$uri;
1.439     www      4826:     $uri=&deversion($uri);
1.152     www      4827:     my $orguri=$uri;
1.52      www      4828:     $uri=&declutter($uri);
1.809     raeburn  4829: 
1.810     raeburn  4830:     if ($priv eq 'evb') {
                   4831: # Evade communication block restrictions for specified role in a course
                   4832:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4833:             return $1;
                   4834:         } else {
                   4835:             return;
                   4836:         }
                   4837:     }
                   4838: 
1.620     albertel 4839:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4840: # Free bre access to adm and meta resources
1.775     albertel 4841:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4842: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4843: 	&& ($priv eq 'bre')) {
1.14      www      4844: 	return 'F';
1.159     www      4845:     }
                   4846: 
1.545     banghart 4847: # Free bre access to user's own portfolio contents
1.714     raeburn  4848:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4849:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4850: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4851:         my %setters;
                   4852:         my ($startblock,$endblock) = 
                   4853:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4854:         if ($startblock && $endblock) {
                   4855:             return 'B';
                   4856:         } else {
                   4857:             return 'F';
                   4858:         }
1.545     banghart 4859:     }
                   4860: 
1.762     raeburn  4861: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4862:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4863:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4864:         if (exists($env{'request.course.id'})) {
                   4865:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4866:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4867:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4868:                 my $courseprivid=$env{'request.course.id'};
                   4869:                 $courseprivid=~s/\_/\//;
                   4870:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4871:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4872:                     return $1; 
1.762     raeburn  4873:                 } else {
                   4874:                     if ($env{'request.course.sec'}) {
                   4875:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4876:                     }
                   4877:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4878:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4879:                         return $2;
                   4880:                     }
1.714     raeburn  4881:                 }
                   4882:             }
                   4883:         }
                   4884:     }
                   4885: 
1.159     www      4886: # Free bre to public access
                   4887: 
                   4888:     if ($priv eq 'bre') {
1.238     www      4889:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4890: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4891:            return 'F'; 
                   4892:         }
1.238     www      4893:         if ($copyright eq 'priv') {
                   4894:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4895: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4896: 		return '';
                   4897:             }
                   4898:         }
                   4899:         if ($copyright eq 'domain') {
                   4900:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4901: 	    unless (($env{'user.domain'} eq $1) ||
                   4902:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4903: 		return '';
                   4904:             }
1.262     matthew  4905:         }
1.620     albertel 4906:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4907:             # Library role, so allow browsing of resources in this domain.
                   4908:             return 'F';
1.238     www      4909:         }
1.341     www      4910:         if ($copyright eq 'custom') {
                   4911: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4912:         }
1.14      www      4913:     }
1.264     matthew  4914:     # Domain coordinator is trying to create a course
1.620     albertel 4915:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4916:         # uri is the requested domain in this case.
                   4917:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4918:         # a role of dc for the domain in question.
1.620     albertel 4919:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4920:     }
1.29      www      4921: 
1.52      www      4922:     my $thisallowed='';
                   4923:     my $statecond=0;
                   4924:     my $courseprivid='';
                   4925: 
                   4926: # Course
                   4927: 
1.620     albertel 4928:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4929:        $thisallowed.=$1;
                   4930:     }
1.29      www      4931: 
1.52      www      4932: # Domain
                   4933: 
1.620     albertel 4934:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4935:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4936:        $thisallowed.=$1;
                   4937:     }
1.52      www      4938: 
                   4939: # Course: uri itself is a course
1.66      www      4940:     my $courseuri=$uri;
                   4941:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4942:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4943: 
1.620     albertel 4944:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4945:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4946:        $thisallowed.=$1;
                   4947:     }
1.29      www      4948: 
1.665     albertel 4949: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4950: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4951:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4952: 	$thisallowed='';
1.671     raeburn  4953:         my ($match)=&is_on_map($uri);
                   4954:         if ($match) {
                   4955:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4956:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4957:                 $thisallowed.=$1;
                   4958:             }
                   4959:         } else {
1.705     albertel 4960:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4961:             if ($refuri) {
                   4962:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4963:                     $thisallowed='F';
1.671     raeburn  4964:                 } else {
                   4965:                     $refuri=&declutter($refuri);
                   4966:                     my ($match) = &is_on_map($refuri);
                   4967:                     if ($match) {
                   4968:                         $thisallowed='F';
                   4969:                     }
1.669     raeburn  4970:                 }
1.671     raeburn  4971:             }
                   4972:         }
1.314     www      4973:     }
1.492     albertel 4974: 
1.766     albertel 4975:     if ($priv eq 'bre'
                   4976: 	&& $thisallowed ne 'F' 
                   4977: 	&& $thisallowed ne '2'
                   4978: 	&& &is_portfolio_url($uri)) {
                   4979: 	$thisallowed = &portfolio_access($uri);
                   4980:     }
                   4981:     
1.52      www      4982: # Full access at system, domain or course-wide level? Exit.
1.29      www      4983:     if ($thisallowed=~/F/) {
                   4984: 	return 'F';
                   4985:     }
                   4986: 
1.52      www      4987: # If this is generating or modifying users, exit with special codes
1.29      www      4988: 
1.643     www      4989:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4990: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4991: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4992: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4993: 	    unless ($auname) { return $thisallowed; }
                   4994: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4995: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4996: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4997: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4998: 	}
1.52      www      4999: 	return $thisallowed;
                   5000:     }
                   5001: #
1.103     harris41 5002: # Gathered so far: system, domain and course wide privileges
1.52      www      5003: #
                   5004: # Course: See if uri or referer is an individual resource that is part of 
                   5005: # the course
                   5006: 
1.620     albertel 5007:     if ($env{'request.course.id'}) {
1.232     www      5008: 
1.620     albertel 5009:        $courseprivid=$env{'request.course.id'};
                   5010:        if ($env{'request.course.sec'}) {
                   5011:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5012:        }
                   5013:        $courseprivid=~s/\_/\//;
                   5014:        my $checkreferer=1;
1.232     www      5015:        my ($match,$cond)=&is_on_map($uri);
                   5016:        if ($match) {
                   5017:            $statecond=$cond;
1.620     albertel 5018:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5019:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5020:                $thisallowed.=$1;
                   5021:                $checkreferer=0;
                   5022:            }
1.29      www      5023:        }
1.83      www      5024:        
1.148     www      5025:        if ($checkreferer) {
1.620     albertel 5026: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5027:             unless ($refuri) {
1.800     albertel 5028:                 foreach my $key (keys(%env)) {
                   5029: 		    if ($key=~/^httpref\..*\*/) {
                   5030: 			my $pattern=$key;
1.156     www      5031:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5032:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5033:                         $pattern=~s/\//\\\//g;
1.152     www      5034:                         if ($orguri=~/$pattern/) {
1.800     albertel 5035: 			    $refuri=$env{$key};
1.148     www      5036:                         }
                   5037:                     }
1.191     harris41 5038:                 }
1.148     www      5039:             }
1.232     www      5040: 
1.148     www      5041:          if ($refuri) { 
1.152     www      5042: 	  $refuri=&declutter($refuri);
1.232     www      5043:           my ($match,$cond)=&is_on_map($refuri);
                   5044:             if ($match) {
                   5045:               my $refstatecond=$cond;
1.620     albertel 5046:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5047:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5048:                   $thisallowed.=$1;
1.53      www      5049:                   $uri=$refuri;
                   5050:                   $statecond=$refstatecond;
1.52      www      5051:               }
                   5052:           }
1.148     www      5053:         }
1.29      www      5054:        }
1.52      www      5055:    }
1.29      www      5056: 
1.52      www      5057: #
1.103     harris41 5058: # Gathered now: all privileges that could apply, and condition number
1.52      www      5059: # 
                   5060: #
                   5061: # Full or no access?
                   5062: #
1.29      www      5063: 
1.52      www      5064:     if ($thisallowed=~/F/) {
                   5065: 	return 'F';
                   5066:     }
1.29      www      5067: 
1.52      www      5068:     unless ($thisallowed) {
                   5069:         return '';
                   5070:     }
1.29      www      5071: 
1.52      www      5072: # Restrictions exist, deal with them
                   5073: #
                   5074: #   C:according to course preferences
                   5075: #   R:according to resource settings
                   5076: #   L:unless locked
                   5077: #   X:according to user session state
                   5078: #
                   5079: 
                   5080: # Possibly locked functionality, check all courses
1.54      www      5081: # Locks might take effect only after 10 minutes cache expiration for other
                   5082: # courses, and 2 minutes for current course
1.52      www      5083: 
                   5084:     my $envkey;
                   5085:     if ($thisallowed=~/L/) {
1.1000    raeburn  5086:         foreach $envkey (keys(%env)) {
1.54      www      5087:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5088:                my $courseid=$2;
                   5089:                my $roleid=$1.'.'.$2;
1.92      www      5090:                $courseid=~s/^\///;
1.54      www      5091:                my $expiretime=600;
1.620     albertel 5092:                if ($env{'request.role'} eq $roleid) {
1.54      www      5093: 		  $expiretime=120;
                   5094:                }
                   5095: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5096:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5097:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5098: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5099:                }
1.620     albertel 5100:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5101:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5102: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5103:                        &log($env{'user.domain'},$env{'user.name'},
                   5104:                             $env{'user.home'},
1.57      www      5105:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5106:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5107:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5108: 		       return '';
                   5109:                    }
                   5110:                }
1.620     albertel 5111:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5112:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5113: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5114:                        &log($env{'user.domain'},$env{'user.name'},
                   5115:                             $env{'user.home'},
1.57      www      5116:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5117:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5118:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5119: 		       return '';
                   5120:                    }
                   5121:                }
                   5122: 	   }
1.29      www      5123:        }
1.52      www      5124:     }
                   5125:    
                   5126: #
                   5127: # Rest of the restrictions depend on selected course
                   5128: #
                   5129: 
1.620     albertel 5130:     unless ($env{'request.course.id'}) {
1.766     albertel 5131: 	if ($thisallowed eq 'A') {
                   5132: 	    return 'A';
1.814     raeburn  5133:         } elsif ($thisallowed eq 'B') {
                   5134:             return 'B';
1.766     albertel 5135: 	} else {
                   5136: 	    return '1';
                   5137: 	}
1.52      www      5138:     }
1.29      www      5139: 
1.52      www      5140: #
                   5141: # Now user is definitely in a course
                   5142: #
1.53      www      5143: 
                   5144: 
                   5145: # Course preferences
                   5146: 
                   5147:    if ($thisallowed=~/C/) {
1.620     albertel 5148:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5149:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5150:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5151: 	   =~/\Q$rolecode\E/) {
1.689     albertel 5152: 	   if ($priv ne 'pch') { 
                   5153: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5154: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5155: 			$env{'request.course.id'});
                   5156: 	   }
1.237     www      5157:            return '';
                   5158:        }
                   5159: 
1.620     albertel 5160:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5161: 	   =~/\Q$unamedom\E/) {
1.689     albertel 5162: 	   if ($priv ne 'pch') { 
                   5163: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5164: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5165: 			$env{'request.course.id'});
                   5166: 	   }
1.54      www      5167:            return '';
                   5168:        }
1.53      www      5169:    }
                   5170: 
                   5171: # Resource preferences
                   5172: 
                   5173:    if ($thisallowed=~/R/) {
1.620     albertel 5174:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5175:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 5176: 	   if ($priv ne 'pch') { 
                   5177: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5178: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5179: 	   }
                   5180: 	   return '';
1.54      www      5181:        }
1.53      www      5182:    }
1.30      www      5183: 
1.246     www      5184: # Restricted by state or randomout?
1.30      www      5185: 
1.52      www      5186:    if ($thisallowed=~/X/) {
1.620     albertel 5187:       if ($env{'acc.randomout'}) {
1.579     albertel 5188: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5189:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5190:             return ''; 
                   5191:          }
1.247     www      5192:       }
                   5193:       if (&condval($statecond)) {
1.52      www      5194: 	 return '2';
                   5195:       } else {
                   5196:          return '';
                   5197:       }
                   5198:    }
1.30      www      5199: 
1.766     albertel 5200:     if ($thisallowed eq 'A') {
                   5201: 	return 'A';
1.814     raeburn  5202:     } elsif ($thisallowed eq 'B') {
                   5203:         return 'B';
1.766     albertel 5204:     }
1.52      www      5205:    return 'F';
1.232     www      5206: }
                   5207: 
1.710     albertel 5208: sub split_uri_for_cond {
                   5209:     my $uri=&deversion(&declutter(shift));
                   5210:     my @uriparts=split(/\//,$uri);
                   5211:     my $filename=pop(@uriparts);
                   5212:     my $pathname=join('/',@uriparts);
                   5213:     return ($pathname,$filename);
                   5214: }
1.232     www      5215: # --------------------------------------------------- Is a resource on the map?
                   5216: 
                   5217: sub is_on_map {
1.710     albertel 5218:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5219:     #Trying to find the conditional for the file
1.620     albertel 5220:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5221: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5222:     if ($match) {
1.289     bowersj2 5223: 	return (1,$1);
                   5224:     } else {
1.434     www      5225: 	return (0,0);
1.289     bowersj2 5226:     }
1.12      www      5227: }
                   5228: 
1.427     www      5229: # --------------------------------------------------------- Get symb from alias
                   5230: 
                   5231: sub get_symb_from_alias {
                   5232:     my $symb=shift;
                   5233:     my ($map,$resid,$url)=&decode_symb($symb);
                   5234: # Already is a symb
                   5235:     if ($url) { return $symb; }
                   5236: # Must be an alias
                   5237:     my $aliassymb='';
                   5238:     my %bighash;
1.620     albertel 5239:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5240:                             &GDBM_READER(),0640)) {
                   5241:         my $rid=$bighash{'mapalias_'.$symb};
                   5242: 	if ($rid) {
                   5243: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5244: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5245: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5246: 	}
                   5247:         untie %bighash;
                   5248:     }
                   5249:     return $aliassymb;
                   5250: }
                   5251: 
1.12      www      5252: # ----------------------------------------------------------------- Define Role
                   5253: 
                   5254: sub definerole {
                   5255:   if (allowed('mcr','/')) {
                   5256:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5257:     foreach my $role (split(':',$sysrole)) {
                   5258: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5259:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5260:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5261: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5262:                return "refused:s:$crole&$cqual"; 
                   5263:             }
                   5264:         }
1.191     harris41 5265:     }
1.800     albertel 5266:     foreach my $role (split(':',$domrole)) {
                   5267: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5268:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5269:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5270: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5271:                return "refused:d:$crole&$cqual"; 
                   5272:             }
                   5273:         }
1.191     harris41 5274:     }
1.800     albertel 5275:     foreach my $role (split(':',$courole)) {
                   5276: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5277:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5278:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5279: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5280:                return "refused:c:$crole&$cqual"; 
                   5281:             }
                   5282:         }
1.191     harris41 5283:     }
1.620     albertel 5284:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5285:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5286: 	        "rolesdef_$rolename=".
                   5287:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5288:     return reply($command,$env{'user.home'});
1.12      www      5289:   } else {
                   5290:     return 'refused';
                   5291:   }
1.105     harris41 5292: }
                   5293: 
                   5294: # ---------------- Make a metadata query against the network of library servers
                   5295: 
                   5296: sub metadata_query {
1.244     matthew  5297:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5298:     my %rhash;
1.845     albertel 5299:     my %libserv = &all_library();
1.244     matthew  5300:     my @server_list = (defined($server_array) ? @$server_array
                   5301:                                               : keys(%libserv) );
                   5302:     for my $server (@server_list) {
1.118     harris41 5303: 	unless ($custom or $customshow) {
                   5304: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5305: 	    $rhash{$server}=$reply;
                   5306: 	}
                   5307: 	else {
                   5308: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5309: 			     &escape($custom).':'.&escape($customshow),
                   5310: 			     $server);
                   5311: 	    $rhash{$server}=$reply;
                   5312: 	}
1.112     harris41 5313:     }
1.118     harris41 5314:     return \%rhash;
1.240     www      5315: }
                   5316: 
                   5317: # ----------------------------------------- Send log queries and wait for reply
                   5318: 
                   5319: sub log_query {
                   5320:     my ($uname,$udom,$query,%filters)=@_;
                   5321:     my $uhome=&homeserver($uname,$udom);
                   5322:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5323:     my $uhost=&hostname($uhome);
1.800     albertel 5324:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5325:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5326:                        $uhome);
1.479     albertel 5327:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5328:     return get_query_reply($queryid);
                   5329: }
                   5330: 
1.818     raeburn  5331: # -------------------------- Update MySQL table for portfolio file
                   5332: 
                   5333: sub update_portfolio_table {
1.821     raeburn  5334:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5335:     if ($group ne '') {
                   5336:         $file_name =~s /^\Q$group\E//;
                   5337:     }
1.818     raeburn  5338:     my $homeserver = &homeserver($uname,$udom);
                   5339:     my $queryid=
1.821     raeburn  5340:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5341:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5342:     my $reply = &get_query_reply($queryid);
                   5343:     return $reply;
                   5344: }
                   5345: 
1.899     raeburn  5346: # -------------------------- Update MySQL allusers table
                   5347: 
                   5348: sub update_allusers_table {
                   5349:     my ($uname,$udom,$names) = @_;
                   5350:     my $homeserver = &homeserver($uname,$udom);
                   5351:     my $queryid=
                   5352:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5353:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5354:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5355:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5356:                'generation='.&escape($names->{'generation'}).'%%'.
                   5357:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5358:                'id='.&escape($names->{'id'}),$homeserver);
                   5359:     my $reply = &get_query_reply($queryid);
                   5360:     return $reply;
                   5361: }
                   5362: 
1.508     raeburn  5363: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5364: 
                   5365: sub fetch_enrollment_query {
1.511     raeburn  5366:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5367:     my $homeserver;
1.547     raeburn  5368:     my $maxtries = 1;
1.508     raeburn  5369:     if ($context eq 'automated') {
                   5370:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5371:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5372:     } else {
                   5373:         $homeserver = &homeserver($cnum,$dom);
                   5374:     }
1.838     albertel 5375:     my $host=&hostname($homeserver);
1.506     raeburn  5376:     my $cmd = '';
1.1000    raeburn  5377:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 5378:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5379:     }
                   5380:     $cmd =~ s/%%$//;
                   5381:     $cmd = &escape($cmd);
                   5382:     my $query = 'fetchenrollment';
1.620     albertel 5383:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5384:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5385:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5386:         return 'error: '.$queryid;
                   5387:     }
1.506     raeburn  5388:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5389:     my $tries = 1;
                   5390:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5391:         $reply = &get_query_reply($queryid);
                   5392:         $tries ++;
                   5393:     }
1.526     raeburn  5394:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5395:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5396:     } else {
1.901     albertel 5397:         my @responses = split(/:/,$reply);
1.515     raeburn  5398:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5399:             foreach my $line (@responses) {
                   5400:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5401:                 $$replyref{$key} = $value;
                   5402:             }
                   5403:         } else {
1.506     raeburn  5404:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5405:             foreach my $line (@responses) {
                   5406:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5407:                 $$replyref{$key} = $value;
                   5408:                 if ($value > 0) {
1.800     albertel 5409:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5410:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5411:                         my $destname = $pathname.'/'.$filename;
                   5412:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5413:                         if ($xml_classlist =~ /^error/) {
                   5414:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5415:                         } else {
1.506     raeburn  5416:                             if ( open(FILE,">$destname") ) {
                   5417:                                 print FILE &unescape($xml_classlist);
                   5418:                                 close(FILE);
1.526     raeburn  5419:                             } else {
                   5420:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5421:                             }
                   5422:                         }
                   5423:                     }
                   5424:                 }
                   5425:             }
                   5426:         }
                   5427:         return 'ok';
                   5428:     }
                   5429:     return 'error';
                   5430: }
                   5431: 
1.242     www      5432: sub get_query_reply {
                   5433:     my $queryid=shift;
1.240     www      5434:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5435:     my $reply='';
                   5436:     for (1..100) {
                   5437: 	sleep 2;
                   5438:         if (-e $replyfile.'.end') {
1.448     albertel 5439: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5440: 		$reply = join('',<$fh>);
                   5441: 		close($fh);
1.240     www      5442: 	   } else { return 'error: reply_file_error'; }
1.242     www      5443:            return &unescape($reply);
                   5444: 	}
1.240     www      5445:     }
1.242     www      5446:     return 'timeout:'.$queryid;
1.240     www      5447: }
                   5448: 
                   5449: sub courselog_query {
1.241     www      5450: #
                   5451: # possible filters:
                   5452: # url: url or symb
                   5453: # username
                   5454: # domain
                   5455: # action: view, submit, grade
                   5456: # start: timestamp
                   5457: # end: timestamp
                   5458: #
1.240     www      5459:     my (%filters)=@_;
1.620     albertel 5460:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5461:     if ($filters{'url'}) {
                   5462: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5463:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5464:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5465:     }
1.620     albertel 5466:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5467:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5468:     return &log_query($cname,$cdom,'courselog',%filters);
                   5469: }
                   5470: 
                   5471: sub userlog_query {
1.858     raeburn  5472: #
                   5473: # possible filters:
                   5474: # action: log check role
                   5475: # start: timestamp
                   5476: # end: timestamp
                   5477: #
1.240     www      5478:     my ($uname,$udom,%filters)=@_;
                   5479:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5480: }
                   5481: 
1.506     raeburn  5482: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5483: 
                   5484: sub auto_run {
1.508     raeburn  5485:     my ($cnum,$cdom) = @_;
1.876     raeburn  5486:     my $response = 0;
                   5487:     my $settings;
                   5488:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5489:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5490:         $settings = $domconfig{'autoenroll'};
                   5491:         if ($settings->{'run'} eq '1') {
                   5492:             $response = 1;
                   5493:         }
                   5494:     } else {
1.934     raeburn  5495:         my $homeserver;
                   5496:         if (&is_course($cdom,$cnum)) {
                   5497:             $homeserver = &homeserver($cnum,$cdom);
                   5498:         } else {
                   5499:             $homeserver = &domain($cdom,'primary');
                   5500:         }
                   5501:         if ($homeserver ne 'no_host') {
                   5502:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5503:         }
1.876     raeburn  5504:     }
1.506     raeburn  5505:     return $response;
                   5506: }
1.776     albertel 5507: 
1.506     raeburn  5508: sub auto_get_sections {
1.508     raeburn  5509:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   5510:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  5511:     my @secs = ();
1.511     raeburn  5512:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  5513:     unless ($response eq 'refused') {
1.901     albertel 5514:         @secs = split(/:/,$response);
1.506     raeburn  5515:     }
                   5516:     return @secs;
                   5517: }
1.776     albertel 5518: 
1.506     raeburn  5519: sub auto_new_course {
1.508     raeburn  5520:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5521:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5522:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5523:     return $response;
                   5524: }
1.776     albertel 5525: 
1.506     raeburn  5526: sub auto_validate_courseID {
1.508     raeburn  5527:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5528:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5529:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5530:     return $response;
                   5531: }
1.776     albertel 5532: 
1.506     raeburn  5533: sub auto_create_password {
1.873     raeburn  5534:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5535:     my ($homeserver,$response);
1.506     raeburn  5536:     my $create_passwd = 0;
                   5537:     my $authchk = '';
1.873     raeburn  5538:     if ($udom =~ /^$match_domain$/) {
                   5539:         $homeserver = &domain($udom,'primary');
                   5540:     }
                   5541:     if ($homeserver eq '') {
                   5542:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5543:             $homeserver = &homeserver($cnum,$cdom);
                   5544:         }
                   5545:     }
                   5546:     if ($homeserver eq '') {
                   5547:         $authchk = 'nodomain';
1.506     raeburn  5548:     } else {
1.873     raeburn  5549:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5550:         if ($response eq 'refused') {
                   5551:             $authchk = 'refused';
                   5552:         } else {
1.901     albertel 5553:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5554:         }
1.506     raeburn  5555:     }
                   5556:     return ($authparam,$create_passwd,$authchk);
                   5557: }
                   5558: 
1.706     raeburn  5559: sub auto_photo_permission {
                   5560:     my ($cnum,$cdom,$students) = @_;
                   5561:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5562:     my ($outcome,$perm_reqd,$conditions) = 
                   5563: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5564:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5565: 	return (undef,undef);
                   5566:     }
1.706     raeburn  5567:     return ($outcome,$perm_reqd,$conditions);
                   5568: }
                   5569: 
                   5570: sub auto_checkphotos {
                   5571:     my ($uname,$udom,$pid) = @_;
                   5572:     my $homeserver = &homeserver($uname,$udom);
                   5573:     my ($result,$resulttype);
                   5574:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5575: 				   &escape($uname).':'.&escape($pid),
                   5576: 				   $homeserver));
1.709     albertel 5577:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5578: 	return (undef,undef);
                   5579:     }
1.706     raeburn  5580:     if ($outcome) {
                   5581:         ($result,$resulttype) = split(/:/,$outcome);
                   5582:     } 
                   5583:     return ($result,$resulttype);
                   5584: }
                   5585: 
                   5586: sub auto_photochoice {
                   5587:     my ($cnum,$cdom) = @_;
                   5588:     my $homeserver = &homeserver($cnum,$cdom);
                   5589:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5590: 						       &escape($cdom),
                   5591: 						       $homeserver)));
1.709     albertel 5592:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5593: 	return (undef,undef);
                   5594:     }
1.706     raeburn  5595:     return ($update,$comment);
                   5596: }
                   5597: 
                   5598: sub auto_photoupdate {
                   5599:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5600:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5601:     my $host=&hostname($homeserver);
1.706     raeburn  5602:     my $cmd = '';
                   5603:     my $maxtries = 1;
1.800     albertel 5604:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5605:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5606:     }
                   5607:     $cmd =~ s/%%$//;
                   5608:     $cmd = &escape($cmd);
                   5609:     my $query = 'institutionalphotos';
                   5610:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5611:     unless ($queryid=~/^\Q$host\E\_/) {
                   5612:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5613:         return 'error: '.$queryid;
                   5614:     }
                   5615:     my $reply = &get_query_reply($queryid);
                   5616:     my $tries = 1;
                   5617:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5618:         $reply = &get_query_reply($queryid);
                   5619:         $tries ++;
                   5620:     }
                   5621:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5622:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5623:     } else {
                   5624:         my @responses = split(/:/,$reply);
                   5625:         my $outcome = shift(@responses); 
                   5626:         foreach my $item (@responses) {
                   5627:             my ($key,$value) = split(/=/,$item);
                   5628:             $$photo{$key} = $value;
                   5629:         }
                   5630:         return $outcome;
                   5631:     }
                   5632:     return 'error';
                   5633: }
                   5634: 
1.521     raeburn  5635: sub auto_instcode_format {
1.793     albertel 5636:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5637: 	$cat_order) = @_;
1.521     raeburn  5638:     my $courses = '';
1.772     raeburn  5639:     my @homeservers;
1.521     raeburn  5640:     if ($caller eq 'global') {
1.841     albertel 5641: 	my %servers = &get_servers($codedom,'library');
                   5642: 	foreach my $tryserver (keys(%servers)) {
                   5643: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5644: 		push(@homeservers,$tryserver);
                   5645: 	    }
1.584     raeburn  5646:         }
1.521     raeburn  5647:     } else {
1.772     raeburn  5648:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5649:     }
1.793     albertel 5650:     foreach my $code (keys(%{$instcodes})) {
                   5651:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5652:     }
                   5653:     chop($courses);
1.772     raeburn  5654:     my $ok_response = 0;
                   5655:     my $response;
                   5656:     while (@homeservers > 0 && $ok_response == 0) {
                   5657:         my $server = shift(@homeservers); 
                   5658:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5659:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5660:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5661: 		split(/:/,$response);
1.772     raeburn  5662:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5663:             push(@{$codetitles},&str2array($codetitles_str));
                   5664:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5665:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5666:             $ok_response = 1;
                   5667:         }
                   5668:     }
                   5669:     if ($ok_response) {
1.521     raeburn  5670:         return 'ok';
1.772     raeburn  5671:     } else {
                   5672:         return $response;
1.521     raeburn  5673:     }
                   5674: }
                   5675: 
1.792     raeburn  5676: sub auto_instcode_defaults {
                   5677:     my ($domain,$returnhash,$code_order) = @_;
                   5678:     my @homeservers;
1.841     albertel 5679: 
                   5680:     my %servers = &get_servers($domain,'library');
                   5681:     foreach my $tryserver (keys(%servers)) {
                   5682: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5683: 	    push(@homeservers,$tryserver);
                   5684: 	}
1.792     raeburn  5685:     }
1.841     albertel 5686: 
1.792     raeburn  5687:     my $response;
1.841     albertel 5688:     foreach my $server (@homeservers) {
1.792     raeburn  5689:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5690:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5691: 	
                   5692: 	foreach my $pair (split(/\&/,$response)) {
                   5693: 	    my ($name,$value)=split(/\=/,$pair);
                   5694: 	    if ($name eq 'code_order') {
                   5695: 		@{$code_order} = split(/\&/,&unescape($value));
                   5696: 	    } else {
                   5697: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5698: 	    }
                   5699: 	}
                   5700: 	return 'ok';
1.792     raeburn  5701:     }
1.841     albertel 5702: 
                   5703:     return $response;
1.1003    raeburn  5704: }
                   5705: 
                   5706: sub auto_possible_instcodes {
1.1005    raeburn  5707:     my ($domain,$codetitles,$cat_titles,$cat_orders) = @_;
1.1003    raeburn  5708:     my (@homeservers,$uhome);
                   5709:     if (defined(&domain($domain,'primary'))) {
                   5710:         $uhome=&domain($domain,'primary');
                   5711:         push(@homeservers,&domain($domain,'primary'));
                   5712:     } else {
                   5713:         my %servers = &get_servers($domain,'library');
                   5714:         foreach my $tryserver (keys(%servers)) {
                   5715:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5716:                 push(@homeservers,$tryserver);
                   5717:             }
                   5718:         }
                   5719:     }
                   5720:     my $response;
                   5721:     foreach my $server (@homeservers) {
                   5722:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   5723:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5724:         my ($codetitlestr,$cat_title,$cat_order) = split(':',$response);
                   5725:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));  
                   5726:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  5727:             my ($name,$value)=split('=',$item);
                   5728:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  5729:         }
                   5730:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  5731:             my ($name,$value)=split('=',$item);
                   5732:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  5733:         }
                   5734:         return 'ok';
                   5735:     }
                   5736:     return $response;
                   5737: }
1.792     raeburn  5738: 
1.777     albertel 5739: sub auto_validate_class_sec {
1.918     raeburn  5740:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5741:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5742:     my $ownerlist;
                   5743:     if (ref($owners) eq 'ARRAY') {
                   5744:         $ownerlist = join(',',@{$owners});
                   5745:     } else {
                   5746:         $ownerlist = $owners;
                   5747:     }
1.773     raeburn  5748:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5749:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5750:     return $response;
                   5751: }
                   5752: 
1.679     raeburn  5753: # ------------------------------------------------------- Course Group routines
                   5754: 
                   5755: sub get_coursegroups {
1.809     raeburn  5756:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5757:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5758: }
                   5759: 
1.679     raeburn  5760: sub modify_coursegroup {
                   5761:     my ($cdom,$cnum,$groupsettings) = @_;
                   5762:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5763: }
                   5764: 
1.809     raeburn  5765: sub toggle_coursegroup_status {
                   5766:     my ($cdom,$cnum,$group,$action) = @_;
                   5767:     my ($from_namespace,$to_namespace);
                   5768:     if ($action eq 'delete') {
                   5769:         $from_namespace = 'coursegroups';
                   5770:         $to_namespace = 'deleted_groups';
                   5771:     } else {
                   5772:         $from_namespace = 'deleted_groups';
                   5773:         $to_namespace = 'coursegroups';
                   5774:     }
                   5775:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5776:     if (my $tmp = &error(%curr_group)) {
                   5777:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5778:         return ('read error',$tmp);
                   5779:     } else {
                   5780:         my %savedsettings = %curr_group; 
1.809     raeburn  5781:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5782:         my $deloutcome;
                   5783:         if ($result eq 'ok') {
1.809     raeburn  5784:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5785:         } else {
                   5786:             return ('write error',$result);
                   5787:         }
                   5788:         if ($deloutcome eq 'ok') {
                   5789:             return 'ok';
                   5790:         } else {
                   5791:             return ('delete error',$deloutcome);
                   5792:         }
                   5793:     }
                   5794: }
                   5795: 
1.679     raeburn  5796: sub modify_group_roles {
1.957     raeburn  5797:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  5798:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5799:     my $role = 'gr/'.&escape($userprivs);
                   5800:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  5801:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  5802:     if ($result eq 'ok') {
                   5803:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5804:     }
1.679     raeburn  5805:     return $result;
                   5806: }
                   5807: 
                   5808: sub modify_coursegroup_membership {
                   5809:     my ($cdom,$cnum,$membership) = @_;
                   5810:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5811:     return $result;
                   5812: }
                   5813: 
1.682     raeburn  5814: sub get_active_groups {
                   5815:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5816:     my $now = time;
                   5817:     my %groups = ();
                   5818:     foreach my $key (keys(%env)) {
1.811     albertel 5819:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5820:             my ($start,$end) = split(/\./,$env{$key});
                   5821:             if (($end!=0) && ($end<$now)) { next; }
                   5822:             if (($start!=0) && ($start>$now)) { next; }
                   5823:             if ($1 eq $cdom && $2 eq $cnum) {
                   5824:                 $groups{$3} = $env{$key} ;
                   5825:             }
                   5826:         }
                   5827:     }
                   5828:     return %groups;
                   5829: }
                   5830: 
1.683     raeburn  5831: sub get_group_membership {
                   5832:     my ($cdom,$cnum,$group) = @_;
                   5833:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5834: }
                   5835: 
                   5836: sub get_users_groups {
                   5837:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5838:     my @usersgroups;
1.683     raeburn  5839:     my $cachetime=1800;
                   5840: 
                   5841:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5842:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5843:     if (defined($cached)) {
1.734     albertel 5844:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5845:     } else {  
                   5846:         $grouplist = '';
1.816     raeburn  5847:         my $courseurl = &courseid_to_courseurl($courseid);
                   5848:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5849:         my $access_end = $env{'course.'.$courseid.
                   5850:                               '.default_enrollment_end_date'};
                   5851:         my $now = time;
                   5852:         foreach my $key (keys(%roleshash)) {
                   5853:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5854:                 my $group = $1;
                   5855:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5856:                     my $start = $2;
                   5857:                     my $end = $1;
                   5858:                     if ($start == -1) { next; } # deleted from group
                   5859:                     if (($start!=0) && ($start>$now)) { next; }
                   5860:                     if (($end!=0) && ($end<$now)) {
                   5861:                         if ($access_end && $access_end < $now) {
                   5862:                             if ($access_end - $end < 86400) {
                   5863:                                 push(@usersgroups,$group);
1.733     raeburn  5864:                             }
                   5865:                         }
1.817     raeburn  5866:                         next;
1.733     raeburn  5867:                     }
1.817     raeburn  5868:                     push(@usersgroups,$group);
1.683     raeburn  5869:                 }
                   5870:             }
                   5871:         }
1.817     raeburn  5872:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5873:         $grouplist = join(':',@usersgroups);
                   5874:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5875:     }
1.733     raeburn  5876:     return @usersgroups;
1.683     raeburn  5877: }
                   5878: 
                   5879: sub devalidate_getgroups_cache {
                   5880:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5881:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5882: 
1.683     raeburn  5883:     my $hashid="$udom:$uname:$courseid";
                   5884:     &devalidate_cache_new('getgroups',$hashid);
                   5885: }
                   5886: 
1.12      www      5887: # ------------------------------------------------------------------ Plain Text
                   5888: 
                   5889: sub plaintext {
1.988     raeburn  5890:     my ($short,$type,$cid,$forcedefault) = @_;
1.758     albertel 5891:     if ($short =~ /^cr/) {
                   5892: 	return (split('/',$short))[-1];
                   5893:     }
1.742     raeburn  5894:     if (!defined($cid)) {
                   5895:         $cid = $env{'request.course.id'};
                   5896:     }
1.988     raeburn  5897:     if (defined($cid) && ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '')) {
                   5898:         unless ($forcedefault) {
                   5899:             my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   5900:             &Apache::lonlocal::mt_escape(\$roletext);
                   5901:             return &Apache::lonlocal::mt($roletext);
                   5902:         }
1.742     raeburn  5903:     }
                   5904:     my %rolenames = (
                   5905:                       Course => 'std',
                   5906:                       Group => 'alt1',
                   5907:                     );
                   5908:     if (defined($type) && 
                   5909:          defined($rolenames{$type}) && 
                   5910:          defined($prp{$short}{$rolenames{$type}})) {
                   5911:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5912:     } else {
                   5913:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5914:     }
1.12      www      5915: }
                   5916: 
                   5917: # ----------------------------------------------------------------- Assign Role
                   5918: 
                   5919: sub assignrole {
1.957     raeburn  5920:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   5921:         $context)=@_;
1.21      www      5922:     my $mrole;
                   5923:     if ($role =~ /^cr\//) {
1.393     www      5924:         my $cwosec=$url;
1.811     albertel 5925:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5926: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5927:            &logthis('Refused custom assignrole: '.
                   5928:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5929: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5930:            return 'refused'; 
                   5931:         }
1.21      www      5932:         $mrole='cr';
1.678     raeburn  5933:     } elsif ($role =~ /^gr\//) {
                   5934:         my $cwogrp=$url;
1.811     albertel 5935:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5936:         unless (&allowed('mdg',$cwogrp)) {
                   5937:             &logthis('Refused group assignrole: '.
                   5938:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5939:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5940:             return 'refused';
                   5941:         }
                   5942:         $mrole='gr';
1.21      www      5943:     } else {
1.82      www      5944:         my $cwosec=$url;
1.811     albertel 5945:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5946:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5947:             my $refused;
                   5948:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5949:                 if (!(&allowed('c'.$role,$url))) {
                   5950:                     $refused = 1;
                   5951:                 }
                   5952:             } else {
                   5953:                 $refused = 1;
                   5954:             }
1.947     raeburn  5955:             if ($refused) {
                   5956:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5957:                     $refused = '';
                   5958:                 } else {
                   5959:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   5960:                              ' '.$role.' '.$end.' '.$start.' by '.
                   5961: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   5962:                     return 'refused';
                   5963:                 }
1.932     raeburn  5964:             }
1.104     www      5965:         }
1.21      www      5966:         $mrole=$role;
                   5967:     }
1.620     albertel 5968:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5969:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5970:     if ($end) { $command.='_'.$end; }
1.21      www      5971:     if ($start) {
                   5972: 	if ($end) { 
1.81      www      5973:            $command.='_'.$start; 
1.21      www      5974:         } else {
1.81      www      5975:            $command.='_0_'.$start;
1.21      www      5976:         }
                   5977:     }
1.739     raeburn  5978:     my $origstart = $start;
                   5979:     my $origend = $end;
1.957     raeburn  5980:     my $delflag;
1.357     www      5981: # actually delete
                   5982:     if ($deleteflag) {
1.373     www      5983: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5984: # modify command to delete the role
1.620     albertel 5985:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5986:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5987: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5988: # set start and finish to negative values for userrolelog
                   5989:            $start=-1;
                   5990:            $end=-1;
1.957     raeburn  5991:            $delflag = 1;
1.357     www      5992:         }
                   5993:     }
                   5994: # send command
1.349     www      5995:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5996: # log new user role if status is ok
1.349     www      5997:     if ($answer eq 'ok') {
1.663     raeburn  5998: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5999: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6000:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6001:         unless ($role =~ /^gr/) {
                   6002:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6003:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6004:         }
1.349     www      6005:     }
                   6006:     return $answer;
1.169     harris41 6007: }
                   6008: 
                   6009: # -------------------------------------------------- Modify user authentication
1.197     www      6010: # Overrides without validation
                   6011: 
1.169     harris41 6012: sub modifyuserauth {
                   6013:     my ($udom,$uname,$umode,$upass)=@_;
                   6014:     my $uhome=&homeserver($uname,$udom);
1.197     www      6015:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6016:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6017:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6018:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6019:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6020: 		     &escape($upass),$uhome);
1.620     albertel 6021:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6022:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6023:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6024:     &log($udom,,$uname,$uhome,
1.620     albertel 6025:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6026:                                      $env{'user.name'}.', '.$umode.
1.197     www      6027:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 6028:     unless ($reply eq 'ok') {
1.197     www      6029:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 6030: 	return 'error: '.$reply;
                   6031:     }   
1.170     harris41 6032:     return 'ok';
1.80      www      6033: }
                   6034: 
1.81      www      6035: # --------------------------------------------------------------- Modify a user
1.80      www      6036: 
1.81      www      6037: sub modifyuser {
1.206     matthew  6038:     my ($udom,    $uname, $uid,
                   6039:         $umode,   $upass, $first,
                   6040:         $middle,  $last,  $gene,
1.963     raeburn  6041:         $forceid, $desiredhome, $email, $inststatus)=@_;
1.807     albertel 6042:     $udom= &LONCAPA::clean_domain($udom);
                   6043:     $uname=&LONCAPA::clean_username($uname);
1.81      www      6044:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      6045:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  6046: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   6047:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   6048:                                      ' desiredhome not specified'). 
1.620     albertel 6049:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6050:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 6051:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      6052: # ----------------------------------------------------------------- Create User
1.406     albertel 6053:     if (($uhome eq 'no_host') && 
                   6054: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      6055:         my $unhome='';
1.844     albertel 6056:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  6057:             $unhome = $desiredhome;
1.620     albertel 6058: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   6059: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  6060:         } else { # load balancing routine for determining $unhome
1.81      www      6061:             my $loadm=10000000;
1.841     albertel 6062: 	    my %servers = &get_servers($udom,'library');
                   6063: 	    foreach my $tryserver (keys(%servers)) {
                   6064: 		my $answer=reply('load',$tryserver);
                   6065: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   6066: 		    $loadm=$answer;
                   6067: 		    $unhome=$tryserver;
                   6068: 		}
1.80      www      6069: 	    }
                   6070:         }
                   6071:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  6072: 	    return 'error: unable to find a home server for '.$uname.
                   6073:                    ' in domain '.$udom;
1.80      www      6074:         }
                   6075:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   6076:                          &escape($upass),$unhome);
                   6077: 	unless ($reply eq 'ok') {
                   6078:             return 'error: '.$reply;
                   6079:         }   
1.230     stredwic 6080:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      6081:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  6082: 	    return 'error: unable verify users home machine.';
1.80      www      6083:         }
1.209     matthew  6084:     }   # End of creation of new user
1.80      www      6085: # ---------------------------------------------------------------------- Add ID
                   6086:     if ($uid) {
                   6087:        $uid=~tr/A-Z/a-z/;
                   6088:        my %uidhash=&idrget($udom,$uname);
1.196     www      6089:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   6090:          && (!$forceid)) {
1.80      www      6091: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  6092: 	      return 'error: user id "'.$uid.'" does not match '.
                   6093:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      6094:           }
                   6095:        } else {
                   6096: 	  &idput($udom,($uname => $uid));
                   6097:        }
                   6098:     }
                   6099: # -------------------------------------------------------------- Add names, etc
1.313     matthew  6100:     my @tmp=&get('environment',
1.899     raeburn  6101: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  6102:                     'permanentemail','inststatus'],
1.134     albertel 6103: 		   $udom,$uname);
1.313     matthew  6104:     my %names;
                   6105:     if ($tmp[0] =~ m/^error:.*/) { 
                   6106:         %names=(); 
                   6107:     } else {
                   6108:         %names = @tmp;
                   6109:     }
1.388     www      6110: #
                   6111: # Make sure to not trash student environment if instructor does not bother
                   6112: # to supply name and email information
                   6113: #
                   6114:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  6115:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      6116:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  6117:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      6118:     if ($email) {
                   6119:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  6120:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      6121:     }
1.899     raeburn  6122:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  6123:     if (defined($inststatus)) {
                   6124:         $names{'inststatus'} = '';
                   6125:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   6126:         if (ref($usertypes) eq 'HASH') {
                   6127:             my @okstatuses; 
                   6128:             foreach my $item (split(/:/,$inststatus)) {
                   6129:                 if (defined($usertypes->{$item})) {
                   6130:                     push(@okstatuses,$item);  
                   6131:                 }
                   6132:             }
                   6133:             if (@okstatuses) {
                   6134:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   6135:             }
                   6136:         }
                   6137:     }
1.134     albertel 6138:     my $reply = &put('environment', \%names, $udom,$uname);
                   6139:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  6140:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      6141:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963     raeburn  6142:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
                   6143:                  $umode.', '.$first.', '.$middle.', '.
                   6144: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
                   6145:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   6146:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   6147:     } else {
                   6148:         $logmsg .= ' during self creation';
                   6149:     }
                   6150:     &logthis($logmsg);
1.134     albertel 6151:     return 'ok';
1.80      www      6152: }
                   6153: 
1.81      www      6154: # -------------------------------------------------------------- Modify student
1.80      www      6155: 
1.81      www      6156: sub modifystudent {
                   6157:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  6158:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  6159:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 6160:     if (!$cid) {
1.620     albertel 6161: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6162: 	    return 'not_in_class';
                   6163: 	}
1.80      www      6164:     }
                   6165: # --------------------------------------------------------------- Make the user
1.81      www      6166:     my $reply=&modifyuser
1.209     matthew  6167: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  6168:          $desiredhome,$email,$inststatus);
1.80      www      6169:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  6170:     # This will cause &modify_student_enrollment to get the uid from the
                   6171:     # students environment
                   6172:     $uid = undef if (!$forceid);
1.455     albertel 6173:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  6174: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  6175:     return $reply;
                   6176: }
                   6177: 
                   6178: sub modify_student_enrollment {
1.957     raeburn  6179:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 6180:     my ($cdom,$cnum,$chome);
                   6181:     if (!$cid) {
1.620     albertel 6182: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6183: 	    return 'not_in_class';
                   6184: 	}
1.620     albertel 6185: 	$cdom=$env{'course.'.$cid.'.domain'};
                   6186: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 6187:     } else {
                   6188: 	($cdom,$cnum)=split(/_/,$cid);
                   6189:     }
1.620     albertel 6190:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 6191:     if (!$chome) {
1.457     raeburn  6192: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  6193:     }
1.455     albertel 6194:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  6195:     # Make sure the user exists
1.81      www      6196:     my $uhome=&homeserver($uname,$udom);
                   6197:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6198: 	return 'error: no such user';
                   6199:     }
1.297     matthew  6200:     # Get student data if we were not given enough information
                   6201:     if (!defined($first)  || $first  eq '' || 
                   6202:         !defined($last)   || $last   eq '' || 
                   6203:         !defined($uid)    || $uid    eq '' || 
                   6204:         !defined($middle) || $middle eq '' || 
                   6205:         !defined($gene)   || $gene   eq '') {
1.294     matthew  6206:         # They did not supply us with enough data to enroll the student, so
                   6207:         # we need to pick up more information.
1.297     matthew  6208:         my %tmp = &get('environment',
1.294     matthew  6209:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  6210:                        ,$udom,$uname);
                   6211: 
1.800     albertel 6212:         #foreach my $key (keys(%tmp)) {
                   6213:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 6214:         #}
1.294     matthew  6215:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   6216:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   6217:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  6218:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  6219:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   6220:     }
1.556     albertel 6221:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 6222:     my $reply=cput('classlist',
                   6223: 		   {"$uname:$udom" => 
1.515     raeburn  6224: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 6225: 		   $cdom,$cnum);
1.81      www      6226:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   6227: 	return 'error: '.$reply;
1.652     albertel 6228:     } else {
                   6229: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      6230:     }
1.297     matthew  6231:     # Add student role to user
1.83      www      6232:     my $uurl='/'.$cid;
1.81      www      6233:     $uurl=~s/\_/\//g;
                   6234:     if ($usec) {
                   6235: 	$uurl.='/'.$usec;
                   6236:     }
1.957     raeburn  6237:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      6238: }
                   6239: 
1.556     albertel 6240: sub format_name {
                   6241:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   6242:     my $name;
                   6243:     if ($first ne 'lastname') {
                   6244: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   6245:     } else {
                   6246: 	if ($lastname=~/\S/) {
                   6247: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   6248: 	    $name=~s/\s+,/,/;
                   6249: 	} else {
                   6250: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   6251: 	}
                   6252:     }
                   6253:     $name=~s/^\s+//;
                   6254:     $name=~s/\s+$//;
                   6255:     $name=~s/\s+/ /g;
                   6256:     return $name;
                   6257: }
                   6258: 
1.84      www      6259: # ------------------------------------------------- Write to course preferences
                   6260: 
                   6261: sub writecoursepref {
                   6262:     my ($courseid,%prefs)=@_;
                   6263:     $courseid=~s/^\///;
                   6264:     $courseid=~s/\_/\//g;
                   6265:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   6266:     my $chome=homeserver($cnum,$cdomain);
                   6267:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   6268: 	return 'error: no such course';
                   6269:     }
                   6270:     my $cstring='';
1.800     albertel 6271:     foreach my $pref (keys(%prefs)) {
                   6272: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 6273:     }
1.84      www      6274:     $cstring=~s/\&$//;
                   6275:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   6276: }
                   6277: 
                   6278: # ---------------------------------------------------------- Make/modify course
                   6279: 
                   6280: sub createcourse {
1.741     raeburn  6281:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   6282:         $course_owner,$crstype)=@_;
1.84      www      6283:     $url=&declutter($url);
                   6284:     my $cid='';
1.264     matthew  6285:     unless (&allowed('ccc',$udom)) {
1.84      www      6286:         return 'refused';
                   6287:     }
                   6288: # ------------------------------------------------------------------- Create ID
1.674     www      6289:    my $uname=int(1+rand(9)).
                   6290:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   6291:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      6292:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   6293: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 6294:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      6295:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6296:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   6297:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 6298:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      6299:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6300:            return 'error: unable to generate unique course-ID';
                   6301:        } 
                   6302:    }
1.264     matthew  6303: # ------------------------------------------------ Check supplied server name
1.620     albertel 6304:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 6305:     if (! &is_library($course_server)) {
1.264     matthew  6306:         return 'error:bad server name '.$course_server;
                   6307:     }
1.84      www      6308: # ------------------------------------------------------------- Make the course
                   6309:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  6310:                       $course_server);
1.84      www      6311:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 6312:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      6313:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6314: 	return 'error: no such course';
                   6315:     }
1.271     www      6316: # ----------------------------------------------------------------- Course made
1.516     raeburn  6317: # log existence
1.918     raeburn  6318:     my $newcourse = {
                   6319:                     $udom.'_'.$uname => {
1.921     raeburn  6320:                                      description => $description,
                   6321:                                      inst_code   => $inst_code,
                   6322:                                      owner       => $course_owner,
                   6323:                                      type        => $crstype,
1.918     raeburn  6324:                                                 },
                   6325:                     };
1.921     raeburn  6326:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      6327: # set toplevel url
1.271     www      6328:     my $topurl=$url;
                   6329:     unless ($nonstandard) {
                   6330: # ------------------------------------------ For standard courses, make top url
                   6331:         my $mapurl=&clutter($url);
1.278     www      6332:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 6333:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      6334: <map>
                   6335: <resource id="1" type="start"></resource>
                   6336: <resource id="2" src="$mapurl"></resource>
                   6337: <resource id="3" type="finish"></resource>
                   6338: <link index="1" from="1" to="2"></link>
                   6339: <link index="2" from="2" to="3"></link>
                   6340: </map>
                   6341: ENDINITMAP
                   6342:         $topurl=&declutter(
1.638     albertel 6343:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      6344:                           );
                   6345:     }
                   6346: # ----------------------------------------------------------- Write preferences
1.84      www      6347:     &writecoursepref($udom.'_'.$uname,
                   6348:                      ('description' => $description,
1.271     www      6349:                       'url'         => $topurl));
1.84      www      6350:     return '/'.$udom.'/'.$uname;
                   6351: }
                   6352: 
1.813     albertel 6353: sub is_course {
                   6354:     my ($cdom,$cnum) = @_;
                   6355:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  6356: 				undef,'.');
1.813     albertel 6357:     if (exists($courses{$cdom.'_'.$cnum})) {
                   6358:         return 1;
                   6359:     }
                   6360:     return 0;
                   6361: }
                   6362: 
1.21      www      6363: # ---------------------------------------------------------- Assign Custom Role
                   6364: 
                   6365: sub assigncustomrole {
1.957     raeburn  6366:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6367:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  6368:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      6369: }
                   6370: 
                   6371: # ----------------------------------------------------------------- Revoke Role
                   6372: 
                   6373: sub revokerole {
1.957     raeburn  6374:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6375:     my $now=time;
1.965     raeburn  6376:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      6377: }
                   6378: 
                   6379: # ---------------------------------------------------------- Revoke Custom Role
                   6380: 
                   6381: sub revokecustomrole {
1.957     raeburn  6382:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6383:     my $now=time;
1.357     www      6384:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  6385:            $deleteflag,$selfenroll,$context);
1.17      www      6386: }
                   6387: 
1.533     banghart 6388: # ------------------------------------------------------------ Disk usage
1.535     albertel 6389: sub diskusage {
1.955     raeburn  6390:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   6391:     $directorypath =~ s/\/$//;
                   6392:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   6393:                        .&escape($getpropath).':'.&escape($uname).':'
                   6394:                        .&escape($udom),homeserver($uname,$udom));
                   6395:     if ($listing eq 'unknown_cmd') {
                   6396:         if ($getpropath) {
                   6397:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   6398:         }
                   6399:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   6400:     }
1.514     albertel 6401:     return $listing;
1.512     banghart 6402: }
                   6403: 
1.566     banghart 6404: sub is_locked {
                   6405:     my ($file_name, $domain, $user) = @_;
                   6406:     my @check;
                   6407:     my $is_locked;
                   6408:     push @check, $file_name;
1.613     albertel 6409:     my %locked = &get('file_permissions',\@check,
1.620     albertel 6410: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 6411:     my ($tmp)=keys(%locked);
                   6412:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  6413:     
1.566     banghart 6414:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  6415:         $is_locked = 'false';
                   6416:         foreach my $entry (@{$locked{$file_name}}) {
                   6417:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  6418:                $is_locked = 'true';
                   6419:                last;
1.745     raeburn  6420:            }
                   6421:        }
1.566     banghart 6422:     } else {
                   6423:         $is_locked = 'false';
                   6424:     }
                   6425: }
                   6426: 
1.759     albertel 6427: sub declutter_portfile {
                   6428:     my ($file) = @_;
1.833     albertel 6429:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 6430:     return $file;
                   6431: }
                   6432: 
1.559     banghart 6433: # ------------------------------------------------------------- Mark as Read Only
                   6434: 
                   6435: sub mark_as_readonly {
                   6436:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 6437:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6438:     my ($tmp)=keys(%current_permissions);
                   6439:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 6440:     foreach my $file (@{$files}) {
1.759     albertel 6441: 	$file = &declutter_portfile($file);
1.561     banghart 6442:         push(@{$current_permissions{$file}},$what);
1.559     banghart 6443:     }
1.613     albertel 6444:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6445:     return;
                   6446: }
                   6447: 
1.572     banghart 6448: # ------------------------------------------------------------Save Selected Files
                   6449: 
                   6450: sub save_selected_files {
                   6451:     my ($user, $path, @files) = @_;
                   6452:     my $filename = $user."savedfiles";
1.573     banghart 6453:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 6454:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 6455:     foreach my $file (@files) {
1.620     albertel 6456:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 6457:     }
                   6458:     foreach my $file (@other_files) {
1.574     banghart 6459:         print (OUT $file."\n");
1.572     banghart 6460:     }
1.574     banghart 6461:     close (OUT);
1.572     banghart 6462:     return 'ok';
                   6463: }
                   6464: 
1.574     banghart 6465: sub clear_selected_files {
                   6466:     my ($user) = @_;
                   6467:     my $filename = $user."savedfiles";
                   6468:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6469:     print (OUT undef);
                   6470:     close (OUT);
                   6471:     return ("ok");    
                   6472: }
                   6473: 
1.572     banghart 6474: sub files_in_path {
                   6475:     my ($user, $path) = @_;
                   6476:     my $filename = $user."savedfiles";
                   6477:     my %return_files;
1.574     banghart 6478:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 6479:     while (my $line_in = <IN>) {
1.574     banghart 6480:         chomp ($line_in);
                   6481:         my @paths_and_file = split (m!/!, $line_in);
                   6482:         my $file_part = pop (@paths_and_file);
                   6483:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 6484:         $path_part.='/';
                   6485:         my $path_and_file = $path_part.$file_part;
                   6486:         if ($path_part eq $path) {
                   6487:             $return_files{$file_part}= 'selected';
                   6488:         }
                   6489:     }
1.574     banghart 6490:     close (IN);
                   6491:     return (\%return_files);
1.572     banghart 6492: }
                   6493: 
                   6494: # called in portfolio select mode, to show files selected NOT in current directory
                   6495: sub files_not_in_path {
                   6496:     my ($user, $path) = @_;
                   6497:     my $filename = $user."savedfiles";
                   6498:     my @return_files;
                   6499:     my $path_part;
1.800     albertel 6500:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6501:     while (my $line = <IN>) {
1.572     banghart 6502:         #ok, I know it's clunky, but I want it to work
1.800     albertel 6503:         my @paths_and_file = split(m|/|, $line);
                   6504:         my $file_part = pop(@paths_and_file);
                   6505:         chomp($file_part);
                   6506:         my $path_part = join('/', @paths_and_file);
1.572     banghart 6507:         $path_part .= '/';
                   6508:         my $path_and_file = $path_part.$file_part;
                   6509:         if ($path_part ne $path) {
1.800     albertel 6510:             push(@return_files, ($path_and_file));
1.572     banghart 6511:         }
                   6512:     }
1.800     albertel 6513:     close(OUT);
1.574     banghart 6514:     return (@return_files);
1.572     banghart 6515: }
                   6516: 
1.745     raeburn  6517: #----------------------------------------------Get portfolio file permissions
1.629     banghart 6518: 
1.745     raeburn  6519: sub get_portfile_permissions {
                   6520:     my ($domain,$user) = @_;
1.613     albertel 6521:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6522:     my ($tmp)=keys(%current_permissions);
                   6523:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6524:     return \%current_permissions;
                   6525: }
                   6526: 
                   6527: #---------------------------------------------Get portfolio file access controls
                   6528: 
1.749     raeburn  6529: sub get_access_controls {
1.745     raeburn  6530:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 6531:     my %access;
                   6532:     my $real_file = $file;
                   6533:     $file =~ s/\.meta$//;
1.745     raeburn  6534:     if (defined($file)) {
1.749     raeburn  6535:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   6536:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 6537:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  6538:             }
                   6539:         }
1.745     raeburn  6540:     } else {
1.749     raeburn  6541:         foreach my $key (keys(%{$current_permissions})) {
                   6542:             if ($key =~ /\0accesscontrol$/) {
                   6543:                 if (defined($group)) {
                   6544:                     if ($key !~ m-^\Q$group\E/-) {
                   6545:                         next;
                   6546:                     }
                   6547:                 }
                   6548:                 my ($fullpath) = split(/\0/,$key);
                   6549:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   6550:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   6551:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   6552:                     }
                   6553:                 }
                   6554:             }
                   6555:         }
                   6556:     }
                   6557:     return %access;
                   6558: }
                   6559: 
                   6560: sub modify_access_controls {
                   6561:     my ($file_name,$changes,$domain,$user)=@_;
                   6562:     my ($outcome,$deloutcome);
                   6563:     my %store_permissions;
                   6564:     my %new_values;
                   6565:     my %new_control;
                   6566:     my %translation;
                   6567:     my @deletions = ();
                   6568:     my $now = time;
                   6569:     if (exists($$changes{'activate'})) {
                   6570:         if (ref($$changes{'activate'}) eq 'HASH') {
                   6571:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   6572:             my $numnew = scalar(@newitems);
                   6573:             for (my $i=0; $i<$numnew; $i++) {
                   6574:                 my $newkey = $newitems[$i];
                   6575:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  6576:                 if ($newkey =~ /^\d+:/) { 
                   6577:                     $newkey =~ s/^(\d+)/$newid/;
                   6578:                     $translation{$1} = $newid;
                   6579:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   6580:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   6581:                     $translation{$1} = $newid;
                   6582:                 }
1.749     raeburn  6583:                 $new_values{$file_name."\0".$newkey} = 
                   6584:                                           $$changes{'activate'}{$newitems[$i]};
                   6585:                 $new_control{$newkey} = $now;
                   6586:             }
                   6587:         }
                   6588:     }
                   6589:     my %todelete;
                   6590:     my %changed_items;
                   6591:     foreach my $action ('delete','update') {
                   6592:         if (exists($$changes{$action})) {
                   6593:             if (ref($$changes{$action}) eq 'HASH') {
                   6594:                 foreach my $key (keys(%{$$changes{$action}})) {
                   6595:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   6596:                     if ($action eq 'delete') { 
                   6597:                         $todelete{$itemnum} = 1;
                   6598:                     } else {
                   6599:                         $changed_items{$itemnum} = $key;
                   6600:                     }
                   6601:                 }
1.745     raeburn  6602:             }
                   6603:         }
1.749     raeburn  6604:     }
                   6605:     # get lock on access controls for file.
                   6606:     my $lockhash = {
                   6607:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   6608:                                                        ':'.$env{'user.domain'},
                   6609:                    }; 
                   6610:     my $tries = 0;
                   6611:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6612:    
                   6613:     while (($gotlock ne 'ok') && $tries <3) {
                   6614:         $tries ++;
                   6615:         sleep 1;
                   6616:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6617:     }
                   6618:     if ($gotlock eq 'ok') {
                   6619:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6620:         my ($tmp)=keys(%curr_permissions);
                   6621:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6622:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6623:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6624:             if (ref($curr_controls) eq 'HASH') {
                   6625:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6626:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6627:                     if (defined($todelete{$itemnum})) {
                   6628:                         push(@deletions,$file_name."\0".$control_item);
                   6629:                     } else {
                   6630:                         if (defined($changed_items{$itemnum})) {
                   6631:                             $new_control{$changed_items{$itemnum}} = $now;
                   6632:                             push(@deletions,$file_name."\0".$control_item);
                   6633:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6634:                         } else {
                   6635:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6636:                         }
                   6637:                     }
1.745     raeburn  6638:                 }
                   6639:             }
                   6640:         }
1.970     raeburn  6641:         my ($group);
                   6642:         if (&is_course($domain,$user)) {
                   6643:             ($group,my $file) = split(/\//,$file_name,2);
                   6644:         }
1.749     raeburn  6645:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6646:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6647:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6648:         #  remove lock
                   6649:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6650:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6651:         my $sqlresult =
1.970     raeburn  6652:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  6653:                                     $group);
1.749     raeburn  6654:     } else {
                   6655:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6656:     }
1.749     raeburn  6657:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6658: }
                   6659: 
1.827     raeburn  6660: sub make_public_indefinitely {
                   6661:     my ($requrl) = @_;
                   6662:     my $now = time;
                   6663:     my $action = 'activate';
                   6664:     my $aclnum = 0;
                   6665:     if (&is_portfolio_url($requrl)) {
                   6666:         my (undef,$udom,$unum,$file_name,$group) =
                   6667:             &parse_portfolio_url($requrl);
                   6668:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6669:         my %access_controls = &get_access_controls($current_perms,
                   6670:                                                    $group,$file_name);
                   6671:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6672:             my ($num,$scope,$end,$start) = 
                   6673:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6674:             if ($scope eq 'public') {
                   6675:                 if ($start <= $now && $end == 0) {
                   6676:                     $action = 'none';
                   6677:                 } else {
                   6678:                     $action = 'update';
                   6679:                     $aclnum = $num;
                   6680:                 }
                   6681:                 last;
                   6682:             }
                   6683:         }
                   6684:         if ($action eq 'none') {
                   6685:              return 'ok';
                   6686:         } else {
                   6687:             my %changes;
                   6688:             my $newend = 0;
                   6689:             my $newstart = $now;
                   6690:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6691:             $changes{$action}{$newkey} = {
                   6692:                 type => 'public',
                   6693:                 time => {
                   6694:                     start => $newstart,
                   6695:                     end   => $newend,
                   6696:                 },
                   6697:             };
                   6698:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6699:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6700:             return $outcome;
                   6701:         }
                   6702:     } else {
                   6703:         return 'invalid';
                   6704:     }
                   6705: }
                   6706: 
1.745     raeburn  6707: #------------------------------------------------------Get Marked as Read Only
                   6708: 
                   6709: sub get_marked_as_readonly {
                   6710:     my ($domain,$user,$what,$group) = @_;
                   6711:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6712:     my @readonly_files;
1.629     banghart 6713:     my $cmp1=$what;
                   6714:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6715:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6716:         if (defined($group)) {
                   6717:             if ($file_name !~ m-^\Q$group\E/-) {
                   6718:                 next;
                   6719:             }
                   6720:         }
1.561     banghart 6721:         if (ref($value) eq "ARRAY"){
                   6722:             foreach my $stored_what (@{$value}) {
1.629     banghart 6723:                 my $cmp2=$stored_what;
1.759     albertel 6724:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6725:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6726:                 }
1.629     banghart 6727:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6728:                     push(@readonly_files, $file_name);
1.745     raeburn  6729:                     last;
1.563     banghart 6730:                 } elsif (!defined($what)) {
                   6731:                     push(@readonly_files, $file_name);
1.745     raeburn  6732:                     last;
1.561     banghart 6733:                 }
                   6734:             }
1.745     raeburn  6735:         }
1.561     banghart 6736:     }
                   6737:     return @readonly_files;
                   6738: }
1.577     banghart 6739: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6740: 
1.577     banghart 6741: sub get_marked_as_readonly_hash {
1.745     raeburn  6742:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6743:     my %readonly_files;
1.745     raeburn  6744:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6745:         if (defined($group)) {
                   6746:             if ($file_name !~ m-^\Q$group\E/-) {
                   6747:                 next;
                   6748:             }
                   6749:         }
1.577     banghart 6750:         if (ref($value) eq "ARRAY"){
                   6751:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6752:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6753:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6754:                         if ($lock_descriptor eq 'graded') {
                   6755:                             $readonly_files{$file_name} = 'graded';
                   6756:                         } elsif ($lock_descriptor eq 'handback') {
                   6757:                             $readonly_files{$file_name} = 'handback';
                   6758:                         } else {
                   6759:                             if (!exists($readonly_files{$file_name})) {
                   6760:                                 $readonly_files{$file_name} = 'locked';
                   6761:                             }
                   6762:                         }
1.745     raeburn  6763:                     }
1.750     banghart 6764:                 } 
1.577     banghart 6765:             }
                   6766:         } 
                   6767:     }
                   6768:     return %readonly_files;
                   6769: }
1.559     banghart 6770: # ------------------------------------------------------------ Unmark as Read Only
                   6771: 
                   6772: sub unmark_as_readonly {
1.629     banghart 6773:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6774:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6775:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6776:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6777:     my $symb_crs = $what;
                   6778:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6779:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6780:     my ($tmp)=keys(%current_permissions);
                   6781:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6782:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6783:     foreach my $file (@readonly_files) {
1.759     albertel 6784: 	my $clean_file = &declutter_portfile($file);
                   6785: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6786: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6787:         my @new_locks;
                   6788:         my @del_keys;
                   6789:         if (ref($current_locks) eq "ARRAY"){
                   6790:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6791:                 my $compare=$locker;
1.749     raeburn  6792:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6793:                     $compare=join('',@{$locker});
1.746     raeburn  6794:                     if ($compare ne $symb_crs) {
                   6795:                         push(@new_locks, $locker);
                   6796:                     }
1.563     banghart 6797:                 }
                   6798:             }
1.650     albertel 6799:             if (scalar(@new_locks) > 0) {
1.563     banghart 6800:                 $current_permissions{$file} = \@new_locks;
                   6801:             } else {
                   6802:                 push(@del_keys, $file);
1.613     albertel 6803:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6804:                 delete($current_permissions{$file});
1.563     banghart 6805:             }
                   6806:         }
1.561     banghart 6807:     }
1.613     albertel 6808:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6809:     return;
                   6810: }
1.512     banghart 6811: 
1.17      www      6812: # ------------------------------------------------------------ Directory lister
                   6813: 
                   6814: sub dirlist {
1.955     raeburn  6815:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      6816:     $uri=~s/^\///;
                   6817:     $uri=~s/\/$//;
1.253     stredwic 6818:     my ($udom, $uname);
1.955     raeburn  6819:     if ($getuserdir) {
1.253     stredwic 6820:         $udom = $userdomain;
                   6821:         $uname = $username;
1.955     raeburn  6822:     } else {
                   6823:         (undef,$udom,$uname)=split(/\//,$uri);
                   6824:         if(defined($userdomain)) {
                   6825:             $udom = $userdomain;
                   6826:         }
                   6827:         if(defined($username)) {
                   6828:             $uname = $username;
                   6829:         }
1.253     stredwic 6830:     }
1.955     raeburn  6831:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 6832: 
1.955     raeburn  6833:     $dirRoot = $perlvar{'lonDocRoot'};
                   6834:     if (defined($getpropath)) {
                   6835:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 6836:         $dirRoot =~ s/\/$//;
1.955     raeburn  6837:     } elsif (defined($getuserdir)) {
                   6838:         my $subdir=$uname.'__';
                   6839:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6840:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   6841:                    ."/$udom/$subdir/$uname";
                   6842:     } elsif (defined($alternateRoot)) {
                   6843:         $dirRoot = $alternateRoot;
1.751     banghart 6844:     }
1.253     stredwic 6845: 
                   6846:     if($udom) {
                   6847:         if($uname) {
1.955     raeburn  6848:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  6849:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  6850:                               .':'.&escape($uname).':'.&escape($udom),
                   6851:                               &homeserver($uname,$udom));
                   6852:             if ($listing eq 'unknown_cmd') {
                   6853:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6854:                                   &homeserver($uname,$udom));
                   6855:             } else {
                   6856:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6857:             }
1.605     matthew  6858:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6859:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6860: 				  &homeserver($uname,$udom));
1.605     matthew  6861:                 @listing_results = split(/:/,$listing);
                   6862:             } else {
                   6863:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6864:             }
                   6865:             return @listing_results;
1.955     raeburn  6866:         } elsif(!$alternateRoot) {
1.800     albertel 6867:             my %allusers;
1.841     albertel 6868: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  6869:  	    foreach my $tryserver (keys(%servers)) {
                   6870:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   6871:                                   &escape($udom),$tryserver);
                   6872:                 if ($listing eq 'unknown_cmd') {
                   6873: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6874: 				      $udom, $tryserver);
                   6875:                 } else {
                   6876:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6877:                 }
1.841     albertel 6878: 		if ($listing eq 'unknown_cmd') {
                   6879: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6880: 				      $udom, $tryserver);
                   6881: 		    @listing_results = split(/:/,$listing);
                   6882: 		} else {
                   6883: 		    @listing_results =
                   6884: 			map { &unescape($_); } split(/:/,$listing);
                   6885: 		}
                   6886: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6887: 		    $listing_results[0] ne 'empty'       &&
                   6888: 		    $listing_results[0] ne 'con_lost') {
                   6889: 		    foreach my $line (@listing_results) {
                   6890: 			my ($entry) = split(/&/,$line,2);
                   6891: 			$allusers{$entry} = 1;
                   6892: 		    }
                   6893: 		}
1.253     stredwic 6894:             }
                   6895:             my $alluserstr='';
1.800     albertel 6896:             foreach my $user (sort(keys(%allusers))) {
                   6897:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6898:             }
                   6899:             $alluserstr=~s/:$//;
                   6900:             return split(/:/,$alluserstr);
                   6901:         } else {
1.800     albertel 6902:             return ('missing user name');
1.253     stredwic 6903:         }
1.955     raeburn  6904:     } elsif(!defined($getpropath)) {
1.841     albertel 6905:         my @all_domains = sort(&all_domains());
1.955     raeburn  6906:         foreach my $domain (@all_domains) {
                   6907:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6908:         }
                   6909:         return @all_domains;
                   6910:     } else {
1.800     albertel 6911:         return ('missing domain');
1.275     stredwic 6912:     }
                   6913: }
                   6914: 
                   6915: # --------------------------------------------- GetFileTimestamp
                   6916: # This function utilizes dirlist and returns the date stamp for
                   6917: # when it was last modified.  It will also return an error of -1
                   6918: # if an error occurs
                   6919: 
                   6920: sub GetFileTimestamp {
1.955     raeburn  6921:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 6922:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6923:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  6924:     my ($fileStat) = 
                   6925:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   6926:                                  undef,$getuserdir);
1.275     stredwic 6927:     my @stats = split('&', $fileStat);
                   6928:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6929:         # @stats contains first the filename, then the stat output
                   6930:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6931:     } else {
                   6932:         return -1;
1.253     stredwic 6933:     }
1.26      www      6934: }
                   6935: 
1.712     albertel 6936: sub stat_file {
                   6937:     my ($uri) = @_;
1.787     albertel 6938:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6939: 
1.955     raeburn  6940:     my ($udom,$uname,$file);
1.712     albertel 6941:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6942: 	($udom,$uname,$file) =
1.811     albertel 6943: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6944: 	$file = 'userfiles/'.$file;
                   6945:     }
                   6946:     if ($uri =~ m-^/res/-) {
                   6947: 	($udom,$uname) = 
1.807     albertel 6948: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6949: 	$file = $uri;
                   6950:     }
                   6951: 
                   6952:     if (!$udom || !$uname || !$file) {
                   6953: 	# unable to handle the uri
                   6954: 	return ();
                   6955:     }
1.956     raeburn  6956:     my $getpropath;
                   6957:     if ($file =~ /^userfiles\//) {
                   6958:         $getpropath = 1;
                   6959:     }
1.955     raeburn  6960:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 6961:     my @stats = split('&', $result);
1.721     banghart 6962:     
1.712     albertel 6963:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6964: 	shift(@stats); #filename is first
                   6965: 	return @stats;
                   6966:     }
                   6967:     return ();
                   6968: }
                   6969: 
1.26      www      6970: # -------------------------------------------------------- Value of a Condition
                   6971: 
1.713     albertel 6972: # gets the value of a specific preevaluated condition
                   6973: #    stored in the string  $env{user.state.<cid>}
                   6974: # or looks up a condition reference in the bighash and if if hasn't
                   6975: # already been evaluated recurses into docondval to get the value of
                   6976: # the condition, then memoizing it to 
                   6977: #   $env{user.state.<cid>.<condition>}
1.40      www      6978: sub directcondval {
                   6979:     my $number=shift;
1.620     albertel 6980:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6981: 	&Apache::lonuserstate::evalstate();
                   6982:     }
1.713     albertel 6983:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6984: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6985:     } elsif ($number =~ /^_/) {
                   6986: 	my $sub_condition;
                   6987: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6988: 		&GDBM_READER(),0640)) {
                   6989: 	    $sub_condition=$bighash{'conditions'.$number};
                   6990: 	    untie(%bighash);
                   6991: 	}
                   6992: 	my $value = &docondval($sub_condition);
1.949     raeburn  6993: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 6994: 	return $value;
                   6995:     }
1.620     albertel 6996:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6997:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6998:     } else {
                   6999:        return 2;
                   7000:     }
                   7001: }
                   7002: 
1.713     albertel 7003: # get the collection of conditions for this resource
1.26      www      7004: sub condval {
                   7005:     my $condidx=shift;
1.54      www      7006:     my $allpathcond='';
1.713     albertel 7007:     foreach my $cond (split(/\|/,$condidx)) {
                   7008: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   7009: 	    $allpathcond.=
                   7010: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   7011: 	}
1.191     harris41 7012:     }
1.54      www      7013:     $allpathcond=~s/\|$//;
1.713     albertel 7014:     return &docondval($allpathcond);
                   7015: }
                   7016: 
                   7017: #evaluates an expression of conditions
                   7018: sub docondval {
                   7019:     my ($allpathcond) = @_;
                   7020:     my $result=0;
                   7021:     if ($env{'request.course.id'}
                   7022: 	&& defined($allpathcond)) {
                   7023: 	my $operand='|';
                   7024: 	my @stack;
                   7025: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   7026: 	    if ($chunk eq '(') {
                   7027: 		push @stack,($operand,$result);
                   7028: 	    } elsif ($chunk eq ')') {
                   7029: 		my $before=pop @stack;
                   7030: 		if (pop @stack eq '&') {
                   7031: 		    $result=$result>$before?$before:$result;
                   7032: 		} else {
                   7033: 		    $result=$result>$before?$result:$before;
                   7034: 		}
                   7035: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   7036: 		$operand=$chunk;
                   7037: 	    } else {
                   7038: 		my $new=directcondval($chunk);
                   7039: 		if ($operand eq '&') {
                   7040: 		    $result=$result>$new?$new:$result;
                   7041: 		} else {
                   7042: 		    $result=$result>$new?$result:$new;
                   7043: 		}
                   7044: 	    }
                   7045: 	}
1.26      www      7046:     }
                   7047:     return $result;
1.421     albertel 7048: }
                   7049: 
                   7050: # ---------------------------------------------------- Devalidate courseresdata
                   7051: 
                   7052: sub devalidatecourseresdata {
                   7053:     my ($coursenum,$coursedomain)=@_;
                   7054:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7055:     &devalidate_cache_new('courseres',$hashid);
1.28      www      7056: }
                   7057: 
1.763     www      7058: 
1.200     www      7059: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     7060: #
                   7061: #  Parameters:
                   7062: #      $coursenum    - Number of the course.
                   7063: #      $coursedomain - Domain at which the course was created.
                   7064: #  Returns:
                   7065: #     A hash of the course parameters along (I think) with timestamps
                   7066: #     and version info.
1.877     foxr     7067: 
1.624     albertel 7068: sub get_courseresdata {
                   7069:     my ($coursenum,$coursedomain)=@_;
1.200     www      7070:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   7071:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7072:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 7073:     my %dumpreply;
1.417     albertel 7074:     unless (defined($cached)) {
1.624     albertel 7075: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 7076: 	$result=\%dumpreply;
1.251     albertel 7077: 	my ($tmp) = keys(%dumpreply);
                   7078: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 7079: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 7080: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   7081: 	    return $tmp;
1.416     albertel 7082: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 7083: 	    $result=undef;
1.599     albertel 7084: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 7085: 	}
                   7086:     }
1.624     albertel 7087:     return $result;
                   7088: }
                   7089: 
1.633     albertel 7090: sub devalidateuserresdata {
                   7091:     my ($uname,$udom)=@_;
                   7092:     my $hashid="$udom:$uname";
                   7093:     &devalidate_cache_new('userres',$hashid);
                   7094: }
                   7095: 
1.624     albertel 7096: sub get_userresdata {
                   7097:     my ($uname,$udom)=@_;
                   7098:     #most student don\'t have any data set, check if there is some data
                   7099:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   7100: 
                   7101:     my $hashid="$udom:$uname";
                   7102:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   7103:     if (!defined($cached)) {
                   7104: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   7105: 	$result=\%resourcedata;
                   7106: 	&do_cache_new('userres',$hashid,$result,600);
                   7107:     }
                   7108:     my ($tmp)=keys(%$result);
                   7109:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   7110: 	return $result;
                   7111:     }
                   7112:     #error 2 occurs when the .db doesn't exist
                   7113:     if ($tmp!~/error: 2 /) {
1.672     albertel 7114: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 7115: 		 " Trying to get resource data for ".
                   7116: 		 $uname." at ".$udom.": ".
                   7117: 		 $tmp."</font>");
                   7118:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 7119: 	#&EXT_cache_set($udom,$uname);
                   7120: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 7121: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 7122:     }
                   7123:     return $tmp;
                   7124: }
1.879     foxr     7125: #----------------------------------------------- resdata - return resource data
                   7126: #  Purpose:
                   7127: #    Return resource data for either users or for a course.
                   7128: #  Parameters:
                   7129: #     $name      - Course/user name.
                   7130: #     $domain    - Name of the domain the user/course is registered on.
                   7131: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   7132: #     @which     - Array of names of resources desired.
                   7133: #  Returns:
                   7134: #     The value of the first reasource in @which that is found in the
                   7135: #     resource hash.
                   7136: #  Exceptional Conditions:
                   7137: #     If the $type passed in is not valid (not the string 'course' or 
                   7138: #     'user', an undefined  reference is returned.
                   7139: #     If none of the resources are found, an undef is returned
1.624     albertel 7140: sub resdata {
                   7141:     my ($name,$domain,$type,@which)=@_;
                   7142:     my $result;
                   7143:     if ($type eq 'course') {
                   7144: 	$result=&get_courseresdata($name,$domain);
                   7145:     } elsif ($type eq 'user') {
                   7146: 	$result=&get_userresdata($name,$domain);
                   7147:     }
                   7148:     if (!ref($result)) { return $result; }    
1.251     albertel 7149:     foreach my $item (@which) {
1.927     albertel 7150: 	if (defined($result->{$item->[0]})) {
                   7151: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 7152: 	}
1.250     albertel 7153:     }
1.291     albertel 7154:     return undef;
1.200     www      7155: }
                   7156: 
1.379     matthew  7157: #
                   7158: # EXT resource caching routines
                   7159: #
                   7160: 
                   7161: sub clear_EXT_cache_status {
1.383     albertel 7162:     &delenv('cache.EXT.');
1.379     matthew  7163: }
                   7164: 
                   7165: sub EXT_cache_status {
                   7166:     my ($target_domain,$target_user) = @_;
1.383     albertel 7167:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 7168:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  7169:         # We know already the user has no data
                   7170:         return 1;
                   7171:     } else {
                   7172:         return 0;
                   7173:     }
                   7174: }
                   7175: 
                   7176: sub EXT_cache_set {
                   7177:     my ($target_domain,$target_user) = @_;
1.383     albertel 7178:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  7179:     #&appenv({$cachename => time});
1.379     matthew  7180: }
                   7181: 
1.28      www      7182: # --------------------------------------------------------- Value of a Variable
1.58      www      7183: sub EXT {
1.715     albertel 7184: 
1.395     albertel 7185:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      7186:     unless ($varname) { return ''; }
1.218     albertel 7187:     #get real user name/domain, courseid and symb
                   7188:     my $courseid;
1.359     albertel 7189:     my $publicuser;
1.427     www      7190:     if ($symbparm) {
                   7191: 	$symbparm=&get_symb_from_alias($symbparm);
                   7192:     }
1.218     albertel 7193:     if (!($uname && $udom)) {
1.790     albertel 7194:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 7195:       if (!$symbparm) {	$symbparm=$cursymb; }
                   7196:     } else {
1.620     albertel 7197: 	$courseid=$env{'request.course.id'};
1.218     albertel 7198:     }
1.48      www      7199:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   7200:     my $rest;
1.320     albertel 7201:     if (defined($therest[0])) {
1.48      www      7202:        $rest=join('.',@therest);
                   7203:     } else {
                   7204:        $rest='';
                   7205:     }
1.320     albertel 7206: 
1.57      www      7207:     my $qualifierrest=$qualifier;
                   7208:     if ($rest) { $qualifierrest.='.'.$rest; }
                   7209:     my $spacequalifierrest=$space;
                   7210:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      7211:     if ($realm eq 'user') {
1.48      www      7212: # --------------------------------------------------------------- user.resource
                   7213: 	if ($space eq 'resource') {
1.651     albertel 7214: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   7215: 		  || defined($Apache::lonhomework::parsing_a_task))
                   7216: 		 &&
1.744     albertel 7217: 		 ($symbparm eq &symbread()) ) {	
                   7218: 		# if we are in the middle of processing the resource the
                   7219: 		# get the value we are planning on committing
                   7220:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   7221:                     return $Apache::lonhomework::results{$qualifierrest};
                   7222:                 } else {
                   7223:                     return $Apache::lonhomework::history{$qualifierrest};
                   7224:                 }
1.335     albertel 7225: 	    } else {
1.359     albertel 7226: 		my %restored;
1.620     albertel 7227: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 7228: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   7229: 		} else {
                   7230: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   7231: 		}
1.335     albertel 7232: 		return $restored{$qualifierrest};
                   7233: 	    }
1.48      www      7234: # ----------------------------------------------------------------- user.access
                   7235:         } elsif ($space eq 'access') {
1.218     albertel 7236: 	    # FIXME - not supporting calls for a specific user
1.48      www      7237:             return &allowed($qualifier,$rest);
                   7238: # ------------------------------------------ user.preferences, user.environment
                   7239:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 7240: 	    if (($uname eq $env{'user.name'}) &&
                   7241: 		($udom eq $env{'user.domain'})) {
                   7242: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 7243: 	    } else {
1.359     albertel 7244: 		my %returnhash;
                   7245: 		if (!$publicuser) {
                   7246: 		    %returnhash=&userenvironment($udom,$uname,
                   7247: 						 $qualifierrest);
                   7248: 		}
1.218     albertel 7249: 		return $returnhash{$qualifierrest};
                   7250: 	    }
1.48      www      7251: # ----------------------------------------------------------------- user.course
                   7252:         } elsif ($space eq 'course') {
1.218     albertel 7253: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 7254:             return $env{join('.',('request.course',$qualifier))};
1.48      www      7255: # ------------------------------------------------------------------- user.role
                   7256:         } elsif ($space eq 'role') {
1.218     albertel 7257: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 7258:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      7259:             if ($qualifier eq 'value') {
                   7260: 		return $role;
                   7261:             } elsif ($qualifier eq 'extent') {
                   7262:                 return $where;
                   7263:             }
                   7264: # ----------------------------------------------------------------- user.domain
                   7265:         } elsif ($space eq 'domain') {
1.218     albertel 7266:             return $udom;
1.48      www      7267: # ------------------------------------------------------------------- user.name
                   7268:         } elsif ($space eq 'name') {
1.218     albertel 7269:             return $uname;
1.48      www      7270: # ---------------------------------------------------- Any other user namespace
1.29      www      7271:         } else {
1.359     albertel 7272: 	    my %reply;
                   7273: 	    if (!$publicuser) {
                   7274: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   7275: 	    }
                   7276: 	    return $reply{$qualifierrest};
1.48      www      7277:         }
1.236     www      7278:     } elsif ($realm eq 'query') {
                   7279: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 7280:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   7281: 						[$spacequalifierrest]);
1.620     albertel 7282: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      7283:    } elsif ($realm eq 'request') {
1.48      www      7284: # ------------------------------------------------------------- request.browser
                   7285:         if ($space eq 'browser') {
1.430     www      7286: 	    if ($qualifier eq 'textremote') {
1.676     albertel 7287: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      7288: 		    return 1;
                   7289: 		} else {
                   7290: 		    return 0;
                   7291: 		}
                   7292: 	    } else {
1.620     albertel 7293: 		return $env{'browser.'.$qualifier};
1.430     www      7294: 	    }
1.57      www      7295: # ------------------------------------------------------------ request.filename
                   7296:         } else {
1.620     albertel 7297:             return $env{'request.'.$spacequalifierrest};
1.29      www      7298:         }
1.28      www      7299:     } elsif ($realm eq 'course') {
1.48      www      7300: # ---------------------------------------------------------- course.description
1.620     albertel 7301:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      7302:     } elsif ($realm eq 'resource') {
1.165     www      7303: 
1.620     albertel 7304: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 7305: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   7306: 	}
1.693     albertel 7307: 
                   7308: 	if ($space eq 'title') {
                   7309: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   7310: 	    return &gettitle($symbparm);
                   7311: 	}
                   7312: 	
                   7313: 	if ($space eq 'map') {
                   7314: 	    my ($map) = &decode_symb($symbparm);
                   7315: 	    return &symbread($map);
                   7316: 	}
1.905     albertel 7317: 	if ($space eq 'filename') {
                   7318: 	    if ($symbparm) {
                   7319: 		return &clutter((&decode_symb($symbparm))[2]);
                   7320: 	    }
                   7321: 	    return &hreflocation('',$env{'request.filename'});
                   7322: 	}
1.693     albertel 7323: 
                   7324: 	my ($section, $group, @groups);
1.593     albertel 7325: 	my ($courselevelm,$courselevel);
1.539     albertel 7326: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7327: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      7328: 
1.218     albertel 7329: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      7330: 
1.60      www      7331: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 7332: 	    my $symbp=$symbparm;
1.735     albertel 7333: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 7334: 
                   7335: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   7336: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   7337: 
1.620     albertel 7338: 	    if (($env{'user.name'} eq $uname) &&
                   7339: 		($env{'user.domain'} eq $udom)) {
                   7340: 		$section=$env{'request.course.sec'};
1.733     raeburn  7341:                 @groups = split(/:/,$env{'request.course.groups'});  
                   7342:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 7343: 	    } else {
1.539     albertel 7344: 		if (! defined($usection)) {
1.551     albertel 7345: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 7346: 		} else {
                   7347: 		    $section = $usection;
                   7348: 		}
1.733     raeburn  7349:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 7350: 	    }
                   7351: 
                   7352: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   7353: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   7354: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   7355: 
1.593     albertel 7356: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 7357: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 7358: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      7359: 
1.60      www      7360: # ----------------------------------------------------------- first, check user
1.624     albertel 7361: 
                   7362: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 7363: 				       ([$courselevelr,'resource'],
                   7364: 					[$courselevelm,'map'     ],
                   7365: 					[$courselevel, 'course'  ]));
1.931     albertel 7366: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      7367: 
1.594     albertel 7368: # ------------------------------------------------ second, check some of course
1.684     raeburn  7369:             my $coursereply;
1.691     raeburn  7370:             if (@groups > 0) {
                   7371:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   7372:                                        $mapparm,$spacequalifierrest);
1.927     albertel 7373:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  7374:             }
1.96      www      7375: 
1.684     raeburn  7376: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 7377: 				  $env{'course.'.$courseid.'.domain'},
                   7378: 				  'course',
                   7379: 				  ([$seclevelr,   'resource'],
                   7380: 				   [$seclevelm,   'map'     ],
                   7381: 				   [$seclevel,    'course'  ],
                   7382: 				   [$courselevelr,'resource']));
                   7383: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      7384: 
1.60      www      7385: # ------------------------------------------------------ third, check map parms
1.218     albertel 7386: 	    my %parmhash=();
                   7387: 	    my $thisparm='';
                   7388: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 7389: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 7390: 		    &GDBM_READER(),0640)) {
1.218     albertel 7391: 		$thisparm=$parmhash{$symbparm};
                   7392: 		untie(%parmhash);
                   7393: 	    }
1.927     albertel 7394: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 7395: 	}
1.594     albertel 7396: # ------------------------------------------ fourth, look in resource metadata
1.71      www      7397: 
1.218     albertel 7398: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 7399: 	my $filename;
                   7400: 	if (!$symbparm) { $symbparm=&symbread(); }
                   7401: 	if ($symbparm) {
1.409     www      7402: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 7403: 	} else {
1.620     albertel 7404: 	    $filename=$env{'request.filename'};
1.282     albertel 7405: 	}
                   7406: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 7407: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 7408: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 7409: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      7410: 
1.927     albertel 7411: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 7412: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7413: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 7414: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   7415: 				     $env{'course.'.$courseid.'.domain'},
                   7416: 				     'course',
1.927     albertel 7417: 				     ([$courselevelm,'map'   ],
                   7418: 				      [$courselevel, 'course']));
                   7419: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 7420: 	}
1.145     www      7421: # ------------------------------------------------------------------ Cascade up
1.218     albertel 7422: 	unless ($space eq '0') {
1.336     albertel 7423: 	    my @parts=split(/_/,$space);
                   7424: 	    my $id=pop(@parts);
                   7425: 	    my $part=join('_',@parts);
                   7426: 	    if ($part eq '') { $part='0'; }
1.927     albertel 7427: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 7428: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  7429: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 7430: 	}
1.395     albertel 7431: 	if ($recurse) { return undef; }
                   7432: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 7433: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      7434: # ---------------------------------------------------- Any other user namespace
                   7435:     } elsif ($realm eq 'environment') {
                   7436: # ----------------------------------------------------------------- environment
1.620     albertel 7437: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   7438: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 7439: 	} else {
1.770     albertel 7440: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   7441: 		return '';
                   7442: 	    }
1.219     albertel 7443: 	    my %returnhash=&userenvironment($udom,$uname,
                   7444: 					    $spacequalifierrest);
                   7445: 	    return $returnhash{$spacequalifierrest};
                   7446: 	}
1.28      www      7447:     } elsif ($realm eq 'system') {
1.48      www      7448: # ----------------------------------------------------------------- system.time
                   7449: 	if ($space eq 'time') {
                   7450: 	    return time;
                   7451:         }
1.696     albertel 7452:     } elsif ($realm eq 'server') {
                   7453: # ----------------------------------------------------------------- system.time
                   7454: 	if ($space eq 'name') {
                   7455: 	    return $ENV{'SERVER_NAME'};
                   7456:         }
1.28      www      7457:     }
1.48      www      7458:     return '';
1.61      www      7459: }
                   7460: 
1.927     albertel 7461: sub get_reply {
                   7462:     my ($reply_value) = @_;
1.940     raeburn  7463:     if (ref($reply_value) eq 'ARRAY') {
                   7464:         if (wantarray) {
                   7465: 	    return @$reply_value;
                   7466:         }
                   7467:         return $reply_value->[0];
                   7468:     } else {
                   7469:         return $reply_value;
1.927     albertel 7470:     }
                   7471: }
                   7472: 
1.691     raeburn  7473: sub check_group_parms {
                   7474:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   7475:     my @groupitems = ();
                   7476:     my $resultitem;
1.927     albertel 7477:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  7478:     foreach my $group (@{$groups}) {
                   7479:         foreach my $level (@levels) {
1.927     albertel 7480:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   7481:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  7482:         }
                   7483:     }
                   7484:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   7485:                             $env{'course.'.$courseid.'.domain'},
                   7486:                                      'course',@groupitems);
                   7487:     return $coursereply;
                   7488: }
                   7489: 
                   7490: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  7491:     my ($courseid,@groups) = @_;
                   7492:     @groups = sort(@groups);
1.691     raeburn  7493:     return @groups;
                   7494: }
                   7495: 
1.395     albertel 7496: sub packages_tab_default {
                   7497:     my ($uri,$varname)=@_;
                   7498:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 7499: 
                   7500:     my (@extension,@specifics,$do_default);
                   7501:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 7502: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 7503: 	if ($pack_type eq 'default') {
                   7504: 	    $do_default=1;
                   7505: 	} elsif ($pack_type eq 'extension') {
                   7506: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 7507: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 7508: 	    # only look at packages defaults for packages that this id is
1.738     albertel 7509: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   7510: 	}
                   7511:     }
                   7512:     # first look for a package that matches the requested part id
                   7513:     foreach my $package (@specifics) {
                   7514: 	my (undef,$pack_type,$pack_part)=@{$package};
                   7515: 	next if ($pack_part ne $part);
                   7516: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7517: 	    return $packagetab{"$pack_type&$name&default"};
                   7518: 	}
                   7519:     }
                   7520:     # look for any possible matching non extension_ package
                   7521:     foreach my $package (@specifics) {
                   7522: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 7523: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7524: 	    return $packagetab{"$pack_type&$name&default"};
                   7525: 	}
1.585     albertel 7526: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 7527: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   7528: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 7529: 	}
                   7530:     }
1.738     albertel 7531:     # look for any posible extension_ match
                   7532:     foreach my $package (@extension) {
                   7533: 	my ($package,$pack_type)=@{$package};
                   7534: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7535: 	    return $packagetab{"$pack_type&$name&default"};
                   7536: 	}
                   7537: 	if (defined($packagetab{$package."&$name&default"})) {
                   7538: 	    return $packagetab{$package."&$name&default"};
                   7539: 	}
                   7540:     }
                   7541:     # look for a global default setting
                   7542:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   7543: 	return $packagetab{"default&$name&default"};
                   7544:     }
1.395     albertel 7545:     return undef;
                   7546: }
                   7547: 
1.334     albertel 7548: sub add_prefix_and_part {
                   7549:     my ($prefix,$part)=@_;
                   7550:     my $keyroot;
                   7551:     if (defined($prefix) && $prefix !~ /^__/) {
                   7552: 	# prefix that has a part already
                   7553: 	$keyroot=$prefix;
                   7554:     } elsif (defined($prefix)) {
                   7555: 	# prefix that is missing a part
                   7556: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   7557:     } else {
                   7558: 	# no prefix at all
                   7559: 	if (defined($part)) { $keyroot='_'.$part; }
                   7560:     }
                   7561:     return $keyroot;
                   7562: }
                   7563: 
1.71      www      7564: # ---------------------------------------------------------------- Get metadata
                   7565: 
1.599     albertel 7566: my %metaentry;
1.71      www      7567: sub metadata {
1.176     www      7568:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      7569:     $uri=&declutter($uri);
1.288     albertel 7570:     # if it is a non metadata possible uri return quickly
1.529     albertel 7571:     if (($uri eq '') || 
                   7572: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 7573: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 7574:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   7575: 	return undef;
                   7576:     }
                   7577:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   7578: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 7579: 	return undef;
1.288     albertel 7580:     }
1.73      www      7581:     my $filename=$uri;
                   7582:     $uri=~s/\.meta$//;
1.172     www      7583: #
                   7584: # Is the metadata already cached?
1.177     www      7585: # Look at timestamp of caching
1.172     www      7586: # Everything is cached by the main uri, libraries are never directly cached
                   7587: #
1.428     albertel 7588:     if (!defined($liburi)) {
1.599     albertel 7589: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 7590: 	if (defined($cached)) { return $result->{':'.$what}; }
                   7591:     }
                   7592:     {
1.172     www      7593: #
                   7594: # Is this a recursive call for a library?
                   7595: #
1.599     albertel 7596: #	if (! exists($metacache{$uri})) {
                   7597: #	    $metacache{$uri}={};
                   7598: #	}
1.924     albertel 7599: 	my $cachetime = 60*60;
1.171     www      7600:         if ($liburi) {
                   7601: 	    $liburi=&declutter($liburi);
                   7602:             $filename=$liburi;
1.401     bowersj2 7603:         } else {
1.599     albertel 7604: 	    &devalidate_cache_new('meta',$uri);
                   7605: 	    undef(%metaentry);
1.401     bowersj2 7606: 	}
1.140     www      7607:         my %metathesekeys=();
1.73      www      7608:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 7609: 	my $metastring;
1.924     albertel 7610: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 7611: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 7612: 	    $metastring = 
1.929     albertel 7613: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 7614: 					  ('grade_target' => 'meta'));
                   7615: 	    $cachetime = 1; # only want this cached in the child not long term
                   7616: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 7617: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 7618: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 7619: 	    $metastring=&getfile($file);
1.489     albertel 7620: 	}
1.208     albertel 7621:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      7622:         my $token;
1.140     www      7623:         undef %metathesekeys;
1.71      www      7624:         while ($token=$parser->get_token) {
1.339     albertel 7625: 	    if ($token->[0] eq 'S') {
                   7626: 		if (defined($token->[2]->{'package'})) {
1.172     www      7627: #
                   7628: # This is a package - get package info
                   7629: #
1.339     albertel 7630: 		    my $package=$token->[2]->{'package'};
                   7631: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7632: 		    if (defined($token->[2]->{'id'})) { 
                   7633: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7634: 		    }
1.599     albertel 7635: 		    if ($metaentry{':packages'}) {
                   7636: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7637: 		    } else {
1.599     albertel 7638: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7639: 		    }
1.736     albertel 7640: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7641: 			my $part=$keyroot;
                   7642: 			$part=~s/^\_//;
1.736     albertel 7643: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7644: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7645: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7646: 			    # ignore package.tab specified default values
                   7647:                             # here &package_tab_default() will fetch those
                   7648: 			    if ($subp eq 'default') { next; }
1.736     albertel 7649: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7650: 			    my $unikey;
                   7651: 			    if ($pack =~ /_0$/) {
                   7652: 				$unikey='parameter_0_'.$name;
                   7653: 				$part=0;
                   7654: 			    } else {
                   7655: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7656: 			    }
1.339     albertel 7657: 			    if ($subp eq 'display') {
                   7658: 				$value.=' [Part: '.$part.']';
                   7659: 			    }
1.599     albertel 7660: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7661: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7662: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7663: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7664: 			    }
1.599     albertel 7665: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7666: 				$metaentry{':'.$unikey}=
                   7667: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7668: 			    }
1.339     albertel 7669: 			}
                   7670: 		    }
                   7671: 		} else {
1.172     www      7672: #
                   7673: # This is not a package - some other kind of start tag
1.339     albertel 7674: #
                   7675: 		    my $entry=$token->[1];
                   7676: 		    my $unikey;
                   7677: 		    if ($entry eq 'import') {
                   7678: 			$unikey='';
                   7679: 		    } else {
                   7680: 			$unikey=$entry;
                   7681: 		    }
                   7682: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7683: 
                   7684: 		    if (defined($token->[2]->{'id'})) { 
                   7685: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7686: 		    }
1.175     www      7687: 
1.339     albertel 7688: 		    if ($entry eq 'import') {
1.175     www      7689: #
                   7690: # Importing a library here
1.339     albertel 7691: #
                   7692: 			if ($depthcount<20) {
                   7693: 			    my $location=$parser->get_text('/import');
                   7694: 			    my $dir=$filename;
                   7695: 			    $dir=~s|[^/]*$||;
                   7696: 			    $location=&filelocation($dir,$location);
1.736     albertel 7697: 			    my $metadata = 
                   7698: 				&metadata($uri,'keys', $location,$unikey,
                   7699: 					  $depthcount+1);
                   7700: 			    foreach my $meta (split(',',$metadata)) {
                   7701: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7702: 				$metathesekeys{$meta}=1;
1.339     albertel 7703: 			    }
                   7704: 			}
                   7705: 		    } else { 
                   7706: 			
                   7707: 			if (defined($token->[2]->{'name'})) { 
                   7708: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7709: 			}
                   7710: 			$metathesekeys{$unikey}=1;
1.736     albertel 7711: 			foreach my $param (@{$token->[3]}) {
                   7712: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7713: 				$token->[2]->{$param};
1.339     albertel 7714: 			}
                   7715: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7716: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7717: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7718: 		 # only ws inside the tag, and not in default, so use default
                   7719: 		 # as value
1.599     albertel 7720: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7721: 			} elsif ( $internaltext =~ /\S/ ) {
                   7722: 		  # something interesting inside the tag
                   7723: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7724: 			} else {
1.908     albertel 7725: 		  # no interesting values, don't set a default
1.339     albertel 7726: 			}
1.172     www      7727: # end of not-a-package not-a-library import
1.339     albertel 7728: 		    }
1.172     www      7729: # end of not-a-package start tag
1.339     albertel 7730: 		}
1.172     www      7731: # the next is the end of "start tag"
1.339     albertel 7732: 	    }
                   7733: 	}
1.483     albertel 7734: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7735: 	$extension = lc($extension);
                   7736: 	if ($extension eq 'htm') { $extension='html'; }
                   7737: 
1.737     albertel 7738: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7739: 	    #no specific packages #how's our extension
                   7740: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7741: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7742: 					 \%metathesekeys);
                   7743: 	}
1.883     albertel 7744: 
                   7745: 	if (!exists($metaentry{':packages'})
                   7746: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7747: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7748: 		#no specific packages well let's get default then
                   7749: 		if ($key!~/^default&/) { next; }
1.488     albertel 7750: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7751: 					     \%metathesekeys);
                   7752: 	    }
                   7753: 	}
1.338     www      7754: # are there custom rights to evaluate
1.599     albertel 7755: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7756: 
1.338     www      7757:     #
                   7758:     # Importing a rights file here
1.339     albertel 7759:     #
                   7760: 	    unless ($depthcount) {
1.599     albertel 7761: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7762: 		my $dir=$filename;
                   7763: 		$dir=~s|[^/]*$||;
                   7764: 		$location=&filelocation($dir,$location);
1.736     albertel 7765: 		my $rights_metadata =
                   7766: 		    &metadata($uri,'keys',$location,'_rights',
                   7767: 			      $depthcount+1);
                   7768: 		foreach my $rights (split(',',$rights_metadata)) {
                   7769: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7770: 		    $metathesekeys{$rights}=1;
1.339     albertel 7771: 		}
                   7772: 	    }
                   7773: 	}
1.737     albertel 7774: 	# uniqifiy package listing
                   7775: 	my %seen;
                   7776: 	my @uniq_packages =
                   7777: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7778: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7779: 
                   7780: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7781: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7782: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7783: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7784: # this is the end of "was not already recently cached
1.71      www      7785:     }
1.599     albertel 7786:     return $metaentry{':'.$what};
1.261     albertel 7787: }
                   7788: 
1.488     albertel 7789: sub metadata_create_package_def {
1.483     albertel 7790:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7791:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7792:     if ($subp eq 'default') { next; }
                   7793:     
1.599     albertel 7794:     if (defined($metaentry{':packages'})) {
                   7795: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7796:     } else {
1.599     albertel 7797: 	$metaentry{':packages'}=$package;
1.483     albertel 7798:     }
                   7799:     my $value=$packagetab{$key};
                   7800:     my $unikey;
                   7801:     $unikey='parameter_0_'.$name;
1.599     albertel 7802:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7803:     $$metathesekeys{$unikey}=1;
1.599     albertel 7804:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7805: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7806:     }
1.599     albertel 7807:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7808: 	$metaentry{':'.$unikey}=
                   7809: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7810:     }
                   7811: }
                   7812: 
1.261     albertel 7813: sub metadata_generate_part0 {
                   7814:     my ($metadata,$metacache,$uri) = @_;
                   7815:     my %allnames;
1.737     albertel 7816:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7817: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7818: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7819: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7820: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7821: 	    $allnames{$name}=$part;
                   7822: 	  }
                   7823: 	}
                   7824:     }
                   7825:     foreach my $name (keys(%allnames)) {
                   7826:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7827:       my $key=":parameter_0_$name";
1.261     albertel 7828:       $$metacache{"$key.part"}='0';
                   7829:       $$metacache{"$key.name"}=$name;
1.428     albertel 7830:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7831: 					   $allnames{$name}.'_'.$name.
                   7832: 					   '.type'};
1.428     albertel 7833:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7834: 			     '.display'};
1.644     www      7835:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7836:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7837:       $$metacache{"$key.display"}=$olddis;
                   7838:     }
1.71      www      7839: }
                   7840: 
1.764     albertel 7841: # ------------------------------------------------------ Devalidate title cache
                   7842: 
                   7843: sub devalidate_title_cache {
                   7844:     my ($url)=@_;
                   7845:     if (!$env{'request.course.id'}) { return; }
                   7846:     my $symb=&symbread($url);
                   7847:     if (!$symb) { return; }
                   7848:     my $key=$env{'request.course.id'}."\0".$symb;
                   7849:     &devalidate_cache_new('title',$key);
                   7850: }
                   7851: 
1.301     www      7852: # ------------------------------------------------- Get the title of a resource
                   7853: 
                   7854: sub gettitle {
                   7855:     my $urlsymb=shift;
                   7856:     my $symb=&symbread($urlsymb);
1.534     albertel 7857:     if ($symb) {
1.620     albertel 7858: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7859: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7860: 	if (defined($cached)) { 
                   7861: 	    return $result;
                   7862: 	}
1.534     albertel 7863: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7864: 	my $title='';
1.907     albertel 7865: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7866: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7867: 	} else {
                   7868: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7869: 		    &GDBM_READER(),0640)) {
                   7870: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7871: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7872: 		untie(%bighash);
                   7873: 	    }
1.534     albertel 7874: 	}
                   7875: 	$title=~s/\&colon\;/\:/gs;
                   7876: 	if ($title) {
1.599     albertel 7877: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7878: 	}
                   7879: 	$urlsymb=$url;
                   7880:     }
                   7881:     my $title=&metadata($urlsymb,'title');
                   7882:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7883:     return $title;
1.301     www      7884: }
1.613     albertel 7885: 
1.614     albertel 7886: sub get_slot {
                   7887:     my ($which,$cnum,$cdom)=@_;
                   7888:     if (!$cnum || !$cdom) {
1.790     albertel 7889: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7890: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7891: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7892:     }
1.703     albertel 7893:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7894:     my %slotinfo;
                   7895:     if (exists($remembered{$key})) {
                   7896: 	$slotinfo{$which} = $remembered{$key};
                   7897:     } else {
                   7898: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7899: 	&Apache::lonhomework::showhash(%slotinfo);
                   7900: 	my ($tmp)=keys(%slotinfo);
                   7901: 	if ($tmp=~/^error:/) { return (); }
                   7902: 	$remembered{$key} = $slotinfo{$which};
                   7903:     }
1.616     albertel 7904:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7905: 	return %{$slotinfo{$which}};
                   7906:     }
                   7907:     return $slotinfo{$which};
1.614     albertel 7908: }
1.31      www      7909: # ------------------------------------------------- Update symbolic store links
                   7910: 
                   7911: sub symblist {
                   7912:     my ($mapname,%newhash)=@_;
1.438     www      7913:     $mapname=&deversion(&declutter($mapname));
1.31      www      7914:     my %hash;
1.620     albertel 7915:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7916:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7917:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  7918: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 7919: 		next if ($url eq 'last_known'
                   7920: 			 && $env{'form.no_update_last_known'});
                   7921: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7922: 						    $newhash{$url}->[1],
                   7923: 						    $newhash{$url}->[0]);
1.191     harris41 7924:             }
1.31      www      7925:             if (untie(%hash)) {
                   7926: 		return 'ok';
                   7927:             }
                   7928:         }
                   7929:     }
                   7930:     return 'error';
1.212     www      7931: }
                   7932: 
                   7933: # --------------------------------------------------------------- Verify a symb
                   7934: 
                   7935: sub symbverify {
1.510     www      7936:     my ($symb,$thisurl)=@_;
                   7937:     my $thisfn=$thisurl;
1.439     www      7938:     $thisfn=&declutter($thisfn);
1.215     www      7939: # direct jump to resource in page or to a sequence - will construct own symbs
                   7940:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7941: # check URL part
1.409     www      7942:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7943: 
1.431     www      7944:     unless ($url eq $thisfn) { return 0; }
1.213     www      7945: 
1.216     www      7946:     $symb=&symbclean($symb);
1.510     www      7947:     $thisurl=&deversion($thisurl);
1.439     www      7948:     $thisfn=&deversion($thisfn);
1.213     www      7949: 
                   7950:     my %bighash;
                   7951:     my $okay=0;
1.431     www      7952: 
1.620     albertel 7953:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7954:                             &GDBM_READER(),0640)) {
1.510     www      7955:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7956:         unless ($ids) { 
1.510     www      7957:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7958:         }
                   7959:         if ($ids) {
                   7960: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7961: 	    foreach my $id (split(/\,/,$ids)) {
                   7962: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7963:                if (
                   7964:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7965:    eq $symb) { 
1.620     albertel 7966: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7967: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7968: 		       $okay=1; 
                   7969: 		   }
                   7970: 	       }
1.216     www      7971: 	   }
                   7972:         }
1.213     www      7973: 	untie(%bighash);
                   7974:     }
                   7975:     return $okay;
1.31      www      7976: }
                   7977: 
1.210     www      7978: # --------------------------------------------------------------- Clean-up symb
                   7979: 
                   7980: sub symbclean {
                   7981:     my $symb=shift;
1.568     albertel 7982:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7983: # remove version from map
                   7984:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7985: 
1.210     www      7986: # remove version from URL
                   7987:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7988: 
1.507     www      7989: # remove wrapper
                   7990: 
1.510     www      7991:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7992:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7993:     return $symb;
1.409     www      7994: }
                   7995: 
                   7996: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7997: 
                   7998: sub encode_symb {
                   7999:     my ($map,$resid,$url)=@_;
                   8000:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   8001: }
1.409     www      8002: 
                   8003: sub decode_symb {
1.568     albertel 8004:     my $symb=shift;
                   8005:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   8006:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      8007:     return (&fixversion($map),$resid,&fixversion($url));
                   8008: }
                   8009: 
                   8010: sub fixversion {
                   8011:     my $fn=shift;
1.609     banghart 8012:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      8013:     my %bighash;
                   8014:     my $uri=&clutter($fn);
1.620     albertel 8015:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      8016: # is this cached?
1.599     albertel 8017:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      8018:     if (defined($cached)) { return $result; }
                   8019: # unfortunately not cached, or expired
1.620     albertel 8020:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      8021: 	    &GDBM_READER(),0640)) {
                   8022:  	if ($bighash{'version_'.$uri}) {
                   8023:  	    my $version=$bighash{'version_'.$uri};
1.444     www      8024:  	    unless (($version eq 'mostrecent') || 
                   8025: 		    ($version==&getversion($uri))) {
1.440     www      8026:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   8027:  	    }
                   8028:  	}
                   8029:  	untie %bighash;
1.413     www      8030:     }
1.599     albertel 8031:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      8032: }
                   8033: 
                   8034: sub deversion {
                   8035:     my $url=shift;
                   8036:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   8037:     return $url;
1.210     www      8038: }
                   8039: 
1.31      www      8040: # ------------------------------------------------------ Return symb list entry
                   8041: 
                   8042: sub symbread {
1.249     www      8043:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 8044:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 8045:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      8046: # no filename provided? try from environment
1.44      www      8047:     unless ($thisfn) {
1.620     albertel 8048:         if ($env{'request.symb'}) {
                   8049: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 8050: 	}
1.620     albertel 8051: 	$thisfn=$env{'request.filename'};
1.44      www      8052:     }
1.569     albertel 8053:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      8054: # is that filename actually a symb? Verify, clean, and return
                   8055:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 8056: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 8057: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 8058: 	}
1.242     www      8059:     }
1.44      www      8060:     $thisfn=declutter($thisfn);
1.31      www      8061:     my %hash;
1.37      www      8062:     my %bighash;
                   8063:     my $syval='';
1.620     albertel 8064:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  8065:         my $targetfn = $thisfn;
1.609     banghart 8066:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  8067:             $targetfn = 'adm/wrapper/'.$thisfn;
                   8068:         }
1.687     albertel 8069: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   8070: 	    $targetfn=$1;
                   8071: 	}
1.620     albertel 8072:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8073:                       &GDBM_READER(),0640)) {
1.481     raeburn  8074: 	    $syval=$hash{$targetfn};
1.37      www      8075:             untie(%hash);
                   8076:         }
                   8077: # ---------------------------------------------------------- There was an entry
                   8078:         if ($syval) {
1.601     albertel 8079: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 8080: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  8081: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 8082: 		    #return $env{$cache_str}='';
1.601     albertel 8083: 		#}    
                   8084: 		#$syval.=$1;
                   8085: 	    #}
1.37      www      8086:         } else {
                   8087: # ------------------------------------------------------- Was not in symb table
1.620     albertel 8088:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8089:                             &GDBM_READER(),0640)) {
1.37      www      8090: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      8091:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      8092:               unless ($ids) { 
                   8093:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      8094:               }
                   8095:               unless ($ids) {
                   8096: # alias?
                   8097: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      8098:               }
1.37      www      8099:               if ($ids) {
                   8100: # ------------------------------------------------------------------- Has ID(s)
                   8101:                  my @possibilities=split(/\,/,$ids);
1.39      www      8102:                  if ($#possibilities==0) {
                   8103: # ----------------------------------------------- There is only one possibility
1.37      www      8104: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 8105: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   8106: 						    $resid,$thisfn);
1.249     www      8107:                  } elsif (!$donotrecurse) {
1.39      www      8108: # ------------------------------------------ There is more than one possibility
                   8109:                      my $realpossible=0;
1.800     albertel 8110:                      foreach my $id (@possibilities) {
                   8111: 			 my $file=$bighash{'src_'.$id};
1.39      www      8112:                          if (&allowed('bre',$file)) {
1.800     albertel 8113:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      8114:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   8115: 				$realpossible++;
1.626     albertel 8116:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   8117: 						    $resid,$thisfn);
1.39      www      8118:                             }
                   8119: 			 }
1.191     harris41 8120:                      }
1.39      www      8121: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      8122:                  } else {
                   8123:                      $syval='';
1.37      www      8124:                  }
                   8125: 	      }
                   8126:               untie(%bighash)
1.481     raeburn  8127:            }
1.31      www      8128:         }
1.62      www      8129:         if ($syval) {
1.620     albertel 8130: 	    return $env{$cache_str}=$syval;
1.62      www      8131:         }
1.31      www      8132:     }
1.949     raeburn  8133:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 8134:     return $env{$cache_str}='';
1.31      www      8135: }
                   8136: 
                   8137: # ---------------------------------------------------------- Return random seed
                   8138: 
1.32      www      8139: sub numval {
                   8140:     my $txt=shift;
                   8141:     $txt=~tr/A-J/0-9/;
                   8142:     $txt=~tr/a-j/0-9/;
                   8143:     $txt=~tr/K-T/0-9/;
                   8144:     $txt=~tr/k-t/0-9/;
                   8145:     $txt=~tr/U-Z/0-5/;
                   8146:     $txt=~tr/u-z/0-5/;
                   8147:     $txt=~s/\D//g;
1.564     albertel 8148:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      8149:     return int($txt);
1.368     albertel 8150: }
                   8151: 
1.484     albertel 8152: sub numval2 {
                   8153:     my $txt=shift;
                   8154:     $txt=~tr/A-J/0-9/;
                   8155:     $txt=~tr/a-j/0-9/;
                   8156:     $txt=~tr/K-T/0-9/;
                   8157:     $txt=~tr/k-t/0-9/;
                   8158:     $txt=~tr/U-Z/0-5/;
                   8159:     $txt=~tr/u-z/0-5/;
                   8160:     $txt=~s/\D//g;
                   8161:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   8162:     my $total;
                   8163:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 8164:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 8165:     return int($total);
                   8166: }
                   8167: 
1.575     albertel 8168: sub numval3 {
                   8169:     use integer;
                   8170:     my $txt=shift;
                   8171:     $txt=~tr/A-J/0-9/;
                   8172:     $txt=~tr/a-j/0-9/;
                   8173:     $txt=~tr/K-T/0-9/;
                   8174:     $txt=~tr/k-t/0-9/;
                   8175:     $txt=~tr/U-Z/0-5/;
                   8176:     $txt=~tr/u-z/0-5/;
                   8177:     $txt=~s/\D//g;
                   8178:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   8179:     my $total;
                   8180:     foreach my $val (@txts) { $total+=$val; }
                   8181:     if ($_64bit) { $total=(($total<<32)>>32); }
                   8182:     return $total;
                   8183: }
                   8184: 
1.675     albertel 8185: sub digest {
                   8186:     my ($data)=@_;
                   8187:     my $digest=&Digest::MD5::md5($data);
                   8188:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   8189:     my ($e,$f);
                   8190:     {
                   8191:         use integer;
                   8192:         $e=($a+$b);
                   8193:         $f=($c+$d);
                   8194:         if ($_64bit) {
                   8195:             $e=(($e<<32)>>32);
                   8196:             $f=(($f<<32)>>32);
                   8197:         }
                   8198:     }
                   8199:     if (wantarray) {
                   8200: 	return ($e,$f);
                   8201:     } else {
                   8202: 	my $g;
                   8203: 	{
                   8204: 	    use integer;
                   8205: 	    $g=($e+$f);
                   8206: 	    if ($_64bit) {
                   8207: 		$g=(($g<<32)>>32);
                   8208: 	    }
                   8209: 	}
                   8210: 	return $g;
                   8211:     }
                   8212: }
                   8213: 
1.368     albertel 8214: sub latest_rnd_algorithm_id {
1.675     albertel 8215:     return '64bit5';
1.366     albertel 8216: }
1.32      www      8217: 
1.503     albertel 8218: sub get_rand_alg {
                   8219:     my ($courseid)=@_;
1.790     albertel 8220:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 8221:     if ($courseid) {
1.620     albertel 8222: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 8223:     }
                   8224:     return &latest_rnd_algorithm_id();
                   8225: }
                   8226: 
1.562     albertel 8227: sub validCODE {
                   8228:     my ($CODE)=@_;
                   8229:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   8230:     return 0;
                   8231: }
                   8232: 
1.491     albertel 8233: sub getCODE {
1.620     albertel 8234:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 8235:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   8236: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   8237: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 8238: 	return $Apache::lonhomework::history{'resource.CODE'};
                   8239:     }
                   8240:     return undef;
                   8241: }
                   8242: 
1.31      www      8243: sub rndseed {
1.155     albertel 8244:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 8245:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 8246:     if (!defined($symb)) {
1.366     albertel 8247: 	unless ($symb=$wsymb) { return time; }
                   8248:     }
                   8249:     if (!$courseid) { $courseid=$wcourseid; }
                   8250:     if (!$domain) { $domain=$wdomain; }
                   8251:     if (!$username) { $username=$wusername }
1.503     albertel 8252:     my $which=&get_rand_alg();
1.803     albertel 8253: 
1.491     albertel 8254:     if (defined(&getCODE())) {
1.675     albertel 8255: 	if ($which eq '64bit5') {
                   8256: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   8257: 	} elsif ($which eq '64bit4') {
1.575     albertel 8258: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   8259: 	} else {
                   8260: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   8261: 	}
1.675     albertel 8262:     } elsif ($which eq '64bit5') {
                   8263: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 8264:     } elsif ($which eq '64bit4') {
                   8265: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 8266:     } elsif ($which eq '64bit3') {
                   8267: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 8268:     } elsif ($which eq '64bit2') {
                   8269: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 8270:     } elsif ($which eq '64bit') {
                   8271: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   8272:     }
                   8273:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   8274: }
                   8275: 
                   8276: sub rndseed_32bit {
                   8277:     my ($symb,$courseid,$domain,$username)=@_;
                   8278:     {
                   8279: 	use integer;
                   8280: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   8281: 	my $symbseed=numval($symb) << 22;
                   8282: 	my $namechck=unpack("%32C*",$username) << 17;
                   8283: 	my $nameseed=numval($username) << 12;
                   8284: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   8285: 	my $courseseed=unpack("%32C*",$courseid);
                   8286: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 8287: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8288: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8289: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 8290: 	return $num;
                   8291:     }
                   8292: }
                   8293: 
                   8294: sub rndseed_64bit {
                   8295:     my ($symb,$courseid,$domain,$username)=@_;
                   8296:     {
                   8297: 	use integer;
                   8298: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   8299: 	my $symbseed=numval($symb) << 10;
                   8300: 	my $namechck=unpack("%32S*",$username);
                   8301: 	
                   8302: 	my $nameseed=numval($username) << 21;
                   8303: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   8304: 	my $courseseed=unpack("%32S*",$courseid);
                   8305: 	
                   8306: 	my $num1=$symbchck+$symbseed+$namechck;
                   8307: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8308: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8309: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8310: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 8311: 	return "$num1,$num2";
1.155     albertel 8312:     }
1.366     albertel 8313: }
                   8314: 
1.443     albertel 8315: sub rndseed_64bit2 {
                   8316:     my ($symb,$courseid,$domain,$username)=@_;
                   8317:     {
                   8318: 	use integer;
                   8319: 	# strings need to be an even # of cahracters long, it it is odd the
                   8320:         # last characters gets thrown away
                   8321: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8322: 	my $symbseed=numval($symb) << 10;
                   8323: 	my $namechck=unpack("%32S*",$username.' ');
                   8324: 	
                   8325: 	my $nameseed=numval($username) << 21;
1.501     albertel 8326: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8327: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8328: 	
                   8329: 	my $num1=$symbchck+$symbseed+$namechck;
                   8330: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8331: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8332: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 8333: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 8334: 	return "$num1,$num2";
                   8335:     }
                   8336: }
                   8337: 
                   8338: sub rndseed_64bit3 {
                   8339:     my ($symb,$courseid,$domain,$username)=@_;
                   8340:     {
                   8341: 	use integer;
                   8342: 	# strings need to be an even # of cahracters long, it it is odd the
                   8343:         # last characters gets thrown away
                   8344: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8345: 	my $symbseed=numval2($symb) << 10;
                   8346: 	my $namechck=unpack("%32S*",$username.' ');
                   8347: 	
                   8348: 	my $nameseed=numval2($username) << 21;
1.443     albertel 8349: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8350: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8351: 	
                   8352: 	my $num1=$symbchck+$symbseed+$namechck;
                   8353: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8354: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8355: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 8356: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8357: 	
1.503     albertel 8358: 	return "$num1:$num2";
1.443     albertel 8359:     }
                   8360: }
                   8361: 
1.575     albertel 8362: sub rndseed_64bit4 {
                   8363:     my ($symb,$courseid,$domain,$username)=@_;
                   8364:     {
                   8365: 	use integer;
                   8366: 	# strings need to be an even # of cahracters long, it it is odd the
                   8367:         # last characters gets thrown away
                   8368: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8369: 	my $symbseed=numval3($symb) << 10;
                   8370: 	my $namechck=unpack("%32S*",$username.' ');
                   8371: 	
                   8372: 	my $nameseed=numval3($username) << 21;
                   8373: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8374: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8375: 	
                   8376: 	my $num1=$symbchck+$symbseed+$namechck;
                   8377: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8378: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8379: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 8380: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8381: 	
                   8382: 	return "$num1:$num2";
                   8383:     }
                   8384: }
                   8385: 
1.675     albertel 8386: sub rndseed_64bit5 {
                   8387:     my ($symb,$courseid,$domain,$username)=@_;
                   8388:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   8389:     return "$num1:$num2";
                   8390: }
                   8391: 
1.366     albertel 8392: sub rndseed_CODE_64bit {
                   8393:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 8394:     {
1.366     albertel 8395: 	use integer;
1.443     albertel 8396: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 8397: 	my $symbseed=numval2($symb);
1.491     albertel 8398: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8399: 	my $CODEseed=numval(&getCODE());
1.443     albertel 8400: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 8401: 	my $num1=$symbseed+$CODEchck;
                   8402: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8403: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8404: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 8405: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8406: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 8407: 	return "$num1:$num2";
1.366     albertel 8408:     }
                   8409: }
                   8410: 
1.575     albertel 8411: sub rndseed_CODE_64bit4 {
                   8412:     my ($symb,$courseid,$domain,$username)=@_;
                   8413:     {
                   8414: 	use integer;
                   8415: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   8416: 	my $symbseed=numval3($symb);
                   8417: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8418: 	my $CODEseed=numval3(&getCODE());
                   8419: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8420: 	my $num1=$symbseed+$CODEchck;
                   8421: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8422: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8423: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 8424: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8425: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   8426: 	return "$num1:$num2";
                   8427:     }
                   8428: }
                   8429: 
1.675     albertel 8430: sub rndseed_CODE_64bit5 {
                   8431:     my ($symb,$courseid,$domain,$username)=@_;
                   8432:     my $code = &getCODE();
                   8433:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   8434:     return "$num1:$num2";
                   8435: }
                   8436: 
1.366     albertel 8437: sub setup_random_from_rndseed {
                   8438:     my ($rndseed)=@_;
1.503     albertel 8439:     if ($rndseed =~/([,:])/) {
                   8440: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 8441: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   8442:     } else {
                   8443: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 8444:     }
1.36      albertel 8445: }
                   8446: 
1.474     albertel 8447: sub latest_receipt_algorithm_id {
1.835     albertel 8448:     return 'receipt3';
1.474     albertel 8449: }
                   8450: 
1.480     www      8451: sub recunique {
                   8452:     my $fucourseid=shift;
                   8453:     my $unique;
1.835     albertel 8454:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   8455: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8456: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      8457:     } else {
                   8458: 	$unique=$perlvar{'lonReceipt'};
                   8459:     }
                   8460:     return unpack("%32C*",$unique);
                   8461: }
                   8462: 
                   8463: sub recprefix {
                   8464:     my $fucourseid=shift;
                   8465:     my $prefix;
1.835     albertel 8466:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   8467: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8468: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      8469:     } else {
                   8470: 	$prefix=$perlvar{'lonHostID'};
                   8471:     }
                   8472:     return unpack("%32C*",$prefix);
                   8473: }
                   8474: 
1.76      www      8475: sub ireceipt {
1.474     albertel 8476:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 8477: 
                   8478:     my $return =&recprefix($fucourseid).'-';
                   8479: 
                   8480:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   8481: 	$env{'request.state'} eq 'construct') {
                   8482: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   8483: 	return $return;
                   8484:     }
                   8485: 
1.76      www      8486:     my $cuname=unpack("%32C*",$funame);
                   8487:     my $cudom=unpack("%32C*",$fudom);
                   8488:     my $cucourseid=unpack("%32C*",$fucourseid);
                   8489:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      8490:     my $cunique=&recunique($fucourseid);
1.474     albertel 8491:     my $cpart=unpack("%32S*",$part);
1.835     albertel 8492:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   8493: 
1.790     albertel 8494: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 8495: 			       
                   8496: 	$return.= ($cunique%$cuname+
                   8497: 		   $cunique%$cudom+
                   8498: 		   $cusymb%$cuname+
                   8499: 		   $cusymb%$cudom+
                   8500: 		   $cucourseid%$cuname+
                   8501: 		   $cucourseid%$cudom+
                   8502: 		   $cpart%$cuname+
                   8503: 		   $cpart%$cudom);
                   8504:     } else {
                   8505: 	$return.= ($cunique%$cuname+
                   8506: 		   $cunique%$cudom+
                   8507: 		   $cusymb%$cuname+
                   8508: 		   $cusymb%$cudom+
                   8509: 		   $cucourseid%$cuname+
                   8510: 		   $cucourseid%$cudom);
                   8511:     }
                   8512:     return $return;
1.76      www      8513: }
                   8514: 
                   8515: sub receipt {
1.474     albertel 8516:     my ($part)=@_;
1.790     albertel 8517:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 8518:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      8519: }
1.260     ng       8520: 
1.790     albertel 8521: sub whichuser {
                   8522:     my ($passedsymb)=@_;
                   8523:     my ($symb,$courseid,$domain,$name,$publicuser);
                   8524:     if (defined($env{'form.grade_symb'})) {
                   8525: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   8526: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   8527: 	if (!$allowed &&
                   8528: 	    exists($env{'request.course.sec'}) &&
                   8529: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   8530: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   8531: 			      '/'.$env{'request.course.sec'});
                   8532: 	}
                   8533: 	if ($allowed) {
                   8534: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   8535: 	    $courseid=$tmp_courseid;
                   8536: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   8537: 	    ($name)=&get_env_multiple('form.grade_username');
                   8538: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   8539: 	}
                   8540:     }
                   8541:     if (!$passedsymb) {
                   8542: 	$symb=&symbread();
                   8543:     } else {
                   8544: 	$symb=$passedsymb;
                   8545:     }
                   8546:     $courseid=$env{'request.course.id'};
                   8547:     $domain=$env{'user.domain'};
                   8548:     $name=$env{'user.name'};
                   8549:     if ($name eq 'public' && $domain eq 'public') {
                   8550: 	if (!defined($env{'form.username'})) {
                   8551: 	    $env{'form.username'}.=time.rand(10000000);
                   8552: 	}
                   8553: 	$name.=$env{'form.username'};
                   8554:     }
                   8555:     return ($symb,$courseid,$domain,$name,$publicuser);
                   8556: 
                   8557: }
                   8558: 
1.36      albertel 8559: # ------------------------------------------------------------ Serves up a file
1.472     albertel 8560: # returns either the contents of the file or 
                   8561: # -1 if the file doesn't exist
1.481     raeburn  8562: #
                   8563: # if the target is a file that was uploaded via DOCS, 
                   8564: # a check will be made to see if a current copy exists on the local server,
                   8565: # if it does this will be served, otherwise a copy will be retrieved from
                   8566: # the home server for the course and stored in /home/httpd/html/userfiles on
                   8567: # the local server.   
1.472     albertel 8568: 
1.36      albertel 8569: sub getfile {
1.538     albertel 8570:     my ($file) = @_;
1.609     banghart 8571:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 8572:     &repcopy($file);
                   8573:     return &readfile($file);
                   8574: }
                   8575: 
                   8576: sub repcopy_userfile {
                   8577:     my ($file)=@_;
1.609     banghart 8578:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 8579:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 8580:     my ($cdom,$cnum,$filename) = 
1.811     albertel 8581: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 8582:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   8583:     if (-e "$file") {
1.828     www      8584: # we already have a local copy, check it out
1.538     albertel 8585: 	my @fileinfo = stat($file);
1.828     www      8586: 	my $rtncode;
                   8587: 	my $info;
1.538     albertel 8588: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 8589: 	if ($lwpresp ne 'ok') {
1.828     www      8590: # there is no such file anymore, even though we had a local copy
1.482     albertel 8591: 	    if ($rtncode eq '404') {
1.538     albertel 8592: 		unlink($file);
1.482     albertel 8593: 	    }
                   8594: 	    return -1;
                   8595: 	}
                   8596: 	if ($info < $fileinfo[9]) {
1.828     www      8597: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  8598: 	    return 'ok';
1.828     www      8599: 	} else {
                   8600: # the file is outdated, get rid of it
                   8601: 	    unlink($file);
1.482     albertel 8602: 	}
1.828     www      8603:     }
                   8604: # one way or the other, at this point, we don't have the file
                   8605: # construct the correct path for the file
                   8606:     my @parts = ($cdom,$cnum); 
                   8607:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   8608: 	push @parts, split(/\//,$1);
                   8609:     }
                   8610:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   8611:     foreach my $part (@parts) {
                   8612: 	$path .= '/'.$part;
                   8613: 	if (!-e $path) {
                   8614: 	    mkdir($path,0770);
1.482     albertel 8615: 	}
                   8616:     }
1.828     www      8617: # now the path exists for sure
                   8618: # get a user agent
                   8619:     my $ua=new LWP::UserAgent;
                   8620:     my $transferfile=$file.'.in.transfer';
                   8621: # FIXME: this should flock
                   8622:     if (-e $transferfile) { return 'ok'; }
                   8623:     my $request;
                   8624:     $uri=~s/^\///;
1.980     raeburn  8625:     my $homeserver = &homeserver($cnum,$cdom);
                   8626:     my $protocol = $protocol{$homeserver};
                   8627:     $protocol = 'http' if ($protocol ne 'https');
                   8628:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      8629:     my $response=$ua->request($request,$transferfile);
                   8630: # did it work?
                   8631:     if ($response->is_error()) {
                   8632: 	unlink($transferfile);
                   8633: 	&logthis("Userfile repcopy failed for $uri");
                   8634: 	return -1;
                   8635:     }
                   8636: # worked, rename the transfer file
                   8637:     rename($transferfile,$file);
1.607     raeburn  8638:     return 'ok';
1.481     raeburn  8639: }
                   8640: 
1.517     albertel 8641: sub tokenwrapper {
                   8642:     my $uri=shift;
1.980     raeburn  8643:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 8644:     $uri=~s|^/||;
1.620     albertel 8645:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8646:     my $token=$1;
1.552     albertel 8647:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8648:     if ($udom && $uname && $file) {
                   8649: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8650:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  8651:         my $homeserver = &homeserver($uname,$udom);
                   8652:         my $protocol = $protocol{$homeserver};
                   8653:         $protocol = 'http' if ($protocol ne 'https');
                   8654:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 8655:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8656:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8657:     } else {
                   8658:         return '/adm/notfound.html';
                   8659:     }
                   8660: }
                   8661: 
1.828     www      8662: # call with reqtype HEAD: get last modification time
                   8663: # call with reqtype GET: get the file contents
                   8664: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8665: #
1.481     raeburn  8666: sub getuploaded {
                   8667:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8668:     $uri=~s/^\///;
1.980     raeburn  8669:     my $homeserver = &homeserver($cnum,$cdom);
                   8670:     my $protocol = $protocol{$homeserver};
                   8671:     $protocol = 'http' if ($protocol ne 'https');
                   8672:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  8673:     my $ua=new LWP::UserAgent;
                   8674:     my $request=new HTTP::Request($reqtype,$uri);
                   8675:     my $response=$ua->request($request);
                   8676:     $$rtncode = $response->code;
1.482     albertel 8677:     if (! $response->is_success()) {
                   8678: 	return 'failed';
                   8679:     }      
                   8680:     if ($reqtype eq 'HEAD') {
1.486     www      8681: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8682:     } elsif ($reqtype eq 'GET') {
                   8683: 	$$info = $response->content;
1.472     albertel 8684:     }
1.482     albertel 8685:     return 'ok';
1.36      albertel 8686: }
                   8687: 
1.481     raeburn  8688: sub readfile {
                   8689:     my $file = shift;
                   8690:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8691:     my $fh;
                   8692:     open($fh,"<$file");
                   8693:     my $a='';
1.800     albertel 8694:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8695:     return $a;
                   8696: }
                   8697: 
1.36      albertel 8698: sub filelocation {
1.590     banghart 8699:     my ($dir,$file) = @_;
                   8700:     my $location;
                   8701:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8702: 
                   8703:     if ($file =~ m-^/adm/-) {
                   8704: 	$file=~s-^/adm/wrapper/-/-;
                   8705: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8706:     }
1.882     albertel 8707: 
1.590     banghart 8708:     if ($file=~m:^/~:) { # is a contruction space reference
                   8709:         $location = $file;
                   8710:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8711:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8712: 	# is a correct contruction space reference
                   8713:         $location = $file;
1.956     raeburn  8714:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   8715:         $location = $file;
1.609     banghart 8716:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8717:         my ($udom,$uname,$filename)=
1.811     albertel 8718:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8719:         my $home=&homeserver($uname,$udom);
                   8720:         my $is_me=0;
                   8721:         my @ids=&current_machine_ids();
                   8722:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8723:         if ($is_me) {
1.955     raeburn  8724:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 8725:         } else {
                   8726:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8727:   	      $udom.'/'.$uname.'/'.$filename;
                   8728:         }
1.882     albertel 8729:     } elsif ($file =~ m-^/adm/-) {
                   8730: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8731:     } else {
                   8732:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8733:         $file=~s:^/res/:/:;
                   8734:         if ( !( $file =~ m:^/:) ) {
                   8735:             $location = $dir. '/'.$file;
                   8736:         } else {
                   8737:             $location = '/home/httpd/html/res'.$file;
                   8738:         }
1.59      albertel 8739:     }
1.590     banghart 8740:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8741:     while ($location=~m{/\.\./}) {
                   8742: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8743: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8744: 	} else {
                   8745: 	    $location=~ s{/\.\./}{/}g;
                   8746: 	}
                   8747:     } #remove dir/..
1.590     banghart 8748:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8749:     return $location;
1.46      www      8750: }
1.36      albertel 8751: 
1.46      www      8752: sub hreflocation {
                   8753:     my ($dir,$file)=@_;
1.980     raeburn  8754:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 8755: 	$file=filelocation($dir,$file);
1.700     albertel 8756:     } elsif ($file=~m-^/adm/-) {
                   8757: 	$file=~s-^/adm/wrapper/-/-;
                   8758: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8759:     }
                   8760:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8761: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8762:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8763: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8764:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8765: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8766: 	    -/uploaded/$1/$2/-x;
1.46      www      8767:     }
1.913     albertel 8768:     if ($file=~ m{^/userfiles/}) {
                   8769: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8770:     }
1.462     albertel 8771:     return $file;
1.465     albertel 8772: }
                   8773: 
                   8774: sub current_machine_domains {
1.853     albertel 8775:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8776: }
                   8777: 
                   8778: sub machine_domains {
                   8779:     my ($hostname) = @_;
1.465     albertel 8780:     my @domains;
1.838     albertel 8781:     my %hostname = &all_hostnames();
1.465     albertel 8782:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8783: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8784: 	if ($hostname eq $name) {
1.844     albertel 8785: 	    push(@domains,&host_domain($id));
1.465     albertel 8786: 	}
                   8787:     }
                   8788:     return @domains;
                   8789: }
                   8790: 
                   8791: sub current_machine_ids {
1.853     albertel 8792:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8793: }
                   8794: 
                   8795: sub machine_ids {
                   8796:     my ($hostname) = @_;
                   8797:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8798:     my @ids;
1.888     albertel 8799:     my %name_to_host = &all_names();
1.889     albertel 8800:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8801: 	return @{ $name_to_host{$hostname} };
                   8802:     }
                   8803:     return;
1.31      www      8804: }
                   8805: 
1.824     raeburn  8806: sub additional_machine_domains {
                   8807:     my @domains;
                   8808:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8809:     while( my $line = <$fh>) {
                   8810:         $line =~ s/\s//g;
                   8811:         push(@domains,$line);
                   8812:     }
                   8813:     return @domains;
                   8814: }
                   8815: 
                   8816: sub default_login_domain {
                   8817:     my $domain = $perlvar{'lonDefDomain'};
                   8818:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8819:     foreach my $posdom (&current_machine_domains(),
                   8820:                         &additional_machine_domains()) {
                   8821:         if (lc($posdom) eq lc($testdomain)) {
                   8822:             $domain=$posdom;
                   8823:             last;
                   8824:         }
                   8825:     }
                   8826:     return $domain;
                   8827: }
                   8828: 
1.31      www      8829: # ------------------------------------------------------------- Declutters URLs
                   8830: 
                   8831: sub declutter {
                   8832:     my $thisfn=shift;
1.569     albertel 8833:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8834:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8835:     $thisfn=~s/^\///;
1.697     albertel 8836:     $thisfn=~s|^adm/wrapper/||;
                   8837:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8838:     $thisfn=~s/^res\///;
1.235     www      8839:     $thisfn=~s/\?.+$//;
1.268     www      8840:     return $thisfn;
                   8841: }
                   8842: 
                   8843: # ------------------------------------------------------------- Clutter up URLs
                   8844: 
                   8845: sub clutter {
                   8846:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8847:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8848: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8849:        $thisfn='/res'.$thisfn; 
                   8850:     }
1.694     albertel 8851:     if ($thisfn !~m|/adm|) {
1.695     albertel 8852: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8853: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8854: 	} else {
                   8855: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8856: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8857: 	    if ($embstyle eq 'ssi'
                   8858: 		|| ($embstyle eq 'hdn')
                   8859: 		|| ($embstyle eq 'rat')
                   8860: 		|| ($embstyle eq 'prv')
                   8861: 		|| ($embstyle eq 'ign')) {
                   8862: 		#do nothing with these
                   8863: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8864: 		|| ($embstyle eq 'emb')
                   8865: 		|| ($embstyle eq 'wrp')) {
                   8866: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8867: 	    } elsif ($embstyle eq 'unk'
                   8868: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8869: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8870: 	    } else {
1.718     www      8871: #		&logthis("Got a blank emb style");
1.695     albertel 8872: 	    }
1.694     albertel 8873: 	}
                   8874:     }
1.31      www      8875:     return $thisfn;
1.12      www      8876: }
                   8877: 
1.787     albertel 8878: sub clutter_with_no_wrapper {
                   8879:     my $uri = &clutter(shift);
                   8880:     if ($uri =~ m-^/adm/-) {
                   8881: 	$uri =~ s-^/adm/wrapper/-/-;
                   8882: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8883:     }
                   8884:     return $uri;
                   8885: }
                   8886: 
1.557     albertel 8887: sub freeze_escape {
                   8888:     my ($value)=@_;
                   8889:     if (ref($value)) {
                   8890: 	$value=&nfreeze($value);
                   8891: 	return '__FROZEN__'.&escape($value);
                   8892:     }
                   8893:     return &escape($value);
                   8894: }
                   8895: 
1.11      www      8896: 
1.557     albertel 8897: sub thaw_unescape {
                   8898:     my ($value)=@_;
                   8899:     if ($value =~ /^__FROZEN__/) {
                   8900: 	substr($value,0,10,undef);
                   8901: 	$value=&unescape($value);
                   8902: 	return &thaw($value);
                   8903:     }
                   8904:     return &unescape($value);
                   8905: }
                   8906: 
1.436     albertel 8907: sub correct_line_ends {
                   8908:     my ($result)=@_;
                   8909:     $$result =~s/\r\n/\n/mg;
                   8910:     $$result =~s/\r/\n/mg;
1.415     albertel 8911: }
1.1       albertel 8912: # ================================================================ Main Program
                   8913: 
1.184     www      8914: sub goodbye {
1.204     albertel 8915:    &logthis("Starting Shut down");
1.443     albertel 8916: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8917:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8918: #converted
1.599     albertel 8919: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8920:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8921: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8922: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8923: #1.1 only
1.870     albertel 8924: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8925: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8926: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8927: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8928:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8929:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8930:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8931:    &flushcourselogs();
                   8932:    &logthis("Shutting down");
                   8933: }
                   8934: 
1.852     albertel 8935: sub get_dns {
1.869     albertel 8936:     my ($url,$func,$ignore_cache) = @_;
                   8937:     if (!$ignore_cache) {
                   8938: 	my ($content,$cached)=
                   8939: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8940: 	if ($cached) {
                   8941: 	    &$func($content);
                   8942: 	    return;
                   8943: 	}
                   8944:     }
                   8945: 
                   8946:     my %alldns;
1.852     albertel 8947:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8948:     foreach my $dns (<$config>) {
                   8949: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  8950:         my $line = $1;
                   8951:         my ($host,$protocol) = split(/:/,$line);
                   8952:         if ($protocol ne 'https') {
                   8953:             $protocol = 'http';
                   8954:         }
                   8955: 	$alldns{$host} = $protocol;
1.869     albertel 8956:     }
                   8957:     while (%alldns) {
                   8958: 	my ($dns) = keys(%alldns);
1.852     albertel 8959: 	my $ua=new LWP::UserAgent;
1.979     raeburn  8960: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 8961: 	my $response=$ua->request($request);
1.979     raeburn  8962:         delete($alldns{$dns});
1.852     albertel 8963: 	next if ($response->is_error());
                   8964: 	my @content = split("\n",$response->content);
1.869     albertel 8965: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8966: 	&$func(\@content);
1.869     albertel 8967: 	return;
1.852     albertel 8968:     }
                   8969:     close($config);
1.871     albertel 8970:     my $which = (split('/',$url))[3];
                   8971:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8972:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8973:     my @content = <$config>;
                   8974:     &$func(\@content);
                   8975:     return;
1.852     albertel 8976: }
1.327     albertel 8977: # ------------------------------------------------------------ Read domain file
                   8978: {
1.852     albertel 8979:     my $loaded;
1.846     albertel 8980:     my %domain;
                   8981: 
1.852     albertel 8982:     sub parse_domain_tab {
                   8983: 	my ($lines) = @_;
                   8984: 	foreach my $line (@$lines) {
                   8985: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8986: 
1.846     albertel 8987: 	    chomp($line);
1.852     albertel 8988: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8989: 	    my %this_domain;
                   8990: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8991: 			       'lang_def', 'city', 'longi', 'lati',
                   8992: 			       'primary') {
                   8993: 		$this_domain{$field} = shift(@elements);
                   8994: 	    }
                   8995: 	    $domain{$name} = \%this_domain;
1.852     albertel 8996: 	}
                   8997:     }
1.864     albertel 8998: 
                   8999:     sub reset_domain_info {
                   9000: 	undef($loaded);
                   9001: 	undef(%domain);
                   9002:     }
                   9003: 
1.852     albertel 9004:     sub load_domain_tab {
1.869     albertel 9005: 	my ($ignore_cache) = @_;
                   9006: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 9007: 	my $fh;
                   9008: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   9009: 	    my @lines = <$fh>;
                   9010: 	    &parse_domain_tab(\@lines);
1.448     albertel 9011: 	}
1.852     albertel 9012: 	close($fh);
                   9013: 	$loaded = 1;
1.327     albertel 9014:     }
1.846     albertel 9015: 
                   9016:     sub domain {
1.852     albertel 9017: 	&load_domain_tab() if (!$loaded);
                   9018: 
1.846     albertel 9019: 	my ($name,$what) = @_;
                   9020: 	return if ( !exists($domain{$name}) );
                   9021: 
                   9022: 	if (!$what) {
                   9023: 	    return $domain{$name}{'description'};
                   9024: 	}
                   9025: 	return $domain{$name}{$what};
                   9026:     }
1.974     raeburn  9027: 
                   9028:     sub domain_info {
                   9029:         &load_domain_tab() if (!$loaded);
                   9030:         return %domain;
                   9031:     }
                   9032: 
1.327     albertel 9033: }
                   9034: 
                   9035: 
1.1       albertel 9036: # ------------------------------------------------------------- Read hosts file
                   9037: {
1.838     albertel 9038:     my %hostname;
1.844     albertel 9039:     my %hostdom;
1.845     albertel 9040:     my %libserv;
1.852     albertel 9041:     my $loaded;
1.888     albertel 9042:     my %name_to_host;
1.852     albertel 9043: 
                   9044:     sub parse_hosts_tab {
                   9045: 	my ($file) = @_;
                   9046: 	foreach my $configline (@$file) {
                   9047: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   9048: 	    next if ($configline =~ /^\^/);
                   9049: 	    chomp($configline);
1.968     raeburn  9050: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852     albertel 9051: 	    $name=~s/\s//g;
                   9052: 	    if ($id && $domain && $role && $name) {
                   9053: 		$hostname{$id}=$name;
1.888     albertel 9054: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 9055: 		$hostdom{$id}=$domain;
                   9056: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  9057:                 if (defined($protocol)) {
                   9058:                     if ($protocol eq 'https') {
                   9059:                         $protocol{$id} = $protocol;
                   9060:                     } else {
                   9061:                         $protocol{$id} = 'http'; 
                   9062:                     }
1.968     raeburn  9063:                 } else {
1.969     raeburn  9064:                     $protocol{$id} = 'http';
1.968     raeburn  9065:                 }
1.852     albertel 9066: 	    }
                   9067: 	}
                   9068:     }
1.864     albertel 9069:     
                   9070:     sub reset_hosts_info {
1.897     albertel 9071: 	&purge_remembered();
1.864     albertel 9072: 	&reset_domain_info();
                   9073: 	&reset_hosts_ip_info();
1.892     albertel 9074: 	undef(%name_to_host);
1.864     albertel 9075: 	undef(%hostname);
                   9076: 	undef(%hostdom);
                   9077: 	undef(%libserv);
                   9078: 	undef($loaded);
                   9079:     }
1.1       albertel 9080: 
1.852     albertel 9081:     sub load_hosts_tab {
1.869     albertel 9082: 	my ($ignore_cache) = @_;
                   9083: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 9084: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9085: 	my @config = <$config>;
                   9086: 	&parse_hosts_tab(\@config);
                   9087: 	close($config);
                   9088: 	$loaded=1;
1.1       albertel 9089:     }
1.852     albertel 9090: 
1.838     albertel 9091:     sub hostname {
1.852     albertel 9092: 	&load_hosts_tab() if (!$loaded);
                   9093: 
1.838     albertel 9094: 	my ($lonid) = @_;
                   9095: 	return $hostname{$lonid};
                   9096:     }
1.845     albertel 9097: 
1.838     albertel 9098:     sub all_hostnames {
1.852     albertel 9099: 	&load_hosts_tab() if (!$loaded);
                   9100: 
1.838     albertel 9101: 	return %hostname;
                   9102:     }
1.845     albertel 9103: 
1.888     albertel 9104:     sub all_names {
                   9105: 	&load_hosts_tab() if (!$loaded);
                   9106: 
                   9107: 	return %name_to_host;
                   9108:     }
                   9109: 
1.974     raeburn  9110:     sub all_host_domain {
                   9111:         &load_hosts_tab() if (!$loaded);
                   9112:         return %hostdom;
                   9113:     }
                   9114: 
1.845     albertel 9115:     sub is_library {
1.852     albertel 9116: 	&load_hosts_tab() if (!$loaded);
                   9117: 
1.845     albertel 9118: 	return exists($libserv{$_[0]});
                   9119:     }
                   9120: 
                   9121:     sub all_library {
1.852     albertel 9122: 	&load_hosts_tab() if (!$loaded);
                   9123: 
1.845     albertel 9124: 	return %libserv;
                   9125:     }
                   9126: 
1.841     albertel 9127:     sub get_servers {
1.852     albertel 9128: 	&load_hosts_tab() if (!$loaded);
                   9129: 
1.841     albertel 9130: 	my ($domain,$type) = @_;
                   9131: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   9132: 	                                          : %hostname;
                   9133: 	my %result;
1.842     albertel 9134: 	if (ref($domain) eq 'ARRAY') {
                   9135: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 9136: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 9137: 		    $result{$host} = $hostname;
                   9138: 		}
                   9139: 	    }
                   9140: 	} else {
                   9141: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   9142: 		if ($hostdom{$host} eq $domain) {
                   9143: 		    $result{$host} = $hostname;
                   9144: 		}
1.841     albertel 9145: 	    }
                   9146: 	}
                   9147: 	return %result;
                   9148:     }
1.845     albertel 9149: 
1.844     albertel 9150:     sub host_domain {
1.852     albertel 9151: 	&load_hosts_tab() if (!$loaded);
                   9152: 
1.844     albertel 9153: 	my ($lonid) = @_;
                   9154: 	return $hostdom{$lonid};
                   9155:     }
                   9156: 
1.841     albertel 9157:     sub all_domains {
1.852     albertel 9158: 	&load_hosts_tab() if (!$loaded);
                   9159: 
1.841     albertel 9160: 	my %seen;
                   9161: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   9162: 	return @uniq;
                   9163:     }
1.1       albertel 9164: }
                   9165: 
1.847     albertel 9166: { 
                   9167:     my %iphost;
1.856     albertel 9168:     my %name_to_ip;
                   9169:     my %lonid_to_ip;
1.869     albertel 9170: 
1.847     albertel 9171:     sub get_hosts_from_ip {
                   9172: 	my ($ip) = @_;
                   9173: 	my %iphosts = &get_iphost();
                   9174: 	if (ref($iphosts{$ip})) {
                   9175: 	    return @{$iphosts{$ip}};
                   9176: 	}
                   9177: 	return;
1.839     albertel 9178:     }
1.864     albertel 9179:     
                   9180:     sub reset_hosts_ip_info {
                   9181: 	undef(%iphost);
                   9182: 	undef(%name_to_ip);
                   9183: 	undef(%lonid_to_ip);
                   9184:     }
1.856     albertel 9185: 
                   9186:     sub get_host_ip {
                   9187: 	my ($lonid) = @_;
                   9188: 	if (exists($lonid_to_ip{$lonid})) {
                   9189: 	    return $lonid_to_ip{$lonid};
                   9190: 	}
                   9191: 	my $name=&hostname($lonid);
                   9192:    	my $ip = gethostbyname($name);
                   9193: 	return if (!$ip || length($ip) ne 4);
                   9194: 	$ip=inet_ntoa($ip);
                   9195: 	$name_to_ip{$name}   = $ip;
                   9196: 	$lonid_to_ip{$lonid} = $ip;
                   9197: 	return $ip;
                   9198:     }
1.847     albertel 9199:     
                   9200:     sub get_iphost {
1.869     albertel 9201: 	my ($ignore_cache) = @_;
1.894     albertel 9202: 
1.869     albertel 9203: 	if (!$ignore_cache) {
                   9204: 	    if (%iphost) {
                   9205: 		return %iphost;
                   9206: 	    }
                   9207: 	    my ($ip_info,$cached)=
                   9208: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   9209: 	    if ($cached) {
                   9210: 		%iphost      = %{$ip_info->[0]};
                   9211: 		%name_to_ip  = %{$ip_info->[1]};
                   9212: 		%lonid_to_ip = %{$ip_info->[2]};
                   9213: 		return %iphost;
                   9214: 	    }
                   9215: 	}
1.894     albertel 9216: 
                   9217: 	# get yesterday's info for fallback
                   9218: 	my %old_name_to_ip;
                   9219: 	my ($ip_info,$cached)=
                   9220: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   9221: 	if ($cached) {
                   9222: 	    %old_name_to_ip = %{$ip_info->[1]};
                   9223: 	}
                   9224: 
1.888     albertel 9225: 	my %name_to_host = &all_names();
                   9226: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 9227: 	    my $ip;
                   9228: 	    if (!exists($name_to_ip{$name})) {
                   9229: 		$ip = gethostbyname($name);
                   9230: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 9231: 		    if (defined($old_name_to_ip{$name})) {
                   9232: 			$ip = $old_name_to_ip{$name};
                   9233: 			&logthis("Can't find $name defaulting to old $ip");
                   9234: 		    } else {
                   9235: 			&logthis("Name $name no IP found");
                   9236: 			next;
                   9237: 		    }
                   9238: 		} else {
                   9239: 		    $ip=inet_ntoa($ip);
1.847     albertel 9240: 		}
                   9241: 		$name_to_ip{$name} = $ip;
                   9242: 	    } else {
                   9243: 		$ip = $name_to_ip{$name};
1.653     albertel 9244: 	    }
1.888     albertel 9245: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   9246: 		$lonid_to_ip{$id} = $ip;
                   9247: 	    }
                   9248: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 9249: 	}
1.869     albertel 9250: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   9251: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 9252: 				      48*60*60);
1.869     albertel 9253: 
1.847     albertel 9254: 	return %iphost;
1.598     albertel 9255:     }
                   9256: 
1.992     raeburn  9257:     #
                   9258:     #  Given a DNS returns the loncapa host name for that DNS 
                   9259:     # 
                   9260:     sub host_from_dns {
                   9261:         my ($dns) = @_;
                   9262:         my @hosts;
                   9263:         my $ip;
                   9264: 
1.993     raeburn  9265:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  9266:             $ip = $name_to_ip{$dns};
                   9267:         }
                   9268:         if (!$ip) {
                   9269:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   9270:             if (length($ip) == 4) { 
                   9271: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   9272:             }
                   9273:         }
                   9274:         if ($ip) {
                   9275: 	    @hosts = get_hosts_from_ip($ip);
                   9276: 	    return $hosts[0];
                   9277:         }
                   9278:         return undef;
1.986     foxr     9279:     }
1.992     raeburn  9280: 
1.986     foxr     9281: }
                   9282: 
1.862     albertel 9283: BEGIN {
                   9284: 
                   9285: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   9286:     unless ($readit) {
                   9287: {
                   9288:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   9289:     %perlvar = (%perlvar,%{$configvars});
                   9290: }
                   9291: 
                   9292: 
1.1       albertel 9293: # ------------------------------------------------------ Read spare server file
                   9294: {
1.448     albertel 9295:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 9296: 
                   9297:     while (my $configline=<$config>) {
                   9298:        chomp($configline);
1.284     matthew  9299:        if ($configline) {
1.784     albertel 9300: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 9301: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 9302: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 9303:        }
                   9304:     }
1.448     albertel 9305:     close($config);
1.1       albertel 9306: }
1.11      www      9307: # ------------------------------------------------------------ Read permissions
                   9308: {
1.448     albertel 9309:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      9310: 
                   9311:     while (my $configline=<$config>) {
1.448     albertel 9312: 	chomp($configline);
                   9313: 	if ($configline) {
                   9314: 	    my ($role,$perm)=split(/ /,$configline);
                   9315: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   9316: 	}
1.11      www      9317:     }
1.448     albertel 9318:     close($config);
1.11      www      9319: }
                   9320: 
                   9321: # -------------------------------------------- Read plain texts for permissions
                   9322: {
1.448     albertel 9323:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      9324: 
                   9325:     while (my $configline=<$config>) {
1.448     albertel 9326: 	chomp($configline);
                   9327: 	if ($configline) {
1.742     raeburn  9328: 	    my ($short,@plain)=split(/:/,$configline);
                   9329:             %{$prp{$short}} = ();
                   9330: 	    if (@plain > 0) {
                   9331:                 $prp{$short}{'std'} = $plain[0];
                   9332:                 for (my $i=1; $i<@plain; $i++) {
                   9333:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   9334:                 }
                   9335:             }
1.448     albertel 9336: 	}
1.135     www      9337:     }
1.448     albertel 9338:     close($config);
1.135     www      9339: }
                   9340: 
                   9341: # ---------------------------------------------------------- Read package table
                   9342: {
1.448     albertel 9343:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      9344: 
                   9345:     while (my $configline=<$config>) {
1.483     albertel 9346: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 9347: 	chomp($configline);
                   9348: 	my ($short,$plain)=split(/:/,$configline);
                   9349: 	my ($pack,$name)=split(/\&/,$short);
                   9350: 	if ($plain ne '') {
                   9351: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   9352: 	    $packagetab{$short}=$plain; 
                   9353: 	}
1.11      www      9354:     }
1.448     albertel 9355:     close($config);
1.329     matthew  9356: }
                   9357: 
                   9358: # ------------- set up temporary directory
                   9359: {
                   9360:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   9361: 
1.11      www      9362: }
                   9363: 
1.794     albertel 9364: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   9365: 				'compress_threshold'=> 20_000,
                   9366:  			        });
1.185     www      9367: 
1.281     www      9368: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      9369: $dumpcount=0;
1.958     www      9370: $locknum=0;
1.22      www      9371: 
1.163     harris41 9372: &logtouch();
1.672     albertel 9373: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      9374: $readit=1;
1.564     albertel 9375:     {
                   9376: 	use integer;
                   9377: 	my $test=(2**32)+1;
1.568     albertel 9378: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 9379: 	&logthis(" Detected 64bit platform ($_64bit)");
                   9380:     }
1.195     www      9381: }
1.1       albertel 9382: }
1.179     www      9383: 
1.1       albertel 9384: 1;
1.191     harris41 9385: __END__
                   9386: 
1.243     albertel 9387: =pod
                   9388: 
1.191     harris41 9389: =head1 NAME
                   9390: 
1.243     albertel 9391: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 9392: 
                   9393: =head1 SYNOPSIS
                   9394: 
1.243     albertel 9395: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 9396: 
                   9397:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   9398: 
1.243     albertel 9399: Common parameters:
                   9400: 
                   9401: =over 4
                   9402: 
                   9403: =item *
                   9404: 
                   9405: $uname : an internal username (if $cname expecting a course Id specifically)
                   9406: 
                   9407: =item *
                   9408: 
                   9409: $udom : a domain (if $cdom expecting a course's domain specifically)
                   9410: 
                   9411: =item *
                   9412: 
                   9413: $symb : a resource instance identifier
                   9414: 
                   9415: =item *
                   9416: 
                   9417: $namespace : the name of a .db file that contains the data needed or
                   9418: being set.
                   9419: 
                   9420: =back
                   9421: 
1.394     bowersj2 9422: =head1 OVERVIEW
1.191     harris41 9423: 
1.394     bowersj2 9424: lonnet provides subroutines which interact with the
                   9425: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   9426: about classes, users, and resources.
1.243     albertel 9427: 
                   9428: For many of these objects you can also use this to store data about
                   9429: them or modify them in various ways.
1.191     harris41 9430: 
1.394     bowersj2 9431: =head2 Symbs
1.191     harris41 9432: 
1.394     bowersj2 9433: To identify a specific instance of a resource, LON-CAPA uses symbols
                   9434: or "symbs"X<symb>. These identifiers are built from the URL of the
                   9435: map, the resource number of the resource in the map, and the URL of
                   9436: the resource itself. The latter is somewhat redundant, but might help
                   9437: if maps change.
                   9438: 
                   9439: An example is
                   9440: 
                   9441:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   9442: 
                   9443: The respective map entry is
                   9444: 
                   9445:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   9446:   title="Problem 2">
                   9447:  </resource>
                   9448: 
                   9449: Symbs are used by the random number generator, as well as to store and
                   9450: restore data specific to a certain instance of for example a problem.
                   9451: 
                   9452: =head2 Storing And Retrieving Data
                   9453: 
                   9454: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   9455: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   9456: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   9457: is is the non-critical message twin of cstore. These functions are for
                   9458: handlers to store a perl hash to a user's permanent data space in an
                   9459: easy manner, and to retrieve it again on another call. It is expected
                   9460: that a handler would use this once at the beginning to retrieve data,
                   9461: and then again once at the end to send only the new data back.
                   9462: 
                   9463: The data is stored in the user's data directory on the user's
                   9464: homeserver under the ID of the course.
                   9465: 
                   9466: The hash that is returned by restore will have all of the previous
                   9467: value for all of the elements of the hash.
                   9468: 
                   9469: Example:
                   9470: 
                   9471:  #creating a hash
                   9472:  my %hash;
                   9473:  $hash{'foo'}='bar';
                   9474: 
                   9475:  #storing it
                   9476:  &Apache::lonnet::cstore(\%hash);
                   9477: 
                   9478:  #changing a value
                   9479:  $hash{'foo'}='notbar';
                   9480: 
                   9481:  #adding a new value
                   9482:  $hash{'bar'}='foo';
                   9483:  &Apache::lonnet::cstore(\%hash);
                   9484: 
                   9485:  #retrieving the hash
                   9486:  my %history=&Apache::lonnet::restore();
                   9487: 
                   9488:  #print the hash
                   9489:  foreach my $key (sort(keys(%history))) {
                   9490:    print("\%history{$key} = $history{$key}");
                   9491:  }
                   9492: 
                   9493: Will print out:
1.191     harris41 9494: 
1.394     bowersj2 9495:  %history{1:foo} = bar
                   9496:  %history{1:keys} = foo:timestamp
                   9497:  %history{1:timestamp} = 990455579
                   9498:  %history{2:bar} = foo
                   9499:  %history{2:foo} = notbar
                   9500:  %history{2:keys} = foo:bar:timestamp
                   9501:  %history{2:timestamp} = 990455580
                   9502:  %history{bar} = foo
                   9503:  %history{foo} = notbar
                   9504:  %history{timestamp} = 990455580
                   9505:  %history{version} = 2
                   9506: 
                   9507: Note that the special hash entries C<keys>, C<version> and
                   9508: C<timestamp> were added to the hash. C<version> will be equal to the
                   9509: total number of versions of the data that have been stored. The
                   9510: C<timestamp> attribute will be the UNIX time the hash was
                   9511: stored. C<keys> is available in every historical section to list which
                   9512: keys were added or changed at a specific historical revision of a
                   9513: hash.
                   9514: 
                   9515: B<Warning>: do not store the hash that restore returns directly. This
                   9516: will cause a mess since it will restore the historical keys as if the
                   9517: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 9518: 
1.394     bowersj2 9519: Calling convention:
1.191     harris41 9520: 
1.394     bowersj2 9521:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   9522:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 9523: 
1.394     bowersj2 9524: For more detailed information, see lonnet specific documentation.
1.191     harris41 9525: 
1.394     bowersj2 9526: =head1 RETURN MESSAGES
1.191     harris41 9527: 
1.394     bowersj2 9528: =over 4
1.191     harris41 9529: 
1.394     bowersj2 9530: =item * B<con_lost>: unable to contact remote host
1.191     harris41 9531: 
1.394     bowersj2 9532: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   9533: when the connection is brought back up
1.191     harris41 9534: 
1.394     bowersj2 9535: =item * B<con_failed>: unable to contact remote host and unable to save message
                   9536: for later delivery
1.191     harris41 9537: 
1.967     bisitz   9538: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 9539: 
1.394     bowersj2 9540: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 9541: that was requested
1.191     harris41 9542: 
1.243     albertel 9543: =back
1.191     harris41 9544: 
1.243     albertel 9545: =head1 PUBLIC SUBROUTINES
1.191     harris41 9546: 
1.243     albertel 9547: =head2 Session Environment Functions
1.191     harris41 9548: 
1.243     albertel 9549: =over 4
1.191     harris41 9550: 
1.394     bowersj2 9551: =item * 
                   9552: X<appenv()>
1.949     raeburn  9553: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 9554: the user envirnoment file, and will be restored for each access this
1.620     albertel 9555: user makes during this session, also modifies the %env for the current
1.949     raeburn  9556: process. Optional rolesarrayref - if defined contains a reference to an array
                   9557: of roles which are exempt from the restriction on modifying user.role entries 
                   9558: in the user's environment.db and in %env.    
1.191     harris41 9559: 
                   9560: =item *
1.394     bowersj2 9561: X<delenv()>
1.987     raeburn  9562: B<delenv($delthis,$regexp)>: removes all items from the session
                   9563: environment file that begin with $delthis. If the 
                   9564: optional second arg - $regexp - is true, $delthis is treated as a 
                   9565: regular expression, otherwise \Q$delthis\E is used. 
                   9566: The values are also deleted from the current processes %env.
1.191     harris41 9567: 
1.795     albertel 9568: =item * get_env_multiple($name) 
                   9569: 
                   9570: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   9571: values may be defined and end up as an array ref.
                   9572: 
                   9573: returns an array of values
                   9574: 
1.243     albertel 9575: =back
                   9576: 
                   9577: =head2 User Information
1.191     harris41 9578: 
1.243     albertel 9579: =over 4
1.191     harris41 9580: 
                   9581: =item *
1.394     bowersj2 9582: X<queryauthenticate()>
                   9583: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 9584: authentication scheme
                   9585: 
                   9586: =item *
1.394     bowersj2 9587: X<authenticate()>
                   9588: B<authenticate($uname,$upass,$udom)>: try to
                   9589: authenticate user from domain's lib servers (first use the current
                   9590: one). C<$upass> should be the users password.
1.191     harris41 9591: 
                   9592: =item *
1.394     bowersj2 9593: X<homeserver()>
                   9594: B<homeserver($uname,$udom)>: find the server which has
                   9595: the user's directory and files (there must be only one), this caches
                   9596: the answer, and also caches if there is a borken connection.
1.191     harris41 9597: 
                   9598: =item *
1.394     bowersj2 9599: X<idget()>
                   9600: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   9601: (IDs are a unique resource in a domain, there must be only 1 ID per
                   9602: username, and only 1 username per ID in a specific domain) (returns
                   9603: hash: id=>name,id=>name)
1.191     harris41 9604: 
                   9605: =item *
1.394     bowersj2 9606: X<idrget()>
                   9607: B<idrget($udom,@unames)>: find the IDs behind a list of
                   9608: usernames (returns hash: name=>id,name=>id)
1.191     harris41 9609: 
                   9610: =item *
1.394     bowersj2 9611: X<idput()>
                   9612: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 9613: 
                   9614: =item *
1.394     bowersj2 9615: X<rolesinit()>
                   9616: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 9617: 
                   9618: =item *
1.551     albertel 9619: X<getsection()>
                   9620: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 9621: course $cname, return section name/number or '' for "not in course"
                   9622: and '-1' for "no section"
                   9623: 
                   9624: =item *
1.394     bowersj2 9625: X<userenvironment()>
                   9626: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 9627: passed in @what from the requested user's environment, returns a hash
                   9628: 
1.858     raeburn  9629: =item * 
                   9630: X<userlog_query()>
1.859     albertel 9631: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   9632: activity.log file. %filters defines filters applied when parsing the
                   9633: log file. These can be start or end timestamps, or the type of action
                   9634: - log to look for Login or Logout events, check for Checkin or
                   9635: Checkout, role for role selection. The response is in the form
                   9636: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   9637: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  9638: 
1.243     albertel 9639: =back
                   9640: 
                   9641: =head2 User Roles
                   9642: 
                   9643: =over 4
                   9644: 
                   9645: =item *
                   9646: 
1.810     raeburn  9647: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 9648:  F: full access
                   9649:  U,I,K: authentication modes (cxx only)
                   9650:  '': forbidden
                   9651:  1: user needs to choose course
                   9652:  2: browse allowed
1.766     albertel 9653:  A: passphrase authentication needed
1.243     albertel 9654: 
                   9655: =item *
                   9656: 
                   9657: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   9658: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   9659: and course level
                   9660: 
                   9661: =item *
                   9662: 
1.988     raeburn  9663: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   9664: (rolesplain.tab); plain text explanation of a user role term.
                   9665: $type is Course (default) or Group.
                   9666: If $forcedefault evaluates to true, text returned will be default 
                   9667: text for $type. Otherwise, if this is a course, the text returned 
                   9668: will be a custom name for the role (if defined in the course's 
                   9669: environment).  If no custom name is defined the default is returned.
                   9670:    
1.832     raeburn  9671: =item *
                   9672: 
1.935     raeburn  9673: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  9674: All arguments are optional. Returns a hash of a roles, either for
                   9675: co-author/assistant author roles for a user's Construction Space
1.906     albertel 9676: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  9677: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   9678: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   9679: For each key, value is set to colon-separated start and end times for
                   9680: the role.  If no username and domain are specified, will default to
1.934     raeburn  9681: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  9682: of role statuses (active, future or previous), roles 
                   9683: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   9684: to restrict the list of roles reported. If no array ref is 
                   9685: provided for types, will default to return only active roles.
1.834     albertel 9686: 
1.243     albertel 9687: =back
                   9688: 
                   9689: =head2 User Modification
                   9690: 
                   9691: =over 4
                   9692: 
                   9693: =item *
                   9694: 
1.957     raeburn  9695: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 9696: user for the level given by URL.  Optional start and end dates (leave empty
                   9697: string or zero for "no date")
1.191     harris41 9698: 
                   9699: =item *
                   9700: 
1.243     albertel 9701: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   9702: change a users, password, possible return values are: ok,
                   9703: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   9704: refused
1.191     harris41 9705: 
                   9706: =item *
                   9707: 
1.243     albertel 9708: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9709: 
                   9710: =item *
                   9711: 
1.963     raeburn  9712: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
                   9713:            $forceid,$desiredhome,$email,$inststatus) : 
1.243     albertel 9714: modify user
1.191     harris41 9715: 
                   9716: =item *
                   9717: 
1.286     matthew  9718: modifystudent
                   9719: 
1.957     raeburn  9720: modify a student's enrollment and identification information.
1.286     matthew  9721: The course id is resolved based on the current users environment.  
                   9722: This means the envoking user must be a course coordinator or otherwise
                   9723: associated with a course.
                   9724: 
1.297     matthew  9725: This call is essentially a wrapper for lonnet::modifyuser and
                   9726: lonnet::modify_student_enrollment
1.286     matthew  9727: 
                   9728: Inputs: 
                   9729: 
                   9730: =over 4
                   9731: 
1.957     raeburn  9732: =item B<$udom> Student's loncapa domain
1.286     matthew  9733: 
1.957     raeburn  9734: =item B<$uname> Student's loncapa login name
1.286     matthew  9735: 
1.964     bisitz   9736: =item B<$uid> Student/Employee ID
1.286     matthew  9737: 
1.957     raeburn  9738: =item B<$umode> Student's authentication mode
1.286     matthew  9739: 
1.957     raeburn  9740: =item B<$upass> Student's password
1.286     matthew  9741: 
1.957     raeburn  9742: =item B<$first> Student's first name
1.286     matthew  9743: 
1.957     raeburn  9744: =item B<$middle> Student's middle name
1.286     matthew  9745: 
1.957     raeburn  9746: =item B<$last> Student's last name
1.286     matthew  9747: 
1.957     raeburn  9748: =item B<$gene> Student's generation
1.286     matthew  9749: 
1.957     raeburn  9750: =item B<$usec> Student's section in course
1.286     matthew  9751: 
                   9752: =item B<$end> Unix time of the roles expiration
                   9753: 
                   9754: =item B<$start> Unix time of the roles start date
                   9755: 
                   9756: =item B<$forceid> If defined, allow $uid to be changed
                   9757: 
                   9758: =item B<$desiredhome> server to use as home server for student
                   9759: 
1.957     raeburn  9760: =item B<$email> Student's permanent e-mail address
                   9761: 
                   9762: =item B<$type> Type of enrollment (auto or manual)
                   9763: 
1.963     raeburn  9764: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   9765: 
                   9766: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  9767: 
1.963     raeburn  9768: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  9769: 
1.963     raeburn  9770: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  9771: 
1.963     raeburn  9772: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  9773: 
1.286     matthew  9774: =back
1.297     matthew  9775: 
                   9776: =item *
                   9777: 
                   9778: modify_student_enrollment
                   9779: 
                   9780: Change a students enrollment status in a class.  The environment variable
                   9781: 'role.request.course' must be defined for this function to proceed.
                   9782: 
                   9783: Inputs:
                   9784: 
                   9785: =over 4
                   9786: 
                   9787: =item $udom, students domain
                   9788: 
                   9789: =item $uname, students name
                   9790: 
                   9791: =item $uid, students user id
                   9792: 
                   9793: =item $first, students first name
                   9794: 
                   9795: =item $middle
                   9796: 
                   9797: =item $last
                   9798: 
                   9799: =item $gene
                   9800: 
                   9801: =item $usec
                   9802: 
                   9803: =item $end
                   9804: 
                   9805: =item $start
                   9806: 
1.957     raeburn  9807: =item $type
                   9808: 
                   9809: =item $locktype
                   9810: 
                   9811: =item $cid
                   9812: 
                   9813: =item $selfenroll
                   9814: 
                   9815: =item $context
                   9816: 
1.297     matthew  9817: =back
                   9818: 
1.191     harris41 9819: 
                   9820: =item *
                   9821: 
1.243     albertel 9822: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9823: custom role; give a custom role to a user for the level given by URL.  Specify
                   9824: name and domain of role author, and role name
1.191     harris41 9825: 
                   9826: =item *
                   9827: 
1.243     albertel 9828: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9829: 
                   9830: =item *
                   9831: 
1.243     albertel 9832: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9833: 
                   9834: =back
                   9835: 
                   9836: =head2 Course Infomation
                   9837: 
                   9838: =over 4
1.191     harris41 9839: 
                   9840: =item *
                   9841: 
1.631     albertel 9842: coursedescription($courseid) : returns a hash of information about the
                   9843: specified course id, including all environment settings for the
                   9844: course, the description of the course will be in the hash under the
                   9845: key 'description'
1.191     harris41 9846: 
                   9847: =item *
                   9848: 
1.624     albertel 9849: resdata($name,$domain,$type,@which) : request for current parameter
                   9850: setting for a specific $type, where $type is either 'course' or 'user',
                   9851: @what should be a list of parameters to ask about. This routine caches
                   9852: answers for 5 minutes.
1.243     albertel 9853: 
1.877     foxr     9854: =item *
                   9855: 
                   9856: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9857: data base, returning a hash that is keyed by the resource name and has
                   9858: values that are the resource value.  I believe that the timestamps and
                   9859: versions are also returned.
                   9860: 
                   9861: 
1.243     albertel 9862: =back
                   9863: 
                   9864: =head2 Course Modification
                   9865: 
                   9866: =over 4
1.191     harris41 9867: 
                   9868: =item *
                   9869: 
1.243     albertel 9870: writecoursepref($courseid,%prefs) : write preferences (environment
                   9871: database) for a course
1.191     harris41 9872: 
                   9873: =item *
                   9874: 
1.243     albertel 9875: createcourse($udom,$description,$url) : make/modify course
                   9876: 
                   9877: =back
                   9878: 
                   9879: =head2 Resource Subroutines
                   9880: 
                   9881: =over 4
1.191     harris41 9882: 
                   9883: =item *
                   9884: 
1.243     albertel 9885: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9886: 
                   9887: =item *
                   9888: 
1.243     albertel 9889: repcopy($filename) : subscribes to the requested file, and attempts to
                   9890: replicate from the owning library server, Might return
1.607     raeburn  9891: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9892: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9893: resource. Expects the local filesystem pathname
                   9894: (/home/httpd/html/res/....)
                   9895: 
                   9896: =back
                   9897: 
                   9898: =head2 Resource Information
                   9899: 
                   9900: =over 4
1.191     harris41 9901: 
                   9902: =item *
                   9903: 
1.243     albertel 9904: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9905: a vairety of different possible values, $varname should be a request
                   9906: string, and the other parameters can be used to specify who and what
                   9907: one is asking about.
                   9908: 
                   9909: Possible values for $varname are environment.lastname (or other item
                   9910: from the envirnment hash), user.name (or someother aspect about the
                   9911: user), resource.0.maxtries (or some other part and parameter of a
                   9912: resource)
1.204     albertel 9913: 
                   9914: =item *
                   9915: 
1.243     albertel 9916: directcondval($number) : get current value of a condition; reads from a state
                   9917: string
1.204     albertel 9918: 
                   9919: =item *
                   9920: 
1.243     albertel 9921: condval($condidx) : value of condition index based on state
1.204     albertel 9922: 
                   9923: =item *
                   9924: 
1.243     albertel 9925: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9926: resource's metadata, $what should be either a specific key, or either
                   9927: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9928: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9929: 
                   9930: this function automatically caches all requests
1.191     harris41 9931: 
                   9932: =item *
                   9933: 
1.243     albertel 9934: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9935: network of library servers; returns file handle of where SQL and regex results
                   9936: will be stored for query
1.191     harris41 9937: 
                   9938: =item *
                   9939: 
1.243     albertel 9940: symbread($filename) : return symbolic list entry (filename argument optional);
                   9941: returns the data handle
1.191     harris41 9942: 
                   9943: =item *
                   9944: 
1.243     albertel 9945: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9946: a possible symb for the URL in $thisfn, and if is an encryypted
                   9947: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9948: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9949: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9950: 
1.191     harris41 9951: 
                   9952: =item *
                   9953: 
1.243     albertel 9954: symbclean($symb) : removes versions numbers from a symb, returns the
                   9955: cleaned symb
1.191     harris41 9956: 
                   9957: =item *
                   9958: 
1.243     albertel 9959: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9960: course map, user must be in a course for it to work.
1.191     harris41 9961: 
                   9962: =item *
                   9963: 
1.243     albertel 9964: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9965: 
                   9966: =item *
                   9967: 
1.243     albertel 9968: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9969: a random seed, all arguments are optional, if they aren't sent it uses the
                   9970: environment to derive them. Note: if symb isn't sent and it can't get one
                   9971: from &symbread it will use the current time as its return value
1.191     harris41 9972: 
                   9973: =item *
                   9974: 
1.243     albertel 9975: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9976: unfakeable, receipt
1.191     harris41 9977: 
                   9978: =item *
                   9979: 
1.620     albertel 9980: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9981: 
                   9982: =item *
                   9983: 
1.243     albertel 9984: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9985: 
                   9986: =item *
                   9987: 
1.243     albertel 9988: 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 9989: 
                   9990: =item *
                   9991: 
1.243     albertel 9992: 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 9993: 
                   9994: =item *
                   9995: 
1.243     albertel 9996: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9997: 
                   9998: =item *
                   9999: 
1.243     albertel 10000: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   10001: forcing spreadsheet to reevaluate the resource scores next time.
                   10002: 
                   10003: =back
                   10004: 
                   10005: =head2 Storing/Retreiving Data
                   10006: 
                   10007: =over 4
1.191     harris41 10008: 
                   10009: =item *
                   10010: 
1.243     albertel 10011: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   10012: for this url; hashref needs to be given and should be a \%hashname; the
                   10013: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 10014: be derived from the env
1.191     harris41 10015: 
                   10016: =item *
                   10017: 
1.243     albertel 10018: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   10019: uses critical subroutine
1.191     harris41 10020: 
                   10021: =item *
                   10022: 
1.243     albertel 10023: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   10024: all args are optional
1.191     harris41 10025: 
                   10026: =item *
                   10027: 
1.717     albertel 10028: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   10029: dumps the complete (or key matching regexp) namespace into a hash
                   10030: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   10031: normally &store()ed into
                   10032: 
                   10033: $range should be either an integer '100' (give me the first 100
                   10034:                                            matching records)
                   10035:               or be  two integers sperated by a - with no spaces
                   10036:                  '30-50' (give me the 30th through the 50th matching
                   10037:                           records)
                   10038: 
                   10039: 
                   10040: =item *
                   10041: 
                   10042: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   10043: replaces a &store() version of data with a replacement set of data
                   10044: for a particular resource in a namespace passed in the $storehash hash 
                   10045: reference
                   10046: 
                   10047: =item *
                   10048: 
1.243     albertel 10049: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   10050: works very similar to store/cstore, but all data is stored in a
                   10051: temporary location and can be reset using tmpreset, $storehash should
                   10052: be a hash reference, returns nothing on success
1.191     harris41 10053: 
                   10054: =item *
                   10055: 
1.243     albertel 10056: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   10057: similar to restore, but all data is stored in a temporary location and
                   10058: can be reset using tmpreset. Returns a hash of values on success,
                   10059: error string otherwise.
1.191     harris41 10060: 
                   10061: =item *
                   10062: 
1.243     albertel 10063: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   10064: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 10065: 
                   10066: =item *
                   10067: 
1.243     albertel 10068: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   10069: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 10070: 
                   10071: =item *
                   10072: 
1.243     albertel 10073: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   10074: namesp ($udom and $uname are optional)
1.191     harris41 10075: 
                   10076: =item *
                   10077: 
1.702     albertel 10078: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 10079: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 10080: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  10081: 
1.702     albertel 10082: $range should be either an integer '100' (give me the first 100
                   10083:                                            matching records)
                   10084:               or be  two integers sperated by a - with no spaces
                   10085:                  '30-50' (give me the 30th through the 50th matching
                   10086:                           records)
1.449     matthew  10087: =item *
                   10088: 
                   10089: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   10090: $store can be a scalar, an array reference, or if the amount to be 
                   10091: incremented is > 1, a hash reference.
                   10092: 
                   10093: ($udom and $uname are optional)
1.191     harris41 10094: 
                   10095: =item *
                   10096: 
1.243     albertel 10097: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   10098: ($udom and $uname are optional)
1.191     harris41 10099: 
                   10100: =item *
                   10101: 
1.243     albertel 10102: cput($namespace,$storehash,$udom,$uname) : critical put
                   10103: ($udom and $uname are optional)
1.191     harris41 10104: 
                   10105: =item *
                   10106: 
1.748     albertel 10107: newput($namespace,$storehash,$udom,$uname) :
                   10108: 
                   10109: Attempts to store the items in the $storehash, but only if they don't
                   10110: currently exist, if this succeeds you can be certain that you have 
                   10111: successfully created a new key value pair in the $namespace db.
                   10112: 
                   10113: 
                   10114: Args:
                   10115:  $namespace: name of database to store values to
                   10116:  $storehash: hashref to store to the db
                   10117:  $udom: (optional) domain of user containing the db
                   10118:  $uname: (optional) name of user caontaining the db
                   10119: 
                   10120: Returns:
                   10121:  'ok' -> succeeded in storing all keys of $storehash
                   10122:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   10123:                         least <key> already existed in the db (other
                   10124:                         requested keys may also already exist)
1.967     bisitz   10125:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 10126:  'con_lost' -> unable to contact request server
                   10127:  'refused' -> action was not allowed by remote machine
                   10128: 
                   10129: 
                   10130: =item *
                   10131: 
1.243     albertel 10132: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   10133: reference filled in from namesp (encrypts the return communication)
                   10134: ($udom and $uname are optional)
1.191     harris41 10135: 
                   10136: =item *
                   10137: 
1.243     albertel 10138: log($udom,$name,$home,$message) : write to permanent log for user; use
                   10139: critical subroutine
                   10140: 
1.806     raeburn  10141: =item *
                   10142: 
1.860     raeburn  10143: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   10144: array reference filled in from namespace found in domain level on either
                   10145: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  10146: 
                   10147: =item *
                   10148: 
1.860     raeburn  10149: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   10150: domain level either on specified domain server ($uhome) or primary domain 
                   10151: server ($udom and $uhome are optional)
1.806     raeburn  10152: 
1.943     raeburn  10153: =item * 
                   10154: 
                   10155: get_domain_defaults($target_domain) : returns hash with defaults for
                   10156: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   10157: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   10158: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   10159: Values are retrieved from cache (if current), or from domain's configuration.db
                   10160: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   10161: or lonTabs/domain.tab. 
                   10162: 
                   10163: %domdefaults = &get_auth_defaults($target_domain);
                   10164: 
1.243     albertel 10165: =back
                   10166: 
                   10167: =head2 Network Status Functions
                   10168: 
                   10169: =over 4
1.191     harris41 10170: 
                   10171: =item *
                   10172: 
                   10173: dirlist($uri) : return directory list based on URI
                   10174: 
                   10175: =item *
                   10176: 
1.243     albertel 10177: spareserver() : find server with least workload from spare.tab
                   10178: 
1.986     foxr     10179: 
                   10180: =item *
                   10181: 
                   10182: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   10183: if there is no corresponding loncapa host.
                   10184: 
1.243     albertel 10185: =back
                   10186: 
1.986     foxr     10187: 
1.243     albertel 10188: =head2 Apache Request
                   10189: 
                   10190: =over 4
1.191     harris41 10191: 
                   10192: =item *
                   10193: 
1.243     albertel 10194: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   10195: localhost, posts hash
                   10196: 
                   10197: =back
                   10198: 
                   10199: =head2 Data to String to Data
                   10200: 
                   10201: =over 4
1.191     harris41 10202: 
                   10203: =item *
                   10204: 
1.243     albertel 10205: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   10206: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 10207: 
                   10208: =item *
                   10209: 
1.243     albertel 10210: hashref2str($hashref) : convert a hashref into a string complete with
                   10211: escaping and '=' and '&' separators, supports elements that are
                   10212: arrayrefs and hashrefs
1.191     harris41 10213: 
                   10214: =item *
                   10215: 
1.243     albertel 10216: arrayref2str($arrayref) : convert an arrayref into a string complete
                   10217: with escaping and '&' separators, supports elements that are arrayrefs
                   10218: and hashrefs
1.191     harris41 10219: 
                   10220: =item *
                   10221: 
1.243     albertel 10222: str2hash($string) : convert string to hash using unescaping and
                   10223: splitting on '=' and '&', supports elements that are arrayrefs and
                   10224: hashrefs
1.191     harris41 10225: 
                   10226: =item *
                   10227: 
1.243     albertel 10228: str2array($string) : convert string to hash using unescaping and
                   10229: splitting on '&', supports elements that are arrayrefs and hashrefs
                   10230: 
                   10231: =back
                   10232: 
                   10233: =head2 Logging Routines
                   10234: 
                   10235: =over 4
                   10236: 
                   10237: These routines allow one to make log messages in the lonnet.log and
                   10238: lonnet.perm logfiles.
1.191     harris41 10239: 
                   10240: =item *
                   10241: 
1.243     albertel 10242: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 10243: 
                   10244: =item *
                   10245: 
1.243     albertel 10246: logthis() : append message to the normal lonnet.log file, it gets
                   10247: preiodically rolled over and deleted.
1.191     harris41 10248: 
                   10249: =item *
                   10250: 
1.243     albertel 10251: logperm() : append a permanent message to lonnet.perm.log, this log
                   10252: file never gets deleted by any automated portion of the system, only
                   10253: messages of critical importance should go in here.
                   10254: 
                   10255: =back
                   10256: 
                   10257: =head2 General File Helper Routines
                   10258: 
                   10259: =over 4
1.191     harris41 10260: 
                   10261: =item *
                   10262: 
1.481     raeburn  10263: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   10264: (a) files in /uploaded
                   10265:   (i) If a local copy of the file exists - 
                   10266:       compares modification date of local copy with last-modified date for 
                   10267:       definitive version stored on home server for course. If local copy is 
                   10268:       stale, requests a new version from the home server and stores it. 
                   10269:       If the original has been removed from the home server, then local copy 
                   10270:       is unlinked.
                   10271:   (ii) If local copy does not exist -
                   10272:       requests the file from the home server and stores it. 
                   10273:   
                   10274:   If $caller is 'uploadrep':  
                   10275:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   10276:     for request for files originally uploaded via DOCS. 
                   10277:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   10278:   
                   10279:   Otherwise:
                   10280:      This indicates a call from the content generation phase of the request.
                   10281:      -  returns the entire contents of the file or -1.
                   10282:      
                   10283: (b) files in /res
                   10284:    - returns the entire contents of a file or -1; 
                   10285:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 10286: 
1.712     albertel 10287: 
                   10288: =item *
                   10289: 
                   10290: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   10291:                   reference
                   10292: 
                   10293: returns either a stat() list of data about the file or an empty list
                   10294: if the file doesn't exist or couldn't find out about it (connection
                   10295: problems or user unknown)
                   10296: 
1.191     harris41 10297: =item *
                   10298: 
1.243     albertel 10299: filelocation($dir,$file) : returns file system location of a file
                   10300: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   10301: directory that relative $file lookups are to looked in ($dir of /a/dir
                   10302: and a file of ../bob will become /a/bob)
1.191     harris41 10303: 
                   10304: =item *
                   10305: 
                   10306: hreflocation($dir,$file) : returns file system location or a URL; same as
                   10307: filelocation except for hrefs
                   10308: 
                   10309: =item *
                   10310: 
                   10311: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   10312: 
1.243     albertel 10313: =back
                   10314: 
1.608     albertel 10315: =head2 Usererfile file routines (/uploaded*)
                   10316: 
                   10317: =over 4
                   10318: 
                   10319: =item *
                   10320: 
                   10321: userfileupload(): main rotine for putting a file in a user or course's
                   10322:                   filespace, arguments are,
                   10323: 
1.620     albertel 10324:  formname - required - this is the name of the element in $env where the
1.608     albertel 10325:            filename, and the contents of the file to create/modifed exist
1.620     albertel 10326:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   10327:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 10328:  coursedoc - if true, store the file in the course of the active role
                   10329:              of the current user
                   10330:  subdir - required - subdirectory to put the file in under ../userfiles/
                   10331:          if undefined, it will be placed in "unknown"
                   10332: 
                   10333:  (This routine calls clean_filename() to remove any dangerous
                   10334:  characters from the filename, and then calls finuserfileupload() to
                   10335:  complete the transaction)
                   10336: 
                   10337:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10338:  and /adm/notfound.html if unsuccessful
                   10339: 
                   10340: =item *
                   10341: 
                   10342: clean_filename(): routine for cleaing a filename up for storage in
                   10343:                  userfile space, argument is:
                   10344: 
                   10345:  filename - proposed filename
                   10346: 
                   10347: returns: the new clean filename
                   10348: 
                   10349: =item *
                   10350: 
                   10351: finishuserfileupload(): routine that creaes and sends the file to
                   10352: userspace, probably shouldn't be called directly
                   10353: 
                   10354:   docuname: username or courseid of destination for the file
                   10355:   docudom: domain of user/course of destination for the file
                   10356:   formname: same as for userfileupload()
                   10357:   fname: filename (inculding subdirectories) for the file
                   10358: 
                   10359:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10360:  and /adm/notfound.html if unsuccessful
                   10361: 
                   10362: =item *
                   10363: 
                   10364: renameuserfile(): renames an existing userfile to a new name
                   10365: 
                   10366:   Args:
                   10367:    docuname: username or courseid of destination for the file
                   10368:    docudom: domain of user/course of destination for the file
                   10369:    old: current file name (including any subdirs under userfiles)
                   10370:    new: desired file name (including any subdirs under userfiles)
                   10371: 
                   10372: =item *
                   10373: 
                   10374: mkdiruserfile(): creates a directory is a userfiles dir
                   10375: 
                   10376:   Args:
                   10377:    docuname: username or courseid of destination for the file
                   10378:    docudom: domain of user/course of destination for the file
                   10379:    dir: dir to create (including any subdirs under userfiles)
                   10380: 
                   10381: =item *
                   10382: 
                   10383: removeuserfile(): removes a file that exists in userfiles
                   10384: 
                   10385:   Args:
                   10386:    docuname: username or courseid of destination for the file
                   10387:    docudom: domain of user/course of destination for the file
                   10388:    fname: filname to delete (including any subdirs under userfiles)
                   10389: 
                   10390: =item *
                   10391: 
                   10392: removeuploadedurl(): convience function for removeuserfile()
                   10393: 
                   10394:   Args:
                   10395:    url:  a full /uploaded/... url to delete
                   10396: 
1.747     albertel 10397: =item * 
                   10398: 
                   10399: get_portfile_permissions():
                   10400:   Args:
                   10401:     domain: domain of user or course contain the portfolio files
                   10402:     user: name of user or num of course contain the portfolio files
                   10403:   Returns:
                   10404:     hashref of a dump of the proper file_permissions.db
                   10405:    
                   10406: 
                   10407: =item * 
                   10408: 
                   10409: get_access_controls():
                   10410: 
                   10411: Args:
                   10412:   current_permissions: the hash ref returned from get_portfile_permissions()
                   10413:   group: (optional) the group you want the files associated with
                   10414:   file: (optional) the file you want access info on
                   10415: 
                   10416: Returns:
1.749     raeburn  10417:     a hash (keys are file names) of hashes containing
                   10418:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   10419:         values are XML containing access control settings (see below) 
1.747     albertel 10420: 
                   10421: Internal notes:
                   10422: 
1.749     raeburn  10423:  access controls are stored in file_permissions.db as key=value pairs.
                   10424:     key -> path to file/file_name\0uniqueID:scope_end_start
                   10425:         where scope -> public,guest,course,group,domains or users.
                   10426:               end -> UNIX time for end of access (0 -> no end date)
                   10427:               start -> UNIX time for start of access
                   10428: 
                   10429:     value -> XML description of access control
                   10430:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   10431:             <start></start>
                   10432:             <end></end>
                   10433: 
                   10434:             <password></password>  for scope type = guest
                   10435: 
                   10436:             <domain></domain>     for scope type = course or group
                   10437:             <number></number>
                   10438:             <roles id="">
                   10439:              <role></role>
                   10440:              <access></access>
                   10441:              <section></section>
                   10442:              <group></group>
                   10443:             </roles>
                   10444: 
                   10445:             <dom></dom>         for scope type = domains
                   10446: 
                   10447:             <users>             for scope type = users
                   10448:              <user>
                   10449:               <uname></uname>
                   10450:               <udom></udom>
                   10451:              </user>
                   10452:             </users>
                   10453:            </scope> 
                   10454:               
                   10455:  Access data is also aggregated for each file in an additional key=value pair:
                   10456:  key -> path to file/file_name\0accesscontrol 
                   10457:  value -> reference to hash
                   10458:           hash contains key = value pairs
                   10459:           where key = uniqueID:scope_end_start
                   10460:                 value = UNIX time record was last updated
                   10461: 
                   10462:           Used to improve speed of look-ups of access controls for each file.  
                   10463:  
                   10464:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   10465: 
                   10466: modify_access_controls():
                   10467: 
                   10468: Modifies access controls for a portfolio file
                   10469: Args
                   10470: 1. file name
                   10471: 2. reference to hash of required changes,
                   10472: 3. domain
                   10473: 4. username
                   10474:   where domain,username are the domain of the portfolio owner 
                   10475:   (either a user or a course) 
                   10476: 
                   10477: Returns:
                   10478: 1. result of additions or updates ('ok' or 'error', with error message). 
                   10479: 2. result of deletions ('ok' or 'error', with error message).
                   10480: 3. reference to hash of any new or updated access controls.
                   10481: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   10482:    key = integer (inbound ID)
                   10483:    value = uniqueID  
1.747     albertel 10484: 
1.608     albertel 10485: =back
                   10486: 
1.243     albertel 10487: =head2 HTTP Helper Routines
                   10488: 
                   10489: =over 4
                   10490: 
1.191     harris41 10491: =item *
                   10492: 
                   10493: escape() : unpack non-word characters into CGI-compatible hex codes
                   10494: 
                   10495: =item *
                   10496: 
                   10497: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   10498: 
1.243     albertel 10499: =back
                   10500: 
                   10501: =head1 PRIVATE SUBROUTINES
                   10502: 
                   10503: =head2 Underlying communication routines (Shouldn't call)
                   10504: 
                   10505: =over 4
                   10506: 
                   10507: =item *
                   10508: 
                   10509: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   10510: 
                   10511: =item *
                   10512: 
                   10513: reply() : uses subreply to send a message to remote machine, logs all failures
                   10514: 
                   10515: =item *
                   10516: 
                   10517: critical() : passes a critical message to another server; if cannot
                   10518: get through then place message in connection buffer directory and
                   10519: returns con_delayed, if incapable of saving message, returns
                   10520: con_failed
                   10521: 
                   10522: =item *
                   10523: 
                   10524: reconlonc() : tries to reconnect lonc client processes.
                   10525: 
                   10526: =back
                   10527: 
                   10528: =head2 Resource Access Logging
                   10529: 
                   10530: =over 4
                   10531: 
                   10532: =item *
                   10533: 
                   10534: flushcourselogs() : flush (save) buffer logs and access logs
                   10535: 
                   10536: =item *
                   10537: 
                   10538: courselog($what) : save message for course in hash
                   10539: 
                   10540: =item *
                   10541: 
                   10542: courseacclog($what) : save message for course using &courselog().  Perform
                   10543: special processing for specific resource types (problems, exams, quizzes, etc).
                   10544: 
1.191     harris41 10545: =item *
                   10546: 
                   10547: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   10548: as a PerlChildExitHandler
1.243     albertel 10549: 
                   10550: =back
                   10551: 
                   10552: =head2 Other
                   10553: 
                   10554: =over 4
                   10555: 
                   10556: =item *
                   10557: 
                   10558: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 10559: 
                   10560: =back
                   10561: 
                   10562: =cut
1.877     foxr     10563: 

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