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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1011  ! raeburn     4: # $Id: lonnet.pm,v 1.1010 2009/08/08 00:36:10 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.871     albertel   78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.968     raeburn    79:             $_64bit %env %protocol);
1.871     albertel   80: 
                     81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     82:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     83:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        84:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        85: 
1.1       albertel   86: use IO::Socket;
1.31      www        87: use GDBM_File;
1.208     albertel   88: use HTML::LCParser;
1.88      www        89: use Fcntl qw(:flock);
1.870     albertel   90: use Storable qw(thaw nfreeze);
1.539     albertel   91: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   92: use Cache::Memcached;
1.676     albertel   93: use Digest::MD5;
1.790     albertel   94: use Math::Random;
1.807     albertel   95: use LONCAPA qw(:DEFAULT :match);
1.740     www        96: use LONCAPA::Configuration;
1.676     albertel   97: 
1.195     www        98: my $readit;
1.550     foxr       99: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  100: 
1.977     amueller  101: my $upload_photo_form = 0; #Variable to check  when user upload a photo 0=not 1=true
                    102: 
1.619     albertel  103: require Exporter;
                    104: 
                    105: our @ISA = qw (Exporter);
                    106: our @EXPORT = qw(%env);
                    107: 
1.449     matthew   108: 
1.1       albertel  109: # --------------------------------------------------------------------- Logging
1.729     www       110: {
                    111:     my $logid;
                    112:     sub instructor_log {
1.957     raeburn   113: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    114:         if (($cnum eq '') || ($cdom eq '')) {
                    115:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    116:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    117:         }
1.729     www       118: 	$logid++;
1.957     raeburn   119:         my $now = time();
                    120: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       121: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       122: 				    { $id => {
                    123: 					'exe_uname' => $env{'user.name'},
                    124: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   125: 					'exe_time'  => $now,
1.730     www       126: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    127: 					'delflag'   => $delflag,
                    128: 					'logentry'  => $storehash,
                    129: 					'uname'     => $uname,
                    130: 					'udom'      => $udom,
                    131: 				    }
1.957     raeburn   132: 				  },$cdom,$cnum);
1.729     www       133:     }
                    134: }
1.1       albertel  135: 
1.163     harris41  136: sub logtouch {
                    137:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  138:     unless (-e "$execdir/logs/lonnet.log") {	
                    139: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  140: 	close $fh;
                    141:     }
                    142:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    143:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    144: }
                    145: 
1.1       albertel  146: sub logthis {
                    147:     my $message=shift;
                    148:     my $execdir=$perlvar{'lonDaemons'};
                    149:     my $now=time;
                    150:     my $local=localtime($now);
1.448     albertel  151:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      152: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    153: 	print $fh $logstring;
1.448     albertel  154: 	close($fh);
                    155:     }
1.1       albertel  156:     return 1;
                    157: }
                    158: 
                    159: sub logperm {
                    160:     my $message=shift;
                    161:     my $execdir=$perlvar{'lonDaemons'};
                    162:     my $now=time;
                    163:     my $local=localtime($now);
1.448     albertel  164:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    165: 	print $fh "$now:$message:$local\n";
                    166: 	close($fh);
                    167:     }
1.1       albertel  168:     return 1;
                    169: }
                    170: 
1.850     albertel  171: sub create_connection {
1.853     albertel  172:     my ($hostname,$lonid) = @_;
1.851     albertel  173:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  174: 				     Type    => SOCK_STREAM,
                    175: 				     Timeout => 10);
                    176:     return 0 if (!$client);
1.890     albertel  177:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  178:     my $result = <$client>;
                    179:     chomp($result);
                    180:     return 1 if ($result eq 'done');
                    181:     return 0;
                    182: }
                    183: 
1.983     raeburn   184: sub get_server_timezone {
                    185:     my ($cnum,$cdom) = @_;
                    186:     my $home=&homeserver($cnum,$cdom);
                    187:     if ($home ne 'no_host') {
                    188:         my $cachetime = 24*3600;
                    189:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    190:         if (defined($cached)) {
                    191:             return $timezone;
                    192:         } else {
                    193:             my $timezone = &reply('servertimezone',$home);
                    194:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    195:         }
                    196:     }
                    197: }
1.850     albertel  198: 
1.993     raeburn   199: sub get_server_loncaparev {
                    200:     my ($dom,$lonhost) = @_;
                    201:     if (defined($lonhost)) {
                    202:         if (!defined(&hostname($lonhost))) {
                    203:             undef($lonhost);
                    204:         }
                    205:     }
                    206:     if (!defined($lonhost)) {
                    207:         if (defined(&domain($dom,'primary'))) {
                    208:             $lonhost=&domain($dom,'primary');
                    209:             if ($lonhost eq 'no_host') {
                    210:                 undef($lonhost);
                    211:             }
                    212:         }
                    213:     }
                    214:     if (defined($lonhost)) {
                    215:         my $cachetime = 24*3600;
                    216:         my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    217:         if (defined($cached)) {
                    218:             return $loncaparev;
                    219:         } else {
                    220:             my $loncaparev = &reply('serverloncaparev',$lonhost);
                    221:             return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
                    222:         }
                    223:     }
                    224: }
                    225: 
1.1       albertel  226: # -------------------------------------------------- Non-critical communication
                    227: sub subreply {
                    228:     my ($cmd,$server)=@_;
1.838     albertel  229:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      230:     #
                    231:     #  With loncnew process trimming, there's a timing hole between lonc server
                    232:     #  process exit and the master server picking up the listen on the AF_UNIX
                    233:     #  socket.  In that time interval, a lock file will exist:
                    234: 
                    235:     my $lockfile=$peerfile.".lock";
                    236:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    237: 	sleep(1);
                    238:     }
                    239:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      240:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      241:     #
1.550     foxr      242:     #   We'll give the connection a few tries before abandoning it.  If
                    243:     #   connection is not possible, we'll con_lost back to the client.
                    244:     #   
                    245:     my $client;
                    246:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    247: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    248: 				      Type    => SOCK_STREAM,
                    249: 				      Timeout => 10);
1.869     albertel  250: 	if ($client) {
1.550     foxr      251: 	    last;		# Connected!
1.850     albertel  252: 	} else {
1.853     albertel  253: 	    &create_connection(&hostname($server),$server);
1.550     foxr      254: 	}
1.850     albertel  255:         sleep(1);		# Try again later if failed connection.
1.550     foxr      256:     }
                    257:     my $answer;
                    258:     if ($client) {
1.704     albertel  259: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      260: 	$answer=<$client>;
                    261: 	if (!$answer) { $answer="con_lost"; }
                    262: 	chomp($answer);
                    263:     } else {
                    264: 	$answer = 'con_lost';	# Failed connection.
                    265:     }
1.1       albertel  266:     return $answer;
                    267: }
                    268: 
                    269: sub reply {
                    270:     my ($cmd,$server)=@_;
1.838     albertel  271:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  272:     my $answer=subreply($cmd,$server);
1.65      www       273:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  274:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       275:                 " $cmd to $server returned $answer</font>");
                    276:     }
1.1       albertel  277:     return $answer;
                    278: }
                    279: 
                    280: # ----------------------------------------------------------- Send USR1 to lonc
                    281: 
                    282: sub reconlonc {
1.891     albertel  283:     my ($lonid) = @_;
                    284:     my $hostname = &hostname($lonid);
                    285:     if ($lonid) {
                    286: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    287: 	if ($hostname && -e $peerfile) {
                    288: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    289: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    290: 					     Type    => SOCK_STREAM,
                    291: 					     Timeout => 10);
                    292: 	    if ($client) {
                    293: 		print $client ("reset_retries\n");
                    294: 		my $answer=<$client>;
                    295: 		#reset just this one.
                    296: 	    }
                    297: 	}
                    298: 	return;
                    299:     }
                    300: 
1.836     www       301:     &logthis("Trying to reconnect lonc");
1.1       albertel  302:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  303:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  304: 	my $loncpid=<$fh>;
                    305:         chomp($loncpid);
                    306:         if (kill 0 => $loncpid) {
                    307: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    308:             kill USR1 => $loncpid;
                    309:             sleep 1;
1.836     www       310:          } else {
1.12      www       311: 	    &logthis(
1.672     albertel  312:                "<font color=\"blue\">WARNING:".
1.12      www       313:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  314:         }
                    315:     } else {
1.836     www       316: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  317:     }
                    318: }
                    319: 
                    320: # ------------------------------------------------------ Critical communication
1.12      www       321: 
1.1       albertel  322: sub critical {
                    323:     my ($cmd,$server)=@_;
1.838     albertel  324:     unless (&hostname($server)) {
1.672     albertel  325:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       326:                " Critical message to unknown server ($server)</font>");
                    327:         return 'no_such_host';
                    328:     }
1.1       albertel  329:     my $answer=reply($cmd,$server);
                    330:     if ($answer eq 'con_lost') {
                    331: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  332: 	my $answer=reply($cmd,$server);
1.1       albertel  333:         if ($answer eq 'con_lost') {
                    334:             my $now=time;
                    335:             my $middlename=$cmd;
1.5       www       336:             $middlename=substr($middlename,0,16);
1.1       albertel  337:             $middlename=~s/\W//g;
                    338:             my $dfilename=
1.305     www       339:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    340:             $dumpcount++;
1.1       albertel  341:             {
1.448     albertel  342: 		my $dfh;
                    343: 		if (open($dfh,">$dfilename")) {
                    344: 		    print $dfh "$cmd\n"; 
                    345: 		    close($dfh);
                    346: 		}
1.1       albertel  347:             }
                    348:             sleep 2;
                    349:             my $wcmd='';
                    350:             {
1.448     albertel  351: 		my $dfh;
                    352: 		if (open($dfh,"<$dfilename")) {
                    353: 		    $wcmd=<$dfh>; 
                    354: 		    close($dfh);
                    355: 		}
1.1       albertel  356:             }
                    357:             chomp($wcmd);
1.7       www       358:             if ($wcmd eq $cmd) {
1.672     albertel  359: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       360:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  361:                 &logperm("D:$server:$cmd");
                    362: 	        return 'con_delayed';
                    363:             } else {
1.672     albertel  364:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       365:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  366:                 &logperm("F:$server:$cmd");
                    367:                 return 'con_failed';
                    368:             }
                    369:         }
                    370:     }
                    371:     return $answer;
1.405     albertel  372: }
                    373: 
1.755     albertel  374: # ------------------------------------------- check if return value is an error
                    375: 
                    376: sub error {
                    377:     my ($result) = @_;
1.756     albertel  378:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  379: 	if ($2 == 2) { return undef; }
                    380: 	return $1;
                    381:     }
                    382:     return undef;
                    383: }
                    384: 
1.783     albertel  385: sub convert_and_load_session_env {
                    386:     my ($lonidsdir,$handle)=@_;
                    387:     my @profile;
                    388:     {
1.917     albertel  389: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    390: 	if (!$opened) {
1.915     albertel  391: 	    return 0;
                    392: 	}
1.783     albertel  393: 	flock($idf,LOCK_SH);
                    394: 	@profile=<$idf>;
                    395: 	close($idf);
                    396:     }
                    397:     my %temp_env;
                    398:     foreach my $line (@profile) {
1.786     albertel  399: 	if ($line !~ m/=/) {
                    400: 	    return 0;
                    401: 	}
1.783     albertel  402: 	chomp($line);
                    403: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    404: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    405:     }
                    406:     unlink("$lonidsdir/$handle.id");
                    407:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    408: 	    0640)) {
                    409: 	%disk_env = %temp_env;
                    410: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    411: 	untie(%disk_env);
                    412:     }
1.786     albertel  413:     return 1;
1.783     albertel  414: }
                    415: 
1.374     www       416: # ------------------------------------------- Transfer profile into environment
1.780     albertel  417: my $env_loaded;
                    418: sub transfer_profile_to_env {
1.788     albertel  419:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    420:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       421: 
1.720     albertel  422:     if (!defined($lonidsdir)) {
                    423: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    424:     }
                    425:     if (!defined($handle)) {
                    426:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    427:     }
                    428: 
1.786     albertel  429:     my $convert;
                    430:     {
1.917     albertel  431:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    432: 	if (!$opened) {
1.915     albertel  433: 	    return;
                    434: 	}
1.786     albertel  435: 	flock($idf,LOCK_SH);
                    436: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    437: 		&GDBM_READER(),0640)) {
                    438: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    439: 	    untie(%disk_env);
                    440: 	} else {
                    441: 	    $convert = 1;
                    442: 	}
                    443:     }
                    444:     if ($convert) {
                    445: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    446: 	    &logthis("Failed to load session, or convert session.");
                    447: 	}
1.374     www       448:     }
1.783     albertel  449: 
1.786     albertel  450:     my %remove;
1.783     albertel  451:     while ( my $envname = each(%env) ) {
1.433     matthew   452:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    453:             if ($time < time-300) {
1.783     albertel  454:                 $remove{$key}++;
1.433     matthew   455:             }
                    456:         }
                    457:     }
1.783     albertel  458: 
1.619     albertel  459:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  460:     $env_loaded=1;
1.783     albertel  461:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   462:         &delenv($expired_key);
1.374     www       463:     }
1.1       albertel  464: }
                    465: 
1.916     albertel  466: # ---------------------------------------------------- Check for valid session 
                    467: sub check_for_valid_session {
                    468:     my ($r) = @_;
                    469:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    470:     my $lonid=$cookies{'lonID'};
                    471:     return undef if (!$lonid);
                    472: 
                    473:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    474:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    475:     return undef if (!-e "$lonidsdir/$handle.id");
                    476: 
1.917     albertel  477:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    478:     return undef if (!$opened);
1.916     albertel  479: 
                    480:     flock($idf,LOCK_SH);
                    481:     my %disk_env;
                    482:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    483: 	    &GDBM_READER(),0640)) {
                    484: 	return undef;	
                    485:     }
                    486: 
                    487:     if (!defined($disk_env{'user.name'})
                    488: 	|| !defined($disk_env{'user.domain'})) {
                    489: 	return undef;
                    490:     }
                    491:     return $handle;
                    492: }
                    493: 
1.830     albertel  494: sub timed_flock {
                    495:     my ($file,$lock_type) = @_;
                    496:     my $failed=0;
                    497:     eval {
                    498: 	local $SIG{__DIE__}='DEFAULT';
                    499: 	local $SIG{ALRM}=sub {
                    500: 	    $failed=1;
                    501: 	    die("failed lock");
                    502: 	};
                    503: 	alarm(13);
                    504: 	flock($file,$lock_type);
                    505: 	alarm(0);
                    506:     };
                    507:     if ($failed) {
                    508: 	return undef;
                    509:     } else {
                    510: 	return 1;
                    511:     }
                    512: }
                    513: 
1.5       www       514: # ---------------------------------------------------------- Append Environment
                    515: 
                    516: sub appenv {
1.949     raeburn   517:     my ($newenv,$roles) = @_;
                    518:     if (ref($newenv) eq 'HASH') {
                    519:         foreach my $key (keys(%{$newenv})) {
                    520:             my $refused = 0;
                    521: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    522:                 $refused = 1;
                    523:                 if (ref($roles) eq 'ARRAY') {
                    524:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    525:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    526:                         $refused = 0;
                    527:                     }
                    528:                 }
                    529:             }
                    530:             if ($refused) {
                    531:                 &logthis("<font color=\"blue\">WARNING: ".
                    532:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    533:                          .'</font>');
                    534: 	        delete($newenv->{$key});
                    535:             } else {
                    536:                 $env{$key}=$newenv->{$key};
                    537:             }
                    538:         }
                    539:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    540:         if ($opened
                    541: 	    && &timed_flock($env_file,LOCK_EX)
                    542: 	    &&
                    543: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    544: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    545: 	    while (my ($key,$value) = each(%{$newenv})) {
                    546: 	        $disk_env{$key} = $value;
                    547: 	    }
                    548: 	    untie(%disk_env);
1.35      www       549:         }
1.191     harris41  550:     }
1.56      www       551:     return 'ok';
                    552: }
                    553: # ----------------------------------------------------- Delete from Environment
                    554: 
                    555: sub delenv {
1.987     raeburn   556:     my ($delthis,$regexp) = @_;
1.56      www       557:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  558:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       559:                 "Attempt to delete from environment ".$delthis);
                    560:         return 'error';
                    561:     }
1.917     albertel  562:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    563:     if ($opened
1.915     albertel  564: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  565: 	&&
                    566: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    567: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  568: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   569: 	    if ($regexp) {
                    570:                 if ($key=~/^$delthis/) {
                    571:                     delete($env{$key});
                    572:                     delete($disk_env{$key});
                    573:                 } 
                    574:             } else {
                    575:                 if ($key=~/^\Q$delthis\E/) {
                    576: 		    delete($env{$key});
                    577: 		    delete($disk_env{$key});
                    578: 	        }
                    579:             }
1.448     albertel  580: 	}
1.783     albertel  581: 	untie(%disk_env);
1.5       www       582:     }
                    583:     return 'ok';
1.369     albertel  584: }
                    585: 
1.790     albertel  586: sub get_env_multiple {
                    587:     my ($name) = @_;
                    588:     my @values;
                    589:     if (defined($env{$name})) {
                    590:         # exists is it an array
                    591:         if (ref($env{$name})) {
                    592:             @values=@{ $env{$name} };
                    593:         } else {
                    594:             $values[0]=$env{$name};
                    595:         }
                    596:     }
                    597:     return(@values);
                    598: }
                    599: 
1.958     www       600: # ------------------------------------------------------------------- Locking
                    601: 
                    602: sub set_lock {
                    603:     my ($text)=@_;
                    604:     $locknum++;
                    605:     my $id=$$.'-'.$locknum;
                    606:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    607:              'session.lock.'.$id => $text});
                    608:     return $id;
                    609: }
                    610: 
                    611: sub get_locks {
                    612:     my $num=0;
                    613:     my %texts=();
                    614:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    615:        if ($lock=~/\w/) {
                    616:           $num++;
                    617:           $texts{$lock}=$env{'session.lock.'.$lock};
                    618:        }
                    619:    }
                    620:    return ($num,%texts);
                    621: }
                    622: 
                    623: sub remove_lock {
                    624:     my ($id)=@_;
                    625:     my $newlocks='';
                    626:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    627:        if (($lock=~/\w/) && ($lock ne $id)) {
                    628:           $newlocks.=','.$lock;
                    629:        }
                    630:     }
                    631:     &appenv({'session.locks' => $newlocks});
                    632:     &delenv('session.lock.'.$id);
                    633: }
                    634: 
                    635: sub remove_all_locks {
                    636:     my $activelocks=$env{'session.locks'};
                    637:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    638:        if ($lock=~/\w/) {
                    639:           &remove_lock($lock);
                    640:        }
                    641:     }
                    642: }
                    643: 
                    644: 
1.369     albertel  645: # ------------------------------------------ Find out current server userload
                    646: sub userload {
                    647:     my $numusers=0;
                    648:     {
                    649: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    650: 	my $filename;
                    651: 	my $curtime=time;
                    652: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  653: 	    next if ($filename eq '.' || $filename eq '..');
                    654: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  655: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  656: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  657: 	}
                    658: 	closedir(LONIDS);
                    659:     }
                    660:     my $userloadpercent=0;
                    661:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    662:     if ($maxuserload) {
1.371     albertel  663: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  664:     }
1.372     albertel  665:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  666:     return $userloadpercent;
1.283     www       667: }
                    668: 
                    669: # ------------------------------------------ Fight off request when overloaded
                    670: 
                    671: sub overloaderror {
                    672:     my ($r,$checkserver)=@_;
                    673:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    674:     my $loadavg;
                    675:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  676:        open(my $loadfile,'/proc/loadavg');
1.283     www       677:        $loadavg=<$loadfile>;
                    678:        $loadavg =~ s/\s.*//g;
1.285     matthew   679:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  680:        close($loadfile);
1.283     www       681:     } else {
                    682:        $loadavg=&reply('load',$checkserver);
                    683:     }
1.285     matthew   684:     my $overload=$loadavg-100;
1.283     www       685:     if ($overload>0) {
1.285     matthew   686: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       687:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       688:         return 413;
1.283     www       689:     }    
                    690:     return '';
1.5       www       691: }
1.1       albertel  692: 
                    693: # ------------------------------ Find server with least workload from spare.tab
1.11      www       694: 
1.1       albertel  695: sub spareserver {
1.670     albertel  696:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  697:     my $spare_server;
1.370     albertel  698:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  699:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    700:                                                      :  $userloadpercent;
                    701:     
                    702:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    703: 	($spare_server, $lowest_load) =
                    704: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    705:     }
                    706: 
                    707:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    708: 
                    709:     if (!$found_server) {
                    710: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    711: 	    ($spare_server, $lowest_load) =
                    712: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    713: 	}
                    714:     }
                    715: 
                    716:     if (!$want_server_name) {
1.968     raeburn   717:         my $protocol = 'http';
                    718:         if ($protocol{$spare_server} eq 'https') {
                    719:             $protocol = $protocol{$spare_server};
                    720:         }
1.1001    raeburn   721:         if (defined($spare_server)) {
                    722:             my $hostname = &hostname($spare_server);
                    723:             if (defined($hostname)) {  
                    724: 	        $spare_server = $protocol.'://'.$hostname;
                    725:             }
                    726:         }
1.784     albertel  727:     }
                    728:     return $spare_server;
                    729: }
                    730: 
                    731: sub compare_server_load {
                    732:     my ($try_server, $spare_server, $lowest_load) = @_;
                    733: 
                    734:     my $loadans     = &reply('load',    $try_server);
                    735:     my $userloadans = &reply('userload',$try_server);
                    736: 
                    737:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    738: 	next; #didn't get a number from the server
                    739:     }
                    740: 
                    741:     my $load;
                    742:     if ($loadans =~ /\d/) {
                    743: 	if ($userloadans =~ /\d/) {
                    744: 	    #both are numbers, pick the bigger one
                    745: 	    $load = ($loadans > $userloadans) ? $loadans 
                    746: 		                              : $userloadans;
1.411     albertel  747: 	} else {
1.784     albertel  748: 	    $load = $loadans;
1.411     albertel  749: 	}
1.784     albertel  750:     } else {
                    751: 	$load = $userloadans;
                    752:     }
                    753: 
                    754:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    755: 	$spare_server = $try_server;
                    756: 	$lowest_load  = $load;
1.370     albertel  757:     }
1.784     albertel  758:     return ($spare_server,$lowest_load);
1.202     matthew   759: }
1.914     albertel  760: 
                    761: # --------------------------- ask offload servers if user already has a session
                    762: sub find_existing_session {
                    763:     my ($udom,$uname) = @_;
                    764:     foreach my $try_server (@{ $spareid{'primary'} },
                    765: 			    @{ $spareid{'default'} }) {
                    766: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    767:     }
                    768:     return;
                    769: }
                    770: 
                    771: # -------------------------------- ask if server already has a session for user
                    772: sub has_user_session {
                    773:     my ($lonid,$udom,$uname) = @_;
                    774:     my $result = &reply(join(':','userhassession',
                    775: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    776:     return 1 if ($result eq 'ok');
                    777: 
                    778:     return 0;
                    779: }
                    780: 
1.202     matthew   781: # --------------------------------------------- Try to change a user's password
                    782: 
                    783: sub changepass {
1.799     raeburn   784:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   785:     $currentpass = &escape($currentpass);
                    786:     $newpass     = &escape($newpass);
1.799     raeburn   787:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   788: 		       $server);
                    789:     if (! $answer) {
                    790: 	&logthis("No reply on password change request to $server ".
                    791: 		 "by $uname in domain $udom.");
                    792:     } elsif ($answer =~ "^ok") {
                    793:         &logthis("$uname in $udom successfully changed their password ".
                    794: 		 "on $server.");
                    795:     } elsif ($answer =~ "^pwchange_failure") {
                    796: 	&logthis("$uname in $udom was unable to change their password ".
                    797: 		 "on $server.  The action was blocked by either lcpasswd ".
                    798: 		 "or pwchange");
                    799:     } elsif ($answer =~ "^non_authorized") {
                    800:         &logthis("$uname in $udom did not get their password correct when ".
                    801: 		 "attempting to change it on $server.");
                    802:     } elsif ($answer =~ "^auth_mode_error") {
                    803:         &logthis("$uname in $udom attempted to change their password despite ".
                    804: 		 "not being locally or internally authenticated on $server.");
                    805:     } elsif ($answer =~ "^unknown_user") {
                    806:         &logthis("$uname in $udom attempted to change their password ".
                    807: 		 "on $server but were unable to because $server is not ".
                    808: 		 "their home server.");
                    809:     } elsif ($answer =~ "^refused") {
                    810: 	&logthis("$server refused to change $uname in $udom password because ".
                    811: 		 "it was sent an unencrypted request to change the password.");
                    812:     }
                    813:     return $answer;
1.1       albertel  814: }
                    815: 
1.169     harris41  816: # ----------------------- Try to determine user's current authentication scheme
                    817: 
                    818: sub queryauthenticate {
                    819:     my ($uname,$udom)=@_;
1.456     albertel  820:     my $uhome=&homeserver($uname,$udom);
                    821:     if (!$uhome) {
                    822: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    823: 	return 'no_host';
                    824:     }
                    825:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    826:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    827: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  828:     }
1.456     albertel  829:     return $answer;
1.169     harris41  830: }
                    831: 
1.1       albertel  832: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       833: 
1.1       albertel  834: sub authenticate {
1.952     raeburn   835:     my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807     albertel  836:     $upass=&escape($upass);
                    837:     $uname= &LONCAPA::clean_username($uname);
1.836     www       838:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   839:     my $newhome;
1.836     www       840:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    841: # Maybe the machine was offline and only re-appeared again recently?
                    842:         &reconlonc();
                    843: # One more
1.952     raeburn   844: 	$uhome=&homeserver($uname,$udom,1);
                    845:         if (($uhome eq 'no_host') && $checkdefauth) {
                    846:             if (defined(&domain($udom,'primary'))) {
                    847:                 $newhome=&domain($udom,'primary');
                    848:             }
                    849:             if ($newhome ne '') {
                    850:                 $uhome = $newhome;
                    851:             }
                    852:         }
1.836     www       853: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    854: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   855: 	    return 'no_host';
                    856:         }
1.1       albertel  857:     }
1.952     raeburn   858:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471     albertel  859:     if ($answer eq 'authorized') {
1.952     raeburn   860:         if ($newhome) {
                    861:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    862:             return 'no_account_on_host'; 
                    863:         } else {
                    864:             &logthis("User $uname at $udom authorized by $uhome");
                    865:             return $uhome;
                    866:         }
1.471     albertel  867:     }
                    868:     if ($answer eq 'non_authorized') {
                    869: 	&logthis("User $uname at $udom rejected by $uhome");
                    870: 	return 'no_host'; 
1.9       www       871:     }
1.471     albertel  872:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  873:     return 'no_host';
                    874: }
                    875: 
                    876: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       877: 
1.599     albertel  878: my %homecache;
1.1       albertel  879: sub homeserver {
1.230     stredwic  880:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  881:     my $index="$uname:$udom";
1.426     albertel  882: 
1.599     albertel  883:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  884: 
                    885:     my %servers = &get_servers($udom,'library');
                    886:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  887:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  888: 		 exists($badServerCache{$tryserver}));
1.841     albertel  889: 
                    890: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    891: 	if ($answer eq 'found') {
                    892: 	    delete($badServerCache{$tryserver}); 
                    893: 	    return $homecache{$index}=$tryserver;
                    894: 	} elsif ($answer eq 'no_host') {
                    895: 	    $badServerCache{$tryserver}=1;
                    896: 	}
1.1       albertel  897:     }    
                    898:     return 'no_host';
1.70      www       899: }
                    900: 
                    901: # ------------------------------------- Find the usernames behind a list of IDs
                    902: 
                    903: sub idget {
                    904:     my ($udom,@ids)=@_;
                    905:     my %returnhash=();
                    906:     
1.841     albertel  907:     my %servers = &get_servers($udom,'library');
                    908:     foreach my $tryserver (keys(%servers)) {
                    909: 	my $idlist=join('&',@ids);
                    910: 	$idlist=~tr/A-Z/a-z/; 
                    911: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    912: 	my @answer=();
                    913: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    914: 	    @answer=split(/\&/,$reply);
                    915: 	}                    ;
                    916: 	my $i;
                    917: 	for ($i=0;$i<=$#ids;$i++) {
                    918: 	    if ($answer[$i]) {
                    919: 		$returnhash{$ids[$i]}=$answer[$i];
                    920: 	    } 
                    921: 	}
                    922:     } 
1.70      www       923:     return %returnhash;
                    924: }
                    925: 
                    926: # ------------------------------------- Find the IDs behind a list of usernames
                    927: 
                    928: sub idrget {
                    929:     my ($udom,@unames)=@_;
                    930:     my %returnhash=();
1.800     albertel  931:     foreach my $uname (@unames) {
                    932:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  933:     }
1.70      www       934:     return %returnhash;
                    935: }
                    936: 
                    937: # ------------------------------- Store away a list of names and associated IDs
                    938: 
                    939: sub idput {
                    940:     my ($udom,%ids)=@_;
                    941:     my %servers=();
1.800     albertel  942:     foreach my $uname (keys(%ids)) {
                    943: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    944:         my $uhom=&homeserver($uname,$udom);
1.70      www       945:         if ($uhom ne 'no_host') {
1.800     albertel  946:             my $id=&escape($ids{$uname});
1.70      www       947:             $id=~tr/A-Z/a-z/;
1.800     albertel  948:             my $esc_unam=&escape($uname);
1.70      www       949: 	    if ($servers{$uhom}) {
1.800     albertel  950: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       951:             } else {
1.800     albertel  952:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       953:             }
                    954:         }
1.191     harris41  955:     }
1.800     albertel  956:     foreach my $server (keys(%servers)) {
                    957:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  958:     }
1.344     www       959: }
                    960: 
1.806     raeburn   961: # ------------------------------------------- get items from domain db files   
                    962: 
                    963: sub get_dom {
1.860     raeburn   964:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   965:     my $items='';
                    966:     foreach my $item (@$storearr) {
                    967:         $items.=&escape($item).'&';
                    968:     }
                    969:     $items=~s/\&$//;
1.860     raeburn   970:     if (!$udom) {
                    971:         $udom=$env{'user.domain'};
                    972:         if (defined(&domain($udom,'primary'))) {
                    973:             $uhome=&domain($udom,'primary');
                    974:         } else {
1.874     albertel  975:             undef($uhome);
1.860     raeburn   976:         }
                    977:     } else {
                    978:         if (!$uhome) {
                    979:             if (defined(&domain($udom,'primary'))) {
                    980:                 $uhome=&domain($udom,'primary');
                    981:             }
                    982:         }
                    983:     }
                    984:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   985:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn   986:         my %returnhash;
1.875     albertel  987:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn   988:             return %returnhash;
                    989:         }
1.806     raeburn   990:         my @pairs=split(/\&/,$rep);
                    991:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    992:             return @pairs;
                    993:         }
                    994:         my $i=0;
                    995:         foreach my $item (@$storearr) {
                    996:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    997:             $i++;
                    998:         }
                    999:         return %returnhash;
                   1000:     } else {
1.880     banghart 1001:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1002:     }
                   1003: }
                   1004: 
                   1005: # -------------------------------------------- put items in domain db files 
                   1006: 
                   1007: sub put_dom {
1.860     raeburn  1008:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1009:     if (!$udom) {
                   1010:         $udom=$env{'user.domain'};
                   1011:         if (defined(&domain($udom,'primary'))) {
                   1012:             $uhome=&domain($udom,'primary');
                   1013:         } else {
1.874     albertel 1014:             undef($uhome);
1.860     raeburn  1015:         }
                   1016:     } else {
                   1017:         if (!$uhome) {
                   1018:             if (defined(&domain($udom,'primary'))) {
                   1019:                 $uhome=&domain($udom,'primary');
                   1020:             }
                   1021:         }
                   1022:     } 
                   1023:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1024:         my $items='';
                   1025:         foreach my $item (keys(%$storehash)) {
                   1026:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1027:         }
                   1028:         $items=~s/\&$//;
                   1029:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1030:     } else {
1.860     raeburn  1031:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1032:     }
                   1033: }
                   1034: 
1.837     raeburn  1035: sub retrieve_inst_usertypes {
                   1036:     my ($udom) = @_;
                   1037:     my (%returnhash,@order);
1.989     raeburn  1038:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1039:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1040:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1041:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1042:         @order = @{$domdefs{'inststatusorder'}};
                   1043:     } else {
                   1044:         if (defined(&domain($udom,'primary'))) {
                   1045:             my $uhome=&domain($udom,'primary');
                   1046:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1047:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1048:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1049:                 return (\%returnhash,\@order);
                   1050:             }
                   1051:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1052:             my @pairs=split(/\&/,$hashitems);
                   1053:             foreach my $item (@pairs) {
                   1054:                 my ($key,$value)=split(/=/,$item,2);
                   1055:                 $key = &unescape($key);
                   1056:                 next if ($key =~ /^error: 2 /);
                   1057:                 $returnhash{$key}=&thaw_unescape($value);
                   1058:             }
                   1059:             my @esc_order = split(/\&/,$orderitems);
                   1060:             foreach my $item (@esc_order) {
                   1061:                 push(@order,&unescape($item));
                   1062:             }
                   1063:         } else {
                   1064:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1065:         }
                   1066:     }
                   1067:     return (\%returnhash,\@order);
                   1068: }
                   1069: 
1.868     raeburn  1070: sub is_domainimage {
                   1071:     my ($url) = @_;
                   1072:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1073:         if (&domain($1) ne '') {
                   1074:             return '1';
                   1075:         }
                   1076:     }
                   1077:     return;
                   1078: }
                   1079: 
1.899     raeburn  1080: sub inst_directory_query {
                   1081:     my ($srch) = @_;
                   1082:     my $udom = $srch->{'srchdomain'};
                   1083:     my %results;
                   1084:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1085:     my $outcome;
1.899     raeburn  1086:     if ($homeserver ne '') {
1.904     albertel 1087: 	my $queryid=&reply("querysend:instdirsearch:".
                   1088: 			   &escape($srch->{'srchby'}).':'.
                   1089: 			   &escape($srch->{'srchterm'}).':'.
                   1090: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1091: 	my $host=&hostname($homeserver);
                   1092: 	if ($queryid !~/^\Q$host\E\_/) {
                   1093: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1094: 	    return;
                   1095: 	}
                   1096: 	my $response = &get_query_reply($queryid);
                   1097: 	my $maxtries = 5;
                   1098: 	my $tries = 1;
                   1099: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1100: 	    $response = &get_query_reply($queryid);
                   1101: 	    $tries ++;
                   1102: 	}
                   1103: 
                   1104:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1105:             if ($response eq 'unavailable') {
                   1106:                 $outcome = $response;
                   1107:             } else {
                   1108:                 $outcome = 'ok';
                   1109:                 my @matches = split(/\n/,$response);
                   1110:                 foreach my $match (@matches) {
                   1111:                     my ($key,$value) = split(/=/,$match);
                   1112:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1113:                 }
1.899     raeburn  1114:             }
                   1115:         }
                   1116:     }
1.909     raeburn  1117:     return ($outcome,%results);
1.899     raeburn  1118: }
                   1119: 
                   1120: sub usersearch {
                   1121:     my ($srch) = @_;
                   1122:     my $dom = $srch->{'srchdomain'};
                   1123:     my %results;
                   1124:     my %libserv = &all_library();
                   1125:     my $query = 'usersearch';
                   1126:     foreach my $tryserver (keys(%libserv)) {
                   1127:         if (&host_domain($tryserver) eq $dom) {
                   1128:             my $host=&hostname($tryserver);
                   1129:             my $queryid=
1.911     raeburn  1130:                 &reply("querysend:".&escape($query).':'.
                   1131:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1132:                        &escape($srch->{'srchtype'}).':'.
                   1133:                        &escape($srch->{'srchterm'}),$tryserver);
                   1134:             if ($queryid !~/^\Q$host\E\_/) {
                   1135:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1136:                 next;
1.899     raeburn  1137:             }
                   1138:             my $reply = &get_query_reply($queryid);
                   1139:             my $maxtries = 1;
                   1140:             my $tries = 1;
                   1141:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1142:                 $reply = &get_query_reply($queryid);
                   1143:                 $tries ++;
                   1144:             }
                   1145:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1146:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1147:             } else {
1.911     raeburn  1148:                 my @matches;
                   1149:                 if ($reply =~ /\n/) {
                   1150:                     @matches = split(/\n/,$reply);
                   1151:                 } else {
                   1152:                     @matches = split(/\&/,$reply);
                   1153:                 }
1.899     raeburn  1154:                 foreach my $match (@matches) {
                   1155:                     my ($uname,$udom,%userhash);
1.911     raeburn  1156:                     foreach my $entry (split(/:/,$match)) {
                   1157:                         my ($key,$value) =
                   1158:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1159:                         $userhash{$key} = $value;
                   1160:                         if ($key eq 'username') {
                   1161:                             $uname = $value;
                   1162:                         } elsif ($key eq 'domain') {
                   1163:                             $udom = $value;
1.911     raeburn  1164:                         }
1.899     raeburn  1165:                     }
                   1166:                     $results{$uname.':'.$udom} = \%userhash;
                   1167:                 }
                   1168:             }
                   1169:         }
                   1170:     }
                   1171:     return %results;
                   1172: }
                   1173: 
1.912     raeburn  1174: sub get_instuser {
                   1175:     my ($udom,$uname,$id) = @_;
                   1176:     my $homeserver = &domain($udom,'primary');
                   1177:     my ($outcome,%results);
                   1178:     if ($homeserver ne '') {
                   1179:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1180:                            &escape($id).':'.&escape($udom),$homeserver);
                   1181:         my $host=&hostname($homeserver);
                   1182:         if ($queryid !~/^\Q$host\E\_/) {
                   1183:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1184:             return;
                   1185:         }
                   1186:         my $response = &get_query_reply($queryid);
                   1187:         my $maxtries = 5;
                   1188:         my $tries = 1;
                   1189:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1190:             $response = &get_query_reply($queryid);
                   1191:             $tries ++;
                   1192:         }
                   1193:         if (!&error($response) && $response ne 'refused') {
                   1194:             if ($response eq 'unavailable') {
                   1195:                 $outcome = $response;
                   1196:             } else {
                   1197:                 $outcome = 'ok';
                   1198:                 my @matches = split(/\n/,$response);
                   1199:                 foreach my $match (@matches) {
                   1200:                     my ($key,$value) = split(/=/,$match);
                   1201:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1202:                 }
                   1203:             }
                   1204:         }
                   1205:     }
                   1206:     my %userinfo;
                   1207:     if (ref($results{$uname}) eq 'HASH') {
                   1208:         %userinfo = %{$results{$uname}};
                   1209:     } 
                   1210:     return ($outcome,%userinfo);
                   1211: }
                   1212: 
                   1213: sub inst_rulecheck {
1.923     raeburn  1214:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1215:     my %returnhash;
                   1216:     if ($udom ne '') {
                   1217:         if (ref($rules) eq 'ARRAY') {
                   1218:             @{$rules} = map {&escape($_);} (@{$rules});
                   1219:             my $rulestr = join(':',@{$rules});
                   1220:             my $homeserver=&domain($udom,'primary');
                   1221:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1222:                 my $response;
                   1223:                 if ($item eq 'username') {                
                   1224:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1225:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1226:                                               $homeserver));
1.923     raeburn  1227:                 } elsif ($item eq 'id') {
                   1228:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1229:                                               ':'.&escape($id).':'.$rulestr,
                   1230:                                               $homeserver));
1.945     raeburn  1231:                 } elsif ($item eq 'selfcreate') {
                   1232:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1233:                                                &escape($udom).':'.&escape($uname).
                   1234:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1235:                 }
1.912     raeburn  1236:                 if ($response ne 'refused') {
                   1237:                     my @pairs=split(/\&/,$response);
                   1238:                     foreach my $item (@pairs) {
                   1239:                         my ($key,$value)=split(/=/,$item,2);
                   1240:                         $key = &unescape($key);
                   1241:                         next if ($key =~ /^error: 2 /);
                   1242:                         $returnhash{$key}=&thaw_unescape($value);
                   1243:                     }
                   1244:                 }
                   1245:             }
                   1246:         }
                   1247:     }
                   1248:     return %returnhash;
                   1249: }
                   1250: 
                   1251: sub inst_userrules {
1.923     raeburn  1252:     my ($udom,$check) = @_;
1.912     raeburn  1253:     my (%ruleshash,@ruleorder);
                   1254:     if ($udom ne '') {
                   1255:         my $homeserver=&domain($udom,'primary');
                   1256:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1257:             my $response;
                   1258:             if ($check eq 'id') {
                   1259:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1260:                                  $homeserver);
1.943     raeburn  1261:             } elsif ($check eq 'email') {
                   1262:                 $response=&reply('instemailrules:'.&escape($udom),
                   1263:                                  $homeserver);
1.923     raeburn  1264:             } else {
                   1265:                 $response=&reply('instuserrules:'.&escape($udom),
                   1266:                                  $homeserver);
                   1267:             }
1.912     raeburn  1268:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1269:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1270:                 ($response ne 'no_such_host')) {
                   1271:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1272:                 my @pairs=split(/\&/,$hashitems);
                   1273:                 foreach my $item (@pairs) {
                   1274:                     my ($key,$value)=split(/=/,$item,2);
                   1275:                     $key = &unescape($key);
                   1276:                     next if ($key =~ /^error: 2 /);
                   1277:                     $ruleshash{$key}=&thaw_unescape($value);
                   1278:                 }
                   1279:                 my @esc_order = split(/\&/,$orderitems);
                   1280:                 foreach my $item (@esc_order) {
                   1281:                     push(@ruleorder,&unescape($item));
                   1282:                 }
                   1283:             }
                   1284:         }
                   1285:     }
                   1286:     return (\%ruleshash,\@ruleorder);
                   1287: }
                   1288: 
1.976     raeburn  1289: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1290: 
                   1291: sub get_domain_defaults {
                   1292:     my ($domain) = @_;
                   1293:     my $cachetime = 60*60*24;
                   1294:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1295:     if (defined($cached)) {
                   1296:         if (ref($result) eq 'HASH') {
                   1297:             return %{$result};
                   1298:         }
                   1299:     }
                   1300:     my %domdefaults;
                   1301:     my %domconfig =
1.989     raeburn  1302:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
                   1303:                                   'requestcourses','inststatus'],$domain);
1.943     raeburn  1304:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1305:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1306:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1307:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1308:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1309:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1310:     } else {
                   1311:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1312:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1313:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1314:     }
1.976     raeburn  1315:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1316:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1317:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1318:         } else {
                   1319:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1320:         } 
                   1321:         my @usertools = ('aboutme','blog','portfolio');
                   1322:         foreach my $item (@usertools) {
                   1323:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1324:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1325:             }
                   1326:         }
                   1327:     }
1.985     raeburn  1328:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1329:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1330:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1331:         }
                   1332:     }
1.989     raeburn  1333:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1334:         foreach my $item ('inststatustypes','inststatusorder') {
                   1335:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1336:         }
                   1337:     }
1.943     raeburn  1338:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1339:                                   $cachetime);
                   1340:     return %domdefaults;
                   1341: }
                   1342: 
1.344     www      1343: # --------------------------------------------------- Assign a key to a student
                   1344: 
                   1345: sub assign_access_key {
1.364     www      1346: #
                   1347: # a valid key looks like uname:udom#comments
                   1348: # comments are being appended
                   1349: #
1.498     www      1350:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1351:     $kdom=
1.620     albertel 1352:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1353:     $knum=
1.620     albertel 1354:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1355:     $cdom=
1.620     albertel 1356:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1357:     $cnum=
1.620     albertel 1358:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1359:     $udom=$env{'user.name'} unless (defined($udom));
                   1360:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1361:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1362:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1363:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1364:                                                   # assigned to this person
                   1365:                                                   # - this should not happen,
1.345     www      1366:                                                   # unless something went wrong
                   1367:                                                   # the first time around
                   1368: # ready to assign
1.364     www      1369:         $logentry=$1.'; '.$logentry;
1.496     www      1370:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1371:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1372: # key now belongs to user
1.346     www      1373: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1374:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1375:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1376:                 return 'ok';
                   1377:             } else {
                   1378:                 return 
                   1379:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1380: 	    }
                   1381:         } else {
                   1382:             return 'error: Could not assign key, try again later.';
                   1383:         }
1.364     www      1384:     } elsif (!$existing{$ckey}) {
1.345     www      1385: # the key does not exist
                   1386: 	return 'error: The key does not exist';
                   1387:     } else {
                   1388: # the key is somebody else's
                   1389: 	return 'error: The key is already in use';
                   1390:     }
1.344     www      1391: }
                   1392: 
1.364     www      1393: # ------------------------------------------ put an additional comment on a key
                   1394: 
                   1395: sub comment_access_key {
                   1396: #
                   1397: # a valid key looks like uname:udom#comments
                   1398: # comments are being appended
                   1399: #
                   1400:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1401:     $cdom=
1.620     albertel 1402:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1403:     $cnum=
1.620     albertel 1404:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1405:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1406:     if ($existing{$ckey}) {
                   1407:         $existing{$ckey}.='; '.$logentry;
                   1408: # ready to assign
1.367     www      1409:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1410:                                                  $cdom,$cnum) eq 'ok') {
                   1411: 	    return 'ok';
                   1412:         } else {
                   1413: 	    return 'error: Count not store comment.';
                   1414:         }
                   1415:     } else {
                   1416: # the key does not exist
                   1417: 	return 'error: The key does not exist';
                   1418:     }
                   1419: }
                   1420: 
1.344     www      1421: # ------------------------------------------------------ Generate a set of keys
                   1422: 
                   1423: sub generate_access_keys {
1.364     www      1424:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1425:     $cdom=
1.620     albertel 1426:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1427:     $cnum=
1.620     albertel 1428:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1429:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1430:     unless (($cdom) && ($cnum)) { return 0; }
                   1431:     if ($number>10000) { return 0; }
                   1432:     sleep(2); # make sure don't get same seed twice
                   1433:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1434:     my $total=0;
                   1435:     for (my $i=1;$i<=$number;$i++) {
                   1436:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1437:                   sprintf("%lx",int(100000*rand)).'-'.
                   1438:                   sprintf("%lx",int(100000*rand));
                   1439:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1440:        $newkey=~s/0/h/g; # and also 0 and O
                   1441:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1442:        if ($existing{$newkey}) {
                   1443:            $i--;
                   1444:        } else {
1.364     www      1445: 	  if (&put('accesskeys',
                   1446:               { $newkey => '# generated '.localtime().
1.620     albertel 1447:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1448:                            '; '.$logentry },
                   1449: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1450:               $total++;
                   1451: 	  }
                   1452:        }
                   1453:     }
1.620     albertel 1454:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1455:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1456:     return $total;
                   1457: }
                   1458: 
                   1459: # ------------------------------------------------------- Validate an accesskey
                   1460: 
                   1461: sub validate_access_key {
                   1462:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1463:     $cdom=
1.620     albertel 1464:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1465:     $cnum=
1.620     albertel 1466:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1467:     $udom=$env{'user.domain'} unless (defined($udom));
                   1468:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1469:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1470:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1471: }
                   1472: 
                   1473: # ------------------------------------- Find the section of student in a course
1.652     albertel 1474: sub devalidate_getsection_cache {
                   1475:     my ($udom,$unam,$courseid)=@_;
                   1476:     my $hashid="$udom:$unam:$courseid";
                   1477:     &devalidate_cache_new('getsection',$hashid);
                   1478: }
1.298     matthew  1479: 
1.815     albertel 1480: sub courseid_to_courseurl {
                   1481:     my ($courseid) = @_;
                   1482:     #already url style courseid
                   1483:     return $courseid if ($courseid =~ m{^/});
                   1484: 
                   1485:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1486: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1487: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1488: 	return "/$cdom/$cnum";
                   1489:     }
                   1490: 
                   1491:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1492:     if (exists($courseinfo{'num'})) {
                   1493: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1494:     }
                   1495: 
                   1496:     return undef;
                   1497: }
                   1498: 
1.298     matthew  1499: sub getsection {
                   1500:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1501:     my $cachetime=1800;
1.551     albertel 1502: 
                   1503:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1504:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1505:     if (defined($cached)) { return $result; }
                   1506: 
1.298     matthew  1507:     my %Pending; 
                   1508:     my %Expired;
                   1509:     #
                   1510:     # Each role can either have not started yet (pending), be active, 
                   1511:     #    or have expired.
                   1512:     #
                   1513:     # If there is an active role, we are done.
                   1514:     #
                   1515:     # If there is more than one role which has not started yet, 
                   1516:     #     choose the one which will start sooner
                   1517:     # If there is one role which has not started yet, return it.
                   1518:     #
                   1519:     # If there is more than one expired role, choose the one which ended last.
                   1520:     # If there is a role which has expired, return it.
                   1521:     #
1.815     albertel 1522:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1523:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1524:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1525:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1526:         my $section=$1;
                   1527:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1528:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1529:         my $now=time;
1.548     albertel 1530:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1531:             $Expired{$end}=$section;
                   1532:             next;
                   1533:         }
1.548     albertel 1534:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1535:             $Pending{$start}=$section;
                   1536:             next;
                   1537:         }
1.599     albertel 1538:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1539:     }
                   1540:     #
                   1541:     # Presumedly there will be few matching roles from the above
                   1542:     # loop and the sorting time will be negligible.
                   1543:     if (scalar(keys(%Pending))) {
                   1544:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1545:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1546:     } 
                   1547:     if (scalar(keys(%Expired))) {
                   1548:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1549:         my $time = pop(@sorted);
1.599     albertel 1550:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1551:     }
1.599     albertel 1552:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1553: }
1.70      www      1554: 
1.599     albertel 1555: sub save_cache {
                   1556:     &purge_remembered();
1.722     albertel 1557:     #&Apache::loncommon::validate_page();
1.620     albertel 1558:     undef(%env);
1.780     albertel 1559:     undef($env_loaded);
1.599     albertel 1560: }
1.452     albertel 1561: 
1.599     albertel 1562: my $to_remember=-1;
                   1563: my %remembered;
                   1564: my %accessed;
                   1565: my $kicks=0;
                   1566: my $hits=0;
1.849     albertel 1567: sub make_key {
                   1568:     my ($name,$id) = @_;
1.872     albertel 1569:     if (length($id) > 65 
                   1570: 	&& length(&escape($id)) > 200) {
                   1571: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1572:     }
1.849     albertel 1573:     return &escape($name.':'.$id);
                   1574: }
                   1575: 
1.599     albertel 1576: sub devalidate_cache_new {
                   1577:     my ($name,$id,$debug) = @_;
                   1578:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1579:     $id=&make_key($name,$id);
1.599     albertel 1580:     $memcache->delete($id);
                   1581:     delete($remembered{$id});
                   1582:     delete($accessed{$id});
                   1583: }
                   1584: 
                   1585: sub is_cached_new {
                   1586:     my ($name,$id,$debug) = @_;
1.849     albertel 1587:     $id=&make_key($name,$id);
1.599     albertel 1588:     if (exists($remembered{$id})) {
                   1589: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1590: 	$accessed{$id}=[&gettimeofday()];
                   1591: 	$hits++;
                   1592: 	return ($remembered{$id},1);
                   1593:     }
                   1594:     my $value = $memcache->get($id);
                   1595:     if (!(defined($value))) {
                   1596: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1597: 	return (undef,undef);
1.416     albertel 1598:     }
1.599     albertel 1599:     if ($value eq '__undef__') {
                   1600: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1601: 	$value=undef;
                   1602:     }
                   1603:     &make_room($id,$value,$debug);
                   1604:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1605:     return ($value,1);
                   1606: }
                   1607: 
                   1608: sub do_cache_new {
                   1609:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1610:     $id=&make_key($name,$id);
1.599     albertel 1611:     my $setvalue=$value;
                   1612:     if (!defined($setvalue)) {
                   1613: 	$setvalue='__undef__';
                   1614:     }
1.623     albertel 1615:     if (!defined($time) ) {
                   1616: 	$time=600;
                   1617:     }
1.599     albertel 1618:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1619:     my $result = $memcache->set($id,$setvalue,$time);
                   1620:     if (! $result) {
1.872     albertel 1621: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1622: 	$memcache->disconnect_all();
1.872     albertel 1623:     }
1.600     albertel 1624:     # need to make a copy of $value
1.919     albertel 1625:     &make_room($id,$value,$debug);
1.599     albertel 1626:     return $value;
                   1627: }
                   1628: 
                   1629: sub make_room {
                   1630:     my ($id,$value,$debug)=@_;
1.919     albertel 1631: 
                   1632:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1633:                                     : $value;
1.599     albertel 1634:     if ($to_remember<0) { return; }
                   1635:     $accessed{$id}=[&gettimeofday()];
                   1636:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1637:     my $to_kick;
                   1638:     my $max_time=0;
                   1639:     foreach my $other (keys(%accessed)) {
                   1640: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1641: 	    $to_kick=$other;
                   1642: 	    $max_time=&tv_interval($accessed{$other});
                   1643: 	}
                   1644:     }
                   1645:     delete($remembered{$to_kick});
                   1646:     delete($accessed{$to_kick});
                   1647:     $kicks++;
                   1648:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1649:     return;
                   1650: }
                   1651: 
1.599     albertel 1652: sub purge_remembered {
1.604     albertel 1653:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1654:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1655:     undef(%remembered);
                   1656:     undef(%accessed);
1.428     albertel 1657: }
1.70      www      1658: # ------------------------------------- Read an entry from a user's environment
                   1659: 
                   1660: sub userenvironment {
                   1661:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1662:     my $items;
                   1663:     foreach my $item (@what) {
                   1664:         $items.=&escape($item).'&';
                   1665:     }
                   1666:     $items=~s/\&$//;
1.70      www      1667:     my %returnhash=();
1.1009    raeburn  1668:     my $uhome = &homeserver($unam,$udom);
                   1669:     unless ($uhome eq 'no_host') {
                   1670:         my @answer=split(/\&/, 
                   1671:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
                   1672:         my $i;
                   1673:         for ($i=0;$i<=$#what;$i++) {
                   1674: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   1675:         }
1.70      www      1676:     }
                   1677:     return %returnhash;
1.1       albertel 1678: }
                   1679: 
1.617     albertel 1680: # ---------------------------------------------------------- Get a studentphoto
                   1681: sub studentphoto {
                   1682:     my ($udom,$unam,$ext) = @_;
                   1683:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1684:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1685:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1686:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1687:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1688:             } else {
                   1689:                 my ($result,$perm_reqd)=
1.707     albertel 1690: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1691:                 if ($result eq 'ok') {
                   1692:                     if (!($perm_reqd eq 'yes')) {
                   1693:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1694:                     }
                   1695:                 }
                   1696:             }
                   1697:         }
                   1698:     } else {
                   1699:         my ($result,$perm_reqd) = 
1.707     albertel 1700: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1701:         if ($result eq 'ok') {
                   1702:             if (!($perm_reqd eq 'yes')) {
                   1703:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1704:             }
                   1705:         }
                   1706:     }
                   1707:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1708: }
                   1709: 
                   1710: sub retrievestudentphoto {
                   1711:     my ($udom,$unam,$ext,$type) = @_;
                   1712:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1713:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1714:     if ($ret eq 'ok') {
                   1715:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1716:         if ($type eq 'thumbnail') {
                   1717:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1718:         }
                   1719:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1720:         return $tokenurl;
                   1721:     } else {
                   1722:         if ($type eq 'thumbnail') {
                   1723:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1724:         } else { 
                   1725:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1726:         }
1.617     albertel 1727:     }
                   1728: }
                   1729: 
1.263     www      1730: # -------------------------------------------------------------------- New chat
                   1731: 
                   1732: sub chatsend {
1.724     raeburn  1733:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1734:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1735:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1736:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1737:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1738: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1739: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1740: }
                   1741: 
                   1742: # ------------------------------------------ Find current version of a resource
                   1743: 
                   1744: sub getversion {
                   1745:     my $fname=&clutter(shift);
                   1746:     unless ($fname=~/^\/res\//) { return -1; }
                   1747:     return &currentversion(&filelocation('',$fname));
                   1748: }
                   1749: 
                   1750: sub currentversion {
                   1751:     my $fname=shift;
1.599     albertel 1752:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1753:     if (defined($cached)) { return $result; }
1.292     www      1754:     my $author=$fname;
                   1755:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1756:     my ($udom,$uname)=split(/\//,$author);
                   1757:     my $home=homeserver($uname,$udom);
                   1758:     if ($home eq 'no_host') { 
                   1759:         return -1; 
                   1760:     }
                   1761:     my $answer=reply("currentversion:$fname",$home);
                   1762:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1763: 	return -1;
                   1764:     }
1.599     albertel 1765:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1766: }
                   1767: 
1.1       albertel 1768: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1769: 
1.1       albertel 1770: sub subscribe {
                   1771:     my $fname=shift;
1.761     raeburn  1772:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1773:     $fname=~s/[\n\r]//g;
1.1       albertel 1774:     my $author=$fname;
                   1775:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1776:     my ($udom,$uname)=split(/\//,$author);
                   1777:     my $home=homeserver($uname,$udom);
1.335     albertel 1778:     if ($home eq 'no_host') {
                   1779:         return 'not_found';
1.1       albertel 1780:     }
                   1781:     my $answer=reply("sub:$fname",$home);
1.64      www      1782:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1783: 	$answer.=' by '.$home;
                   1784:     }
1.1       albertel 1785:     return $answer;
                   1786: }
                   1787:     
1.8       www      1788: # -------------------------------------------------------------- Replicate file
                   1789: 
                   1790: sub repcopy {
                   1791:     my $filename=shift;
1.23      www      1792:     $filename=~s/\/+/\//g;
1.607     raeburn  1793:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1794:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1795:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1796: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1797: 	return &repcopy_userfile($filename);
                   1798:     }
1.532     albertel 1799:     $filename=~s/[\n\r]//g;
1.8       www      1800:     my $transname="$filename.in.transfer";
1.828     www      1801: # FIXME: this should flock
1.607     raeburn  1802:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1803:     my $remoteurl=subscribe($filename);
1.64      www      1804:     if ($remoteurl =~ /^con_lost by/) {
                   1805: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1806:            return 'unavailable';
1.8       www      1807:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1808: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1809: 	   return 'not_found';
1.64      www      1810:     } elsif ($remoteurl =~ /^rejected by/) {
                   1811: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1812:            return 'forbidden';
1.20      www      1813:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1814:            return 'ok';
1.8       www      1815:     } else {
1.290     www      1816:         my $author=$filename;
                   1817:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1818:         my ($udom,$uname)=split(/\//,$author);
                   1819:         my $home=homeserver($uname,$udom);
                   1820:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1821:            my @parts=split(/\//,$filename);
                   1822:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1823:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1824:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1825: 	       return 'bad_request';
1.8       www      1826:            }
                   1827:            my $count;
                   1828:            for ($count=5;$count<$#parts;$count++) {
                   1829:                $path.="/$parts[$count]";
                   1830:                if ((-e $path)!=1) {
                   1831: 		   mkdir($path,0777);
                   1832:                }
                   1833:            }
                   1834:            my $ua=new LWP::UserAgent;
                   1835:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1836:            my $response=$ua->request($request,$transname);
                   1837:            if ($response->is_error()) {
                   1838: 	       unlink($transname);
                   1839:                my $message=$response->status_line;
1.672     albertel 1840:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1841:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1842:                return 'unavailable';
1.8       www      1843:            } else {
1.16      www      1844: 	       if ($remoteurl!~/\.meta$/) {
                   1845:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1846:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1847:                   if ($mresponse->is_error()) {
                   1848: 		      unlink($filename.'.meta');
                   1849:                       &logthis(
1.672     albertel 1850:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1851:                   }
                   1852: 	       }
1.8       www      1853:                rename($transname,$filename);
1.607     raeburn  1854:                return 'ok';
1.8       www      1855:            }
1.290     www      1856:        }
1.8       www      1857:     }
1.330     www      1858: }
                   1859: 
                   1860: # ------------------------------------------------ Get server side include body
                   1861: sub ssi_body {
1.381     albertel 1862:     my ($filelink,%form)=@_;
1.606     matthew  1863:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1864:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1865:     }
1.953     www      1866:     my $output='';
                   1867:     my $response;
1.980     raeburn  1868:     if ($filelink=~/^https?\:/) {
1.954     raeburn  1869:        ($output,$response)=&externalssi($filelink);
1.953     www      1870:     } else {
1.1004    droeschl 1871:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   1872:        $filelink .= 'inhibitmenu=yes';
1.953     www      1873:        ($output,$response)=&ssi($filelink,%form);
                   1874:     }
1.778     albertel 1875:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1876:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 1877:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      1878:     if (wantarray) {
                   1879:         return ($output, $response);
                   1880:     } else {
                   1881:         return $output;
                   1882:     }
1.8       www      1883: }
                   1884: 
1.15      www      1885: # --------------------------------------------------------- Server Side Include
                   1886: 
1.782     albertel 1887: sub absolute_url {
                   1888:     my ($host_name) = @_;
                   1889:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1890:     if ($host_name eq '') {
                   1891: 	$host_name = $ENV{'SERVER_NAME'};
                   1892:     }
                   1893:     return $protocol.$host_name;
                   1894: }
                   1895: 
1.942     foxr     1896: #
                   1897: #   Server side include.
                   1898: # Parameters:
                   1899: #  fn     Possibly encrypted resource name/id.
                   1900: #  form   Hash that describes how the rendering should be done
                   1901: #         and other things.
1.944     foxr     1902: # Returns:
1.950     raeburn  1903: #   Scalar context: The content of the response.
                   1904: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     1905: #     
1.15      www      1906: sub ssi {
                   1907: 
1.944     foxr     1908:     my ($fn,%form)=@_;
1.15      www      1909:     my $ua=new LWP::UserAgent;
1.23      www      1910:     my $request;
1.711     albertel 1911: 
                   1912:     $form{'no_update_last_known'}=1;
1.895     albertel 1913:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1914:     if (%form) {
1.782     albertel 1915:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  1916:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      1917:     } else {
1.782     albertel 1918:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1919:     }
                   1920: 
1.15      www      1921:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1922:     my $response=$ua->request($request);
                   1923: 
1.944     foxr     1924:     if (wantarray) {
                   1925: 	return ($response->content, $response);
                   1926:     } else {
                   1927: 	return $response->content;
1.942     foxr     1928:     }
1.324     www      1929: }
                   1930: 
                   1931: sub externalssi {
                   1932:     my ($url)=@_;
                   1933:     my $ua=new LWP::UserAgent;
                   1934:     my $request=new HTTP::Request('GET',$url);
                   1935:     my $response=$ua->request($request);
1.954     raeburn  1936:     if (wantarray) {
                   1937:         return ($response->content, $response);
                   1938:     } else {
                   1939:         return $response->content;
                   1940:     }
1.15      www      1941: }
1.254     www      1942: 
1.492     albertel 1943: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1944: 
                   1945: sub allowuploaded {
                   1946:     my ($srcurl,$url)=@_;
                   1947:     $url=&clutter(&declutter($url));
                   1948:     my $dir=$url;
                   1949:     $dir=~s/\/[^\/]+$//;
                   1950:     my %httpref=();
                   1951:     my $httpurl=&hreflocation('',$url);
                   1952:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  1953:     &Apache::lonnet::appenv(\%httpref);
1.254     www      1954: }
1.477     raeburn  1955: 
1.478     albertel 1956: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1957: # input: action, courseID, current domain, intended
1.637     raeburn  1958: #        path to file, source of file, instruction to parse file for objects,
                   1959: #        ref to hash for embedded objects,
                   1960: #        ref to hash for codebase of java objects.
                   1961: #
1.485     raeburn  1962: # output: url to file (if action was uploaddoc), 
                   1963: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1964: #
1.478     albertel 1965: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1966: # course.
1.477     raeburn  1967: #
1.478     albertel 1968: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1969: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1970: #          course's home server.
1.477     raeburn  1971: #
1.478     albertel 1972: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1973: #          be copied from $source (current location) to 
                   1974: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1975: #         and will then be copied to
                   1976: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1977: #         course's home server.
1.485     raeburn  1978: #
1.481     raeburn  1979: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1980: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1981: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1982: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1983: #         in course's home server.
1.637     raeburn  1984: #
1.477     raeburn  1985: 
                   1986: sub process_coursefile {
1.638     albertel 1987:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1988:     my $fetchresult;
1.638     albertel 1989:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1990:     if ($action eq 'propagate') {
1.638     albertel 1991:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1992: 			     $home);
1.481     raeburn  1993:     } else {
1.477     raeburn  1994:         my $fpath = '';
                   1995:         my $fname = $file;
1.478     albertel 1996:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1997:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1998:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1999:         if ($action eq 'copy') {
                   2000:             if ($source eq '') {
                   2001:                 $fetchresult = 'no source file';
                   2002:                 return $fetchresult;
                   2003:             } else {
                   2004:                 my $destination = $filepath.'/'.$fname;
                   2005:                 rename($source,$destination);
                   2006:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2007:                                  $home);
1.481     raeburn  2008:             }
                   2009:         } elsif ($action eq 'uploaddoc') {
                   2010:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2011:             print $fh $env{'form.'.$source};
1.481     raeburn  2012:             close($fh);
1.637     raeburn  2013:             if ($parser eq 'parse') {
1.961     raeburn  2014:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
1.637     raeburn  2015:                 unless ($parse_result eq 'ok') {
                   2016:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2017:                 }
                   2018:             }
1.477     raeburn  2019:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2020:                                  $home);
1.481     raeburn  2021:             if ($fetchresult eq 'ok') {
                   2022:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2023:             } else {
                   2024:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2025:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2026:                 return '/adm/notfound.html';
                   2027:             }
1.477     raeburn  2028:         }
                   2029:     }
1.485     raeburn  2030:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2031:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2032:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2033:     }
                   2034:     return $fetchresult;
                   2035: }
                   2036: 
1.637     raeburn  2037: sub build_filepath {
                   2038:     my ($fpath) = @_;
                   2039:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2040:     unless ($fpath eq '') {
                   2041:         my @parts=split('/',$fpath);
                   2042:         foreach my $part (@parts) {
                   2043:             $filepath.= '/'.$part;
                   2044:             if ((-e $filepath)!=1) {
                   2045:                 mkdir($filepath,0777);
                   2046:             }
                   2047:         }
                   2048:     }
                   2049:     return $filepath;
                   2050: }
                   2051: 
                   2052: sub store_edited_file {
1.638     albertel 2053:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2054:     my $file = $primary_url;
                   2055:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2056:     my $fpath = '';
                   2057:     my $fname = $file;
                   2058:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2059:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2060:     my $filepath = &build_filepath($fpath);
                   2061:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2062:     print $fh $content;
                   2063:     close($fh);
1.638     albertel 2064:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2065:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2066: 			  $home);
1.637     raeburn  2067:     if ($$fetchresult eq 'ok') {
                   2068:         return '/uploaded/'.$fpath.'/'.$fname;
                   2069:     } else {
1.638     albertel 2070:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2071: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2072:         return '/adm/notfound.html';
                   2073:     }
                   2074: }
                   2075: 
1.531     albertel 2076: sub clean_filename {
1.831     albertel 2077:     my ($fname,$args)=@_;
1.315     www      2078: # Replace Windows backslashes by forward slashes
1.257     www      2079:     $fname=~s/\\/\//g;
1.831     albertel 2080:     if (!$args->{'keep_path'}) {
                   2081:         # Get rid of everything but the actual filename
                   2082: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2083:     }
1.315     www      2084: # Replace spaces by underscores
                   2085:     $fname=~s/\s+/\_/g;
                   2086: # Replace all other weird characters by nothing
1.831     albertel 2087:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2088: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2089: # numbers
                   2090:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2091:     return $fname;
                   2092: }
1.984     neumanie 2093: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
                   2094: sub resizeImage {
                   2095: 	my($img_url) = @_;	
                   2096: 	my $ima = Image::Magick->new;                       
                   2097:         $ima->Read($img_url);
                   2098: 	if($ima->Get('width') > 400)
                   2099: 	{
                   2100: 		my $factor = $ima->Get('width')/400;
                   2101:              	$ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
                   2102: 	}
                   2103: 	if($ima->Get('height') > 500)
                   2104:         {
                   2105:         	my $factor = $ima->Get('height')/500;
                   2106:                 $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
                   2107:         } 
                   2108: 		
                   2109: 	$ima->Write($img_url);
                   2110: }
1.531     albertel 2111: 
1.977     amueller 2112: #Wrapper function for userphotoupload
                   2113: sub userphotoupload
                   2114: {
                   2115: 	my($formname,$subdir) = @_;
                   2116: 	$upload_photo_form = 1;
                   2117: 	return &userfileupload($formname,undef,$subdir);
                   2118: }
                   2119: 
1.608     albertel 2120: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2121: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 2122: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 2123: #        $coursedoc - if true up to the current course
                   2124: #                     if false
                   2125: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2126: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2127: #        $allfiles - reference to hash for embedded objects
                   2128: #        $codebase - reference to hash for codebase of java objects
                   2129: #        $desuname - username for permanent storage of uploaded file
                   2130: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2131: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2132: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  2133: # 
1.686     albertel 2134: # output: url of file in userspace, or error: <message> 
                   2135: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2136: 
                   2137: 
1.531     albertel 2138: sub userfileupload {
1.860     raeburn  2139:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   2140:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 2141:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2142:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2143:     $fname=&clean_filename($fname);
1.315     www      2144: # See if there is anything left
1.257     www      2145:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2146:     chop($env{'form.'.$formname});
1.523     raeburn  2147:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2148:         my $now = time;
                   2149:         my $filepath = 'tmp/helprequests/'.$now;
                   2150:         my @parts=split(/\//,$filepath);
                   2151:         my $fullpath = $perlvar{'lonDaemons'};
                   2152:         for (my $i=0;$i<@parts;$i++) {
                   2153:             $fullpath .= '/'.$parts[$i];
                   2154:             if ((-e $fullpath)!=1) {
                   2155:                 mkdir($fullpath,0777);
                   2156:             }
                   2157:         }
                   2158:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2159:         print $fh $env{'form.'.$formname};
1.523     raeburn  2160:         close($fh);
1.741     raeburn  2161:         return $fullpath.'/'.$fname;
                   2162:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2163:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2164:                        '_'.$env{'user.domain'}.'/pending';
                   2165:         my @parts=split(/\//,$filepath);
                   2166:         my $fullpath = $perlvar{'lonDaemons'};
                   2167:         for (my $i=0;$i<@parts;$i++) {
                   2168:             $fullpath .= '/'.$parts[$i];
                   2169:             if ((-e $fullpath)!=1) {
                   2170:                 mkdir($fullpath,0777);
                   2171:             }
                   2172:         }
                   2173:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2174:         print $fh $env{'form.'.$formname};
                   2175:         close($fh);
                   2176:         return $fullpath.'/'.$fname;
1.523     raeburn  2177:     }
1.995     raeburn  2178:     if ($subdir eq 'scantron') {
                   2179:         $fname = 'scantron_orig_'.$fname;
                   2180:     } else {   
1.258     www      2181: # Create the directory if not present
1.995     raeburn  2182:         $fname="$subdir/$fname";
                   2183:     }
1.259     www      2184:     if ($coursedoc) {
1.638     albertel 2185: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2186: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2187:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2188:             return &finishuserfileupload($docuname,$docudom,
                   2189: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  2190: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  2191:         } else {
1.620     albertel 2192:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2193:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2194: 				       $fname,$formname,$parser,
                   2195: 				       $allfiles,$codebase);
1.481     raeburn  2196:         }
1.719     banghart 2197:     } elsif (defined($destuname)) {
                   2198:         my $docuname=$destuname;
                   2199:         my $docudom=$destudom;
1.860     raeburn  2200: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2201: 				     $parser,$allfiles,$codebase,
                   2202:                                      $thumbwidth,$thumbheight);
1.719     banghart 2203:         
1.259     www      2204:     } else {
1.638     albertel 2205:         my $docuname=$env{'user.name'};
                   2206:         my $docudom=$env{'user.domain'};
1.714     raeburn  2207:         if (exists($env{'form.group'})) {
                   2208:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2209:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2210:         }
1.860     raeburn  2211: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2212: 				     $parser,$allfiles,$codebase,
                   2213:                                      $thumbwidth,$thumbheight);
1.259     www      2214:     }
1.271     www      2215: }
                   2216: 
                   2217: sub finishuserfileupload {
1.860     raeburn  2218:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   2219:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  2220:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2221:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2222:   
1.860     raeburn  2223:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2224:     $file=$fname;
                   2225:     if ($fname=~m|/|) {
                   2226:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2227: 	$path.=$fnamepath.'/';
                   2228:     }
1.259     www      2229:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2230:     my $count;
                   2231:     for ($count=4;$count<=$#parts;$count++) {
                   2232:         $filepath.="/$parts[$count]";
                   2233:         if ((-e $filepath)!=1) {
                   2234: 	    mkdir($filepath,0777);
                   2235:         }
                   2236:     }
1.984     neumanie 2237: 
1.258     www      2238: # Save the file
                   2239:     {
1.701     albertel 2240: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2241: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2242: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2243: 	    return '/adm/notfound.html';
                   2244: 	}
                   2245: 	if (!print FH ($env{'form.'.$formname})) {
                   2246: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2247: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2248: 	    return '/adm/notfound.html';
                   2249: 	}
1.570     albertel 2250: 	close(FH);
1.977     amueller 2251: 	if($upload_photo_form==1)
                   2252: 	{
1.984     neumanie 2253: 		resizeImage($filepath.'/'.$file);		
1.977     amueller 2254: 		$upload_photo_form = 0;
                   2255: 	}
1.258     www      2256:     }
1.637     raeburn  2257:     if ($parser eq 'parse') {
1.961     raeburn  2258:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
1.638     albertel 2259: 						   $codebase);
1.637     raeburn  2260:         unless ($parse_result eq 'ok') {
1.638     albertel 2261:             &logthis('Failed to parse '.$filepath.$file.
                   2262: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  2263:         }
                   2264:     }
1.860     raeburn  2265:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2266:         my $input = $filepath.'/'.$file;
                   2267:         my $output = $filepath.'/'.'tn-'.$file;
                   2268:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2269:         system("convert -sample $thumbsize $input $output");
                   2270:         if (-e $filepath.'/'.'tn-'.$file) {
                   2271:             $fetchthumb  = 1; 
                   2272:         }
                   2273:     }
1.858     raeburn  2274:  
1.259     www      2275: # Notify homeserver to grep it
                   2276: #
1.984     neumanie 2277:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2278:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2279:     if ($fetchresult eq 'ok') {
1.860     raeburn  2280:         if ($fetchthumb) {
                   2281:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2282:             if ($thumbresult ne 'ok') {
                   2283:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2284:                          $docuhome.': '.$thumbresult);
                   2285:             }
                   2286:         }
1.259     www      2287: #
1.258     www      2288: # Return the URL to it
1.494     albertel 2289:         return '/uploaded/'.$path.$file;
1.263     www      2290:     } else {
1.494     albertel 2291:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2292: 		 ': '.$fetchresult);
1.263     www      2293:         return '/adm/notfound.html';
1.858     raeburn  2294:     }
1.493     albertel 2295: }
                   2296: 
1.637     raeburn  2297: sub extract_embedded_items {
1.961     raeburn  2298:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2299:     my @state = ();
                   2300:     my %javafiles = (
                   2301:                       codebase => '',
                   2302:                       code => '',
                   2303:                       archive => ''
                   2304:                     );
                   2305:     my %mediafiles = (
                   2306:                       src => '',
                   2307:                       movie => '',
                   2308:                      );
1.648     raeburn  2309:     my $p;
                   2310:     if ($content) {
                   2311:         $p = HTML::LCParser->new($content);
                   2312:     } else {
1.961     raeburn  2313:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2314:     }
1.641     albertel 2315:     while (my $t=$p->get_token()) {
1.640     albertel 2316: 	if ($t->[0] eq 'S') {
                   2317: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2318: 	    push(@state, $tagname);
1.648     raeburn  2319:             if (lc($tagname) eq 'allow') {
                   2320:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2321:             }
1.640     albertel 2322: 	    if (lc($tagname) eq 'img') {
                   2323: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2324: 	    }
1.886     albertel 2325: 	    if (lc($tagname) eq 'a') {
                   2326: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2327: 	    }
1.645     raeburn  2328:             if (lc($tagname) eq 'script') {
                   2329:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2330:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2331:                 } else {
                   2332:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2333:                 }
                   2334:             }
                   2335:             if (lc($tagname) eq 'link') {
                   2336:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2337:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2338:                 }
                   2339:             }
1.640     albertel 2340: 	    if (lc($tagname) eq 'object' ||
                   2341: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2342: 		foreach my $item (keys(%javafiles)) {
                   2343: 		    $javafiles{$item} = '';
                   2344: 		}
                   2345: 	    }
                   2346: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2347: 		my $name = lc($attr->{'name'});
                   2348: 		foreach my $item (keys(%javafiles)) {
                   2349: 		    if ($name eq $item) {
                   2350: 			$javafiles{$item} = $attr->{'value'};
                   2351: 			last;
                   2352: 		    }
                   2353: 		}
                   2354: 		foreach my $item (keys(%mediafiles)) {
                   2355: 		    if ($name eq $item) {
                   2356: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2357: 			last;
                   2358: 		    }
                   2359: 		}
                   2360: 	    }
                   2361: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2362: 		foreach my $item (keys(%javafiles)) {
                   2363: 		    if ($attr->{$item}) {
                   2364: 			$javafiles{$item} = $attr->{$item};
                   2365: 			last;
                   2366: 		    }
                   2367: 		}
                   2368: 		foreach my $item (keys(%mediafiles)) {
                   2369: 		    if ($attr->{$item}) {
                   2370: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2371: 			last;
                   2372: 		    }
                   2373: 		}
                   2374: 	    }
                   2375: 	} elsif ($t->[0] eq 'E') {
                   2376: 	    my ($tagname) = ($t->[1]);
                   2377: 	    if ($javafiles{'codebase'} ne '') {
                   2378: 		$javafiles{'codebase'} .= '/';
                   2379: 	    }  
                   2380: 	    if (lc($tagname) eq 'applet' ||
                   2381: 		lc($tagname) eq 'object' ||
                   2382: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2383: 		) {
                   2384: 		foreach my $item (keys(%javafiles)) {
                   2385: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2386: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2387: 			&add_filetype($allfiles,$file,$item);
                   2388: 		    }
                   2389: 		}
                   2390: 	    } 
                   2391: 	    pop @state;
                   2392: 	}
                   2393:     }
1.637     raeburn  2394:     return 'ok';
                   2395: }
                   2396: 
1.639     albertel 2397: sub add_filetype {
                   2398:     my ($allfiles,$file,$type)=@_;
                   2399:     if (exists($allfiles->{$file})) {
                   2400: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2401: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2402: 	}
                   2403:     } else {
                   2404: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2405:     }
                   2406: }
                   2407: 
1.493     albertel 2408: sub removeuploadedurl {
1.984     neumanie 2409:     my ($url)=@_;	
                   2410:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2411:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2412: }
                   2413: 
                   2414: sub removeuserfile {
                   2415:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2416:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2417:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2418:     if ($result eq 'ok') {	
1.798     raeburn  2419:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2420:             my $metafile = $fname.'.meta';
                   2421:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2422: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2423:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2424:             my $sqlresult = 
1.823     albertel 2425:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2426:                                         'portfolio_metadata',$group,
                   2427:                                         'delete');
1.798     raeburn  2428:         }
                   2429:     }
                   2430:     return $result;
1.257     www      2431: }
1.15      www      2432: 
1.530     albertel 2433: sub mkdiruserfile {
                   2434:     my ($docuname,$docudom,$dir)=@_;
                   2435:     my $home=&homeserver($docuname,$docudom);
                   2436:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2437: }
                   2438: 
1.531     albertel 2439: sub renameuserfile {
                   2440:     my ($docuname,$docudom,$old,$new)=@_;
                   2441:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2442:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2443:                         &escape("$old").':'.&escape("$new"),$home);
                   2444:     if ($result eq 'ok') {
                   2445:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2446:             my $oldmeta = $old.'.meta';
                   2447:             my $newmeta = $new.'.meta';
                   2448:             my $metaresult = 
                   2449:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2450: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2451:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2452:             my $sqlresult = 
1.823     albertel 2453:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2454:                                         'portfolio_metadata',$group,
                   2455:                                         'delete');
1.798     raeburn  2456:         }
                   2457:     }
                   2458:     return $result;
1.531     albertel 2459: }
                   2460: 
1.14      www      2461: # ------------------------------------------------------------------------- Log
                   2462: 
                   2463: sub log {
                   2464:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2465:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2466: }
                   2467: 
                   2468: # ------------------------------------------------------------------ Course Log
1.352     www      2469: #
                   2470: # This routine flushes several buffers of non-mission-critical nature
                   2471: #
1.157     www      2472: 
                   2473: sub flushcourselogs {
1.352     www      2474:     &logthis('Flushing log buffers');
                   2475: #
                   2476: # course logs
                   2477: # This is a log of all transactions in a course, which can be used
                   2478: # for data mining purposes
                   2479: #
                   2480: # It also collects the courseid database, which lists last transaction
                   2481: # times and course titles for all courseids
                   2482: #
                   2483:     my %courseidbuffer=();
1.921     raeburn  2484:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2485:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2486: 		          &escape($courselogs{$crsid}),
                   2487: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2488: 	    delete $courselogs{$crsid};
                   2489:         } else {
                   2490:             &logthis('Failed to flush log buffer for '.$crsid);
                   2491:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2492:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2493:                         " exceeded maximum size, deleting.</font>");
                   2494:                delete $courselogs{$crsid};
                   2495:             }
1.352     www      2496:         }
1.920     raeburn  2497:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2498:             'description' => $coursedescrbuf{$crsid},
                   2499:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2500:             'type'        => $coursetypebuf{$crsid},
                   2501:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2502:         };
1.191     harris41 2503:     }
1.352     www      2504: #
                   2505: # Write course id database (reverse lookup) to homeserver of courses 
                   2506: # Is used in pickcourse
                   2507: #
1.840     albertel 2508:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2509:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2510:                                     $courseidbuffer{$crs_home},
                   2511:                                     $crs_home,'timeonly');
1.352     www      2512:     }
                   2513: #
                   2514: # File accesses
                   2515: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2516: #
1.449     matthew  2517:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2518:         if ($entry =~ /___count$/) {
                   2519:             my ($dom,$name);
1.807     albertel 2520:             ($dom,$name,undef)=
1.811     albertel 2521: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2522:             if (! defined($dom) || $dom eq '' || 
                   2523:                 ! defined($name) || $name eq '') {
1.620     albertel 2524:                 my $cid = $env{'request.course.id'};
                   2525:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2526:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2527:             }
1.450     matthew  2528:             my $value = $accesshash{$entry};
                   2529:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2530:             my %temphash=($url => $value);
1.449     matthew  2531:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2532:             if ($result eq 'ok') {
                   2533:                 delete $accesshash{$entry};
                   2534:             } elsif ($result eq 'unknown_cmd') {
                   2535:                 # Target server has old code running on it.
1.450     matthew  2536:                 my %temphash=($entry => $value);
1.449     matthew  2537:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2538:                     delete $accesshash{$entry};
                   2539:                 }
                   2540:             }
                   2541:         } else {
1.811     albertel 2542:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2543:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2544:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2545:                 delete $accesshash{$entry};
                   2546:             }
1.185     www      2547:         }
1.191     harris41 2548:     }
1.352     www      2549: #
                   2550: # Roles
                   2551: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2552: #
1.800     albertel 2553:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2554:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2555: 	    split(/\:/,$entry);
                   2556:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2557:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2558:                 $rudom,$runame) eq 'ok') {
                   2559: 	    delete $userrolehash{$entry};
                   2560:         }
                   2561:     }
1.662     raeburn  2562: #
                   2563: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2564: #
                   2565:     my %domrolebuffer = ();
1.1000    raeburn  2566:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 2567:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2568:         if ($domrolebuffer{$rudom}) {
                   2569:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2570:                       '='.&escape($domainrolehash{$entry});
                   2571:         } else {
                   2572:             $domrolebuffer{$rudom}.=&escape($entry).
                   2573:                       '='.&escape($domainrolehash{$entry});
                   2574:         }
                   2575:         delete $domainrolehash{$entry};
                   2576:     }
                   2577:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2578: 	my %servers = &get_servers($dom,'library');
                   2579: 	foreach my $tryserver (keys(%servers)) {
                   2580: 	    unless (&reply('domroleput:'.$dom.':'.
                   2581: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2582: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2583: 	    }
1.662     raeburn  2584:         }
                   2585:     }
1.186     www      2586:     $dumpcount++;
1.157     www      2587: }
                   2588: 
                   2589: sub courselog {
                   2590:     my $what=shift;
1.158     www      2591:     $what=time.':'.$what;
1.620     albertel 2592:     unless ($env{'request.course.id'}) { return ''; }
                   2593:     $coursedombuf{$env{'request.course.id'}}=
                   2594:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2595:     $coursenumbuf{$env{'request.course.id'}}=
                   2596:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2597:     $coursehombuf{$env{'request.course.id'}}=
                   2598:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2599:     $coursedescrbuf{$env{'request.course.id'}}=
                   2600:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2601:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2602:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2603:     $courseownerbuf{$env{'request.course.id'}}=
                   2604:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2605:     $coursetypebuf{$env{'request.course.id'}}=
                   2606:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2607:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2608: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2609:     } else {
1.620     albertel 2610: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2611:     }
1.620     albertel 2612:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2613: 	&flushcourselogs();
                   2614:     }
1.158     www      2615: }
                   2616: 
                   2617: sub courseacclog {
                   2618:     my $fnsymb=shift;
1.620     albertel 2619:     unless ($env{'request.course.id'}) { return ''; }
                   2620:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2621:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2622:         $what.=':POST';
1.583     matthew  2623:         # FIXME: Probably ought to escape things....
1.800     albertel 2624: 	foreach my $key (keys(%env)) {
                   2625:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2626:                 my $formitem = $1;
                   2627:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2628:                     $what.=':'.$formitem.'='.$env{$key};
                   2629:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2630:                     $what.=':'.$formitem.'='.$env{$key};
                   2631:                 }
1.158     www      2632:             }
1.191     harris41 2633:         }
1.583     matthew  2634:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2635:         # FIXME: We should not be depending on a form parameter that someone
                   2636:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2637:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2638:             $what.= ':POST';
                   2639:             # FIXME: Probably ought to escape things....
                   2640:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2641:                                  'crsdiscuss') {
1.620     albertel 2642:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2643:             }
                   2644:         }
1.158     www      2645:     }
                   2646:     &courselog($what);
1.149     www      2647: }
                   2648: 
1.185     www      2649: sub countacc {
                   2650:     my $url=&declutter(shift);
1.458     matthew  2651:     return if (! defined($url) || $url eq '');
1.620     albertel 2652:     unless ($env{'request.course.id'}) { return ''; }
                   2653:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2654:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2655:     $accesshash{$key}++;
1.185     www      2656: }
1.349     www      2657: 
1.361     www      2658: sub linklog {
                   2659:     my ($from,$to)=@_;
                   2660:     $from=&declutter($from);
                   2661:     $to=&declutter($to);
                   2662:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2663:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2664: }
                   2665:   
1.349     www      2666: sub userrolelog {
                   2667:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2668:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2669:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2670:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2671:         ($trole=~/^ta/)) {
1.350     www      2672:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2673:        $userrolehash
                   2674:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2675:                     =$tend.':'.$tstart;
1.662     raeburn  2676:     }
1.898     albertel 2677:     if (($env{'request.role'} =~ /dc\./) &&
                   2678: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2679: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2680: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2681:        $userrolehash
                   2682:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2683:                     =$tend.':'.$tstart;
                   2684:     }
1.662     raeburn  2685:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2686:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2687:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2688:         ($trole=~/^sc/)) {
                   2689:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2690:        $domainrolehash
                   2691:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2692:                     = $tend.':'.$tstart;
                   2693:     }
1.351     www      2694: }
                   2695: 
1.957     raeburn  2696: sub courserolelog {
                   2697:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2698:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2699:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2700:         ($trole eq 'ta') || ($trole eq 'st') ||
                   2701:         ($trole=~/^cr/) || ($trole eq 'gr')) {
                   2702:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2703:             my $cdom = $1;
                   2704:             my $cnum = $2;
                   2705:             my $sec = $3;
                   2706:             my $namespace = 'rolelog';
                   2707:             my %storehash = (
                   2708:                                role    => $trole,
                   2709:                                start   => $tstart,
                   2710:                                end     => $tend,
                   2711:                                selfenroll => $selfenroll,
                   2712:                                context    => $context,
                   2713:                             );
                   2714:             if ($trole eq 'gr') {
                   2715:                 $namespace = 'groupslog';
                   2716:                 $storehash{'group'} = $sec;
                   2717:             } else {
                   2718:                 $storehash{'section'} = $sec;
                   2719:             }
                   2720:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  2721:             if (($trole ne 'st') || ($sec ne '')) {
                   2722:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   2723:             }
1.957     raeburn  2724:         }
                   2725:     }
                   2726:     return;
                   2727: }
                   2728: 
1.351     www      2729: sub get_course_adv_roles {
1.948     raeburn  2730:     my ($cid,$codes) = @_;
1.620     albertel 2731:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2732:     my %coursehash=&coursedescription($cid);
1.988     raeburn  2733:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      2734:     my %nothide=();
1.800     albertel 2735:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2736:         if ($user !~ /:/) {
                   2737: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2738:         } else {
                   2739:             $nothide{$user}=1;
                   2740:         }
1.470     www      2741:     }
1.351     www      2742:     my %returnhash=();
                   2743:     my %dumphash=
                   2744:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2745:     my $now=time;
1.997     raeburn  2746:     my %privileged;
1.1000    raeburn  2747:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 2748: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2749:         if (($tstart) && ($tstart<0)) { next; }
                   2750:         if (($tend) && ($tend<$now)) { next; }
                   2751:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2752:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2753: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  2754:         unless (ref($privileged{$domain}) eq 'HASH') {
                   2755:             my %dompersonnel =
1.998     raeburn  2756:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  2757:             $privileged{$domain} = {};
                   2758:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  2759:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  2760:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   2761:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   2762:                         $privileged{$udom}{$uname} = 1;
                   2763:                     }
                   2764:                 }
                   2765:             }
                   2766:         }
                   2767:         if ((exists($privileged{$domain}{$username})) && 
                   2768:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2769: 	if ($role eq 'cr') { next; }
1.948     raeburn  2770:         if ($codes) {
                   2771:             if ($section) { $role .= ':'.$section; }
                   2772:             if ($returnhash{$role}) {
                   2773:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2774:             } else {
                   2775:                 $returnhash{$role}=$username.':'.$domain;
                   2776:             }
1.351     www      2777:         } else {
1.988     raeburn  2778:             my $key=&plaintext($role,$crstype);
1.973     bisitz   2779:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  2780:             if ($returnhash{$key}) {
                   2781: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2782:             } else {
                   2783:                 $returnhash{$key}=$username.':'.$domain;
                   2784:             }
1.351     www      2785:         }
1.948     raeburn  2786:     }
1.400     www      2787:     return %returnhash;
                   2788: }
                   2789: 
                   2790: sub get_my_roles {
1.937     raeburn  2791:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2792:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2793:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2794:     my (%dumphash,%nothide);
1.858     raeburn  2795:     if ($context eq 'userroles') { 
                   2796:         %dumphash = &dump('roles',$udom,$uname);
                   2797:     } else {
                   2798:         %dumphash=
1.400     www      2799:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2800:         if ($hidepriv) {
                   2801:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2802:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2803:                 if ($user !~ /:/) {
                   2804:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2805:                 } else {
                   2806:                     $nothide{$user} = 1;
                   2807:                 }
                   2808:             }
                   2809:         }
1.858     raeburn  2810:     }
1.400     www      2811:     my %returnhash=();
                   2812:     my $now=time;
1.999     raeburn  2813:     my %privileged;
1.800     albertel 2814:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2815:         my ($role,$tend,$tstart);
                   2816:         if ($context eq 'userroles') {
                   2817: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2818:         } else {
                   2819:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2820:         }
1.400     www      2821:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2822:         my $status = 'active';
1.939     raeburn  2823:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2824:             $status = 'previous';
                   2825:         } 
                   2826:         if (($tstart) && ($now<$tstart)) {
                   2827:             $status = 'future';
                   2828:         }
                   2829:         if (ref($types) eq 'ARRAY') {
                   2830:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2831:                 next;
                   2832:             } 
                   2833:         } else {
                   2834:             if ($status ne 'active') {
                   2835:                 next;
                   2836:             }
                   2837:         }
1.867     raeburn  2838:         my ($rolecode,$username,$domain,$section,$area);
                   2839:         if ($context eq 'userroles') {
                   2840:             ($area,$rolecode) = split(/_/,$entry);
                   2841:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2842:         } else {
                   2843:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2844:         }
1.832     raeburn  2845:         if (ref($roledoms) eq 'ARRAY') {
                   2846:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2847:                 next;
                   2848:             }
                   2849:         }
                   2850:         if (ref($roles) eq 'ARRAY') {
                   2851:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2852:                 if ($role =~ /^cr\//) {
                   2853:                     if (!grep(/^cr$/,@{$roles})) {
                   2854:                         next;
                   2855:                     }
                   2856:                 } else {
                   2857:                     next;
                   2858:                 }
1.832     raeburn  2859:             }
1.867     raeburn  2860:         }
1.937     raeburn  2861:         if ($hidepriv) {
1.999     raeburn  2862:             if ($context eq 'userroles') {
                   2863:                 if ((&privileged($username,$domain)) &&
                   2864:                     (!$nothide{$username.':'.$domain})) {
                   2865:                     next;
                   2866:                 }
                   2867:             } else {
                   2868:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   2869:                     my %dompersonnel =
                   2870:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   2871:                     $privileged{$domain} = {};
                   2872:                     if (keys(%dompersonnel)) {
                   2873:                         foreach my $server (keys(%dompersonnel)) {
                   2874:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   2875:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   2876:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   2877:                                     $privileged{$udom}{$uname} = $trole;
                   2878:                                 }
                   2879:                             }
                   2880:                         }
                   2881:                     }
                   2882:                 }
                   2883:                 if (exists($privileged{$domain}{$username})) {
                   2884:                     if (!$nothide{$username.':'.$domain}) {
                   2885:                         next;
                   2886:                     }
                   2887:                 }
1.937     raeburn  2888:             }
                   2889:         }
1.933     raeburn  2890:         if ($withsec) {
                   2891:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2892:                 $tstart.':'.$tend;
                   2893:         } else {
                   2894:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2895:         }
1.832     raeburn  2896:     }
1.373     www      2897:     return %returnhash;
1.399     www      2898: }
                   2899: 
                   2900: # ----------------------------------------------------- Frontpage Announcements
                   2901: #
                   2902: #
                   2903: 
                   2904: sub postannounce {
                   2905:     my ($server,$text)=@_;
1.844     albertel 2906:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2907:     unless ($text=~/\w/) { $text=''; }
                   2908:     return &reply('setannounce:'.&escape($text),$server);
                   2909: }
                   2910: 
                   2911: sub getannounce {
1.448     albertel 2912: 
                   2913:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2914: 	my $announcement='';
1.800     albertel 2915: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2916: 	close($fh);
1.399     www      2917: 	if ($announcement=~/\w/) { 
                   2918: 	    return 
                   2919:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2920:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2921: 	} else {
                   2922: 	    return '';
                   2923: 	}
                   2924:     } else {
                   2925: 	return '';
                   2926:     }
1.351     www      2927: }
1.353     www      2928: 
                   2929: # ---------------------------------------------------------- Course ID routines
                   2930: # Deal with domain's nohist_courseid.db files
                   2931: #
                   2932: 
                   2933: sub courseidput {
1.921     raeburn  2934:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2935:     my $outcome;
                   2936:     if ($caller eq 'timeonly') {
                   2937:         my $cids = '';
                   2938:         foreach my $item (keys(%$storehash)) {
                   2939:             $cids.=&escape($item).'&';
                   2940:         }
                   2941:         $cids=~s/\&$//;
                   2942:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2943:                           $coursehome);       
                   2944:     } else {
                   2945:         my $items = '';
                   2946:         foreach my $item (keys(%$storehash)) {
                   2947:             $items.= &escape($item).'='.
                   2948:                      &freeze_escape($$storehash{$item}).'&';
                   2949:         }
                   2950:         $items=~s/\&$//;
                   2951:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2952:                           $coursehome);
1.918     raeburn  2953:     }
                   2954:     if ($outcome eq 'unknown_cmd') {
                   2955:         my $what;
                   2956:         foreach my $cid (keys(%$storehash)) {
                   2957:             $what .= &escape($cid).'=';
1.921     raeburn  2958:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2959:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2960:             }
                   2961:             $what =~ s/\:$/&/;
                   2962:         }
                   2963:         $what =~ s/\&$//;  
                   2964:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2965:     } else {
                   2966:         return $outcome;
                   2967:     }
1.353     www      2968: }
                   2969: 
                   2970: sub courseiddump {
1.921     raeburn  2971:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  2972:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1008    raeburn  2973:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,$cloneonly)=@_;
1.918     raeburn  2974:     my $as_hash = 1;
                   2975:     my %returnhash;
                   2976:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2977:     my %libserv = &all_library();
                   2978:     foreach my $tryserver (keys(%libserv)) {
                   2979:         if ( (  $hostidflag == 1 
                   2980: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2981: 	     || (!defined($hostidflag)) ) {
                   2982: 
1.918     raeburn  2983: 	    if (($domfilter eq '') ||
                   2984: 		(&host_domain($tryserver) eq $domfilter)) {
                   2985:                 my $rep = 
                   2986:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2987:                          $sincefilter.':'.&escape($descfilter).':'.
                   2988:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2989:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  2990:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  2991:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  2992:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   2993:                          &escape($cc_clone).':'.$cloneonly,$tryserver);
1.918     raeburn  2994:                 my @pairs=split(/\&/,$rep);
                   2995:                 foreach my $item (@pairs) {
                   2996:                     my ($key,$value)=split(/\=/,$item,2);
                   2997:                     $key = &unescape($key);
                   2998:                     next if ($key =~ /^error: 2 /);
                   2999:                     my $result = &thaw_unescape($value);
                   3000:                     if (ref($result) eq 'HASH') {
                   3001:                         $returnhash{$key}=$result;
                   3002:                     } else {
1.921     raeburn  3003:                         my @responses = split(/:/,$value);
                   3004:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3005:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3006:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3007:                         }
1.1008    raeburn  3008:                     }
1.353     www      3009:                 }
                   3010:             }
                   3011:         }
                   3012:     }
                   3013:     return %returnhash;
                   3014: }
                   3015: 
1.658     raeburn  3016: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3017: 
                   3018: sub dcmailput {
1.685     raeburn  3019:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3020:     my $status = &Apache::lonnet::critical(
1.740     www      3021:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3022:        &escape($message),$server);
1.662     raeburn  3023:     return $status;
                   3024: }
                   3025: 
1.658     raeburn  3026: sub dcmaildump {
                   3027:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3028:     my %returnhash=();
1.846     albertel 3029: 
                   3030:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3031:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3032:                                                          &escape($enddate).':';
                   3033: 	my @esc_senders=map { &escape($_)} @$senders;
                   3034: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3035: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3036:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3037:             if (($key) && ($value)) {
                   3038:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3039:             }
                   3040:         }
                   3041:     }
                   3042:     return %returnhash;
                   3043: }
1.662     raeburn  3044: # ---------------------------------------------------------- Domain roles
                   3045: 
                   3046: sub get_domain_roles {
                   3047:     my ($dom,$roles,$startdate,$enddate)=@_;
                   3048:     if (undef($startdate) || $startdate eq '') {
                   3049:         $startdate = '.';
                   3050:     }
                   3051:     if (undef($enddate) || $enddate eq '') {
                   3052:         $enddate = '.';
                   3053:     }
1.922     raeburn  3054:     my $rolelist;
                   3055:     if (ref($roles) eq 'ARRAY') {
                   3056:         $rolelist = join(':',@{$roles});
                   3057:     }
1.662     raeburn  3058:     my %personnel = ();
1.841     albertel 3059: 
                   3060:     my %servers = &get_servers($dom,'library');
                   3061:     foreach my $tryserver (keys(%servers)) {
                   3062: 	%{$personnel{$tryserver}}=();
                   3063: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3064: 					    &escape($startdate).':'.
                   3065: 					    &escape($enddate).':'.
                   3066: 					    &escape($rolelist), $tryserver))) {
                   3067: 	    my ($key,$value) = split(/\=/,$line,2);
                   3068: 	    if (($key) && ($value)) {
                   3069: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3070: 	    }
                   3071: 	}
1.662     raeburn  3072:     }
                   3073:     return %personnel;
                   3074: }
1.658     raeburn  3075: 
1.149     www      3076: # ----------------------------------------------------------- Check out an item
                   3077: 
1.504     albertel 3078: sub get_first_access {
                   3079:     my ($type,$argsymb)=@_;
1.790     albertel 3080:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3081:     if ($argsymb) { $symb=$argsymb; }
                   3082:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3083:     if ($type eq 'course') {
                   3084: 	$res='course';
                   3085:     } elsif ($type eq 'map') {
1.588     albertel 3086: 	$res=&symbread($map);
                   3087:     } else {
                   3088: 	$res=$symb;
                   3089:     }
                   3090:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3091:     return $times{"$courseid\0$res"};
1.504     albertel 3092: }
                   3093: 
                   3094: sub set_first_access {
                   3095:     my ($type)=@_;
1.790     albertel 3096:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3097:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3098:     if ($type eq 'course') {
                   3099: 	$res='course';
                   3100:     } elsif ($type eq 'map') {
1.588     albertel 3101: 	$res=&symbread($map);
                   3102:     } else {
                   3103: 	$res=$symb;
                   3104:     }
                   3105:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3106:     if (!$firstaccess) {
1.588     albertel 3107: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3108:     }
                   3109:     return 'already_set';
1.504     albertel 3110: }
                   3111: 
1.149     www      3112: sub checkout {
                   3113:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   3114:     my $now=time;
                   3115:     my $lonhost=$perlvar{'lonHostID'};
                   3116:     my $infostr=&escape(
1.234     www      3117:                  'CHECKOUTTOKEN&'.
1.149     www      3118:                  $tuname.'&'.
                   3119:                  $tudom.'&'.
                   3120:                  $tcrsid.'&'.
                   3121:                  $symb.'&'.
                   3122: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   3123:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      3124:     if ($token=~/^error\:/) { 
1.672     albertel 3125:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3126:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3127:                  "</font>");
                   3128:         return ''; 
                   3129:     }
                   3130: 
1.149     www      3131:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   3132:     $token=~tr/a-z/A-Z/;
                   3133: 
1.153     www      3134:     my %infohash=('resource.0.outtoken' => $token,
                   3135:                   'resource.0.checkouttime' => $now,
                   3136:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      3137: 
                   3138:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3139:        return '';
1.151     www      3140:     } else {
1.672     albertel 3141:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3142:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3143:                  "</font>");
1.149     www      3144:     }    
                   3145: 
                   3146:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3147:                          &escape('Checkout '.$infostr.' - '.
                   3148:                                                  $token)) ne 'ok') {
                   3149: 	return '';
1.151     www      3150:     } else {
1.672     albertel 3151:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3152:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3153:                  "</font>");
1.149     www      3154:     }
1.151     www      3155:     return $token;
1.149     www      3156: }
                   3157: 
                   3158: # ------------------------------------------------------------ Check in an item
                   3159: 
                   3160: sub checkin {
                   3161:     my $token=shift;
1.150     www      3162:     my $now=time;
                   3163:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3164:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3165:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3166:     $dtoken=~s/\W/\_/g;
1.234     www      3167:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3168:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3169: 
1.154     www      3170:     unless (($tuname) && ($tudom)) {
                   3171:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3172:         return '';
                   3173:     }
                   3174:     
                   3175:     unless (&allowed('mgr',$tcrsid)) {
                   3176:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3177:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3178:         return '';
                   3179:     }
                   3180: 
1.153     www      3181:     my %infohash=('resource.0.intoken' => $token,
                   3182:                   'resource.0.checkintime' => $now,
                   3183:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3184: 
                   3185:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3186:        return '';
                   3187:     }    
                   3188: 
                   3189:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3190:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3191: 	return '';
                   3192:     }
                   3193: 
                   3194:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3195: }
                   3196: 
                   3197: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3198: 
                   3199: sub expirespread {
                   3200:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3201:     my $cid=$env{'request.course.id'}; 
1.110     www      3202:     if ($cid) {
                   3203:        my $now=time;
                   3204:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3205:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3206:                             $env{'course.'.$cid.'.num'}.
1.110     www      3207: 	        	    ':nohist_expirationdates:'.
                   3208:                             &escape($key).'='.$now,
1.620     albertel 3209:                             $env{'course.'.$cid.'.home'})
1.110     www      3210:     }
                   3211:     return 'ok';
1.14      www      3212: }
                   3213: 
1.109     www      3214: # ----------------------------------------------------- Devalidate Spreadsheets
                   3215: 
                   3216: sub devalidate {
1.325     www      3217:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3218:     my $cid=$env{'request.course.id'}; 
1.109     www      3219:     if ($cid) {
1.391     matthew  3220:         # delete the stored spreadsheets for
                   3221:         # - the student level sheet of this user in course's homespace
                   3222:         # - the assessment level sheet for this resource 
                   3223:         #   for this user in user's homespace
1.553     albertel 3224: 	# - current conditional state info
1.325     www      3225: 	my $key=$uname.':'.$udom.':';
1.109     www      3226:         my $status=
1.299     matthew  3227: 	    &del('nohist_calculatedsheets',
1.391     matthew  3228: 		 [$key.'studentcalc:'],
1.620     albertel 3229: 		 $env{'course.'.$cid.'.domain'},
                   3230: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3231: 		.' '.
                   3232: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3233: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3234:         unless ($status eq 'ok ok') {
                   3235:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3236:                     $uname.' at '.$udom.' for '.
1.109     www      3237: 		    $symb.': '.$status);
1.133     albertel 3238:         }
1.553     albertel 3239: 	&delenv('user.state.'.$cid);
1.109     www      3240:     }
                   3241: }
                   3242: 
1.265     albertel 3243: sub get_scalar {
                   3244:     my ($string,$end) = @_;
                   3245:     my $value;
                   3246:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3247: 	$value = $1;
                   3248:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3249: 	$value = $1;
                   3250:     }
                   3251:     return &unescape($value);
                   3252: }
                   3253: 
                   3254: sub array2str {
                   3255:   my (@array) = @_;
                   3256:   my $result=&arrayref2str(\@array);
                   3257:   $result=~s/^__ARRAY_REF__//;
                   3258:   $result=~s/__END_ARRAY_REF__$//;
                   3259:   return $result;
                   3260: }
                   3261: 
1.204     albertel 3262: sub arrayref2str {
                   3263:   my ($arrayref) = @_;
1.265     albertel 3264:   my $result='__ARRAY_REF__';
1.204     albertel 3265:   foreach my $elem (@$arrayref) {
1.265     albertel 3266:     if(ref($elem) eq 'ARRAY') {
                   3267:       $result.=&arrayref2str($elem).'&';
                   3268:     } elsif(ref($elem) eq 'HASH') {
                   3269:       $result.=&hashref2str($elem).'&';
                   3270:     } elsif(ref($elem)) {
                   3271:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3272:     } else {
                   3273:       $result.=&escape($elem).'&';
                   3274:     }
                   3275:   }
                   3276:   $result=~s/\&$//;
1.265     albertel 3277:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3278:   return $result;
                   3279: }
                   3280: 
1.168     albertel 3281: sub hash2str {
1.204     albertel 3282:   my (%hash) = @_;
                   3283:   my $result=&hashref2str(\%hash);
1.265     albertel 3284:   $result=~s/^__HASH_REF__//;
                   3285:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3286:   return $result;
                   3287: }
                   3288: 
                   3289: sub hashref2str {
                   3290:   my ($hashref)=@_;
1.265     albertel 3291:   my $result='__HASH_REF__';
1.800     albertel 3292:   foreach my $key (sort(keys(%$hashref))) {
                   3293:     if (ref($key) eq 'ARRAY') {
                   3294:       $result.=&arrayref2str($key).'=';
                   3295:     } elsif (ref($key) eq 'HASH') {
                   3296:       $result.=&hashref2str($key).'=';
                   3297:     } elsif (ref($key)) {
1.265     albertel 3298:       $result.='=';
1.800     albertel 3299:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3300:     } else {
1.800     albertel 3301: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3302:     }
                   3303: 
1.800     albertel 3304:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3305:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3306:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3307:       $result.=&hashref2str($hashref->{$key}).'&';
                   3308:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3309:        $result.='&';
1.800     albertel 3310:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3311:     } else {
1.800     albertel 3312:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3313:     }
                   3314:   }
1.168     albertel 3315:   $result=~s/\&$//;
1.265     albertel 3316:   $result .= '__END_HASH_REF__';
1.168     albertel 3317:   return $result;
                   3318: }
                   3319: 
                   3320: sub str2hash {
1.265     albertel 3321:     my ($string)=@_;
                   3322:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3323:     return %$hash;
                   3324: }
                   3325: 
                   3326: sub str2hashref {
1.168     albertel 3327:   my ($string) = @_;
1.265     albertel 3328: 
                   3329:   my %hash;
                   3330: 
                   3331:   if($string !~ /^__HASH_REF__/) {
                   3332:       if (! ($string eq '' || !defined($string))) {
                   3333: 	  $hash{'error'}='Not hash reference';
                   3334:       }
                   3335:       return (\%hash, $string);
                   3336:   }
                   3337: 
                   3338:   $string =~ s/^__HASH_REF__//;
                   3339: 
                   3340:   while($string !~ /^__END_HASH_REF__/) {
                   3341:       #key
                   3342:       my $key='';
                   3343:       if($string =~ /^__HASH_REF__/) {
                   3344:           ($key, $string)=&str2hashref($string);
                   3345:           if(defined($key->{'error'})) {
                   3346:               $hash{'error'}='Bad data';
                   3347:               return (\%hash, $string);
                   3348:           }
                   3349:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3350:           ($key, $string)=&str2arrayref($string);
                   3351:           if($key->[0] eq 'Array reference error') {
                   3352:               $hash{'error'}='Bad data';
                   3353:               return (\%hash, $string);
                   3354:           }
                   3355:       } else {
                   3356:           $string =~ s/^(.*?)=//;
1.267     albertel 3357: 	  $key=&unescape($1);
1.265     albertel 3358:       }
                   3359:       $string =~ s/^=//;
                   3360: 
                   3361:       #value
                   3362:       my $value='';
                   3363:       if($string =~ /^__HASH_REF__/) {
                   3364:           ($value, $string)=&str2hashref($string);
                   3365:           if(defined($value->{'error'})) {
                   3366:               $hash{'error'}='Bad data';
                   3367:               return (\%hash, $string);
                   3368:           }
                   3369:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3370:           ($value, $string)=&str2arrayref($string);
                   3371:           if($value->[0] eq 'Array reference error') {
                   3372:               $hash{'error'}='Bad data';
                   3373:               return (\%hash, $string);
                   3374:           }
                   3375:       } else {
                   3376: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3377:       }
                   3378:       $string =~ s/^&//;
                   3379: 
                   3380:       $hash{$key}=$value;
1.204     albertel 3381:   }
1.265     albertel 3382: 
                   3383:   $string =~ s/^__END_HASH_REF__//;
                   3384: 
                   3385:   return (\%hash, $string);
1.204     albertel 3386: }
                   3387: 
                   3388: sub str2array {
1.265     albertel 3389:     my ($string)=@_;
                   3390:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3391:     return @$array;
                   3392: }
                   3393: 
                   3394: sub str2arrayref {
1.204     albertel 3395:   my ($string) = @_;
1.265     albertel 3396:   my @array;
                   3397: 
                   3398:   if($string !~ /^__ARRAY_REF__/) {
                   3399:       if (! ($string eq '' || !defined($string))) {
                   3400: 	  $array[0]='Array reference error';
                   3401:       }
                   3402:       return (\@array, $string);
                   3403:   }
                   3404: 
                   3405:   $string =~ s/^__ARRAY_REF__//;
                   3406: 
                   3407:   while($string !~ /^__END_ARRAY_REF__/) {
                   3408:       my $value='';
                   3409:       if($string =~ /^__HASH_REF__/) {
                   3410:           ($value, $string)=&str2hashref($string);
                   3411:           if(defined($value->{'error'})) {
                   3412:               $array[0] ='Array reference error';
                   3413:               return (\@array, $string);
                   3414:           }
                   3415:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3416:           ($value, $string)=&str2arrayref($string);
                   3417:           if($value->[0] eq 'Array reference error') {
                   3418:               $array[0] ='Array reference error';
                   3419:               return (\@array, $string);
                   3420:           }
                   3421:       } else {
                   3422: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3423:       }
                   3424:       $string =~ s/^&//;
                   3425: 
                   3426:       push(@array, $value);
1.191     harris41 3427:   }
1.265     albertel 3428: 
                   3429:   $string =~ s/^__END_ARRAY_REF__//;
                   3430: 
                   3431:   return (\@array, $string);
1.168     albertel 3432: }
                   3433: 
1.167     albertel 3434: # -------------------------------------------------------------------Temp Store
                   3435: 
1.168     albertel 3436: sub tmpreset {
                   3437:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3438:   if (!$symb) {
                   3439:     $symb=&symbread();
1.620     albertel 3440:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3441:   }
                   3442:   $symb=escape($symb);
                   3443: 
1.620     albertel 3444:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3445:   $namespace=~s/\//\_/g;
                   3446:   $namespace=~s/\W//g;
                   3447: 
1.620     albertel 3448:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3449:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3450:   if ($domain eq 'public' && $stuname eq 'public') {
                   3451:       $stuname=$ENV{'REMOTE_ADDR'};
                   3452:   }
1.168     albertel 3453:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3454:   my %hash;
                   3455:   if (tie(%hash,'GDBM_File',
                   3456: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3457: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3458:     foreach my $key (keys(%hash)) {
1.180     albertel 3459:       if ($key=~ /:$symb/) {
1.168     albertel 3460: 	delete($hash{$key});
                   3461:       }
                   3462:     }
                   3463:   }
                   3464: }
                   3465: 
1.167     albertel 3466: sub tmpstore {
1.168     albertel 3467:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3468: 
                   3469:   if (!$symb) {
                   3470:     $symb=&symbread();
1.620     albertel 3471:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3472:   }
                   3473:   $symb=escape($symb);
                   3474: 
                   3475:   if (!$namespace) {
                   3476:     # I don't think we would ever want to store this for a course.
                   3477:     # it seems this will only be used if we don't have a course.
1.620     albertel 3478:     #$namespace=$env{'request.course.id'};
1.168     albertel 3479:     #if (!$namespace) {
1.620     albertel 3480:       $namespace=$env{'request.state'};
1.168     albertel 3481:     #}
                   3482:   }
                   3483:   $namespace=~s/\//\_/g;
                   3484:   $namespace=~s/\W//g;
1.620     albertel 3485:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3486:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3487:   if ($domain eq 'public' && $stuname eq 'public') {
                   3488:       $stuname=$ENV{'REMOTE_ADDR'};
                   3489:   }
1.168     albertel 3490:   my $now=time;
                   3491:   my %hash;
                   3492:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3493:   if (tie(%hash,'GDBM_File',
                   3494: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3495: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3496:     $hash{"version:$symb"}++;
                   3497:     my $version=$hash{"version:$symb"};
                   3498:     my $allkeys=''; 
                   3499:     foreach my $key (keys(%$storehash)) {
                   3500:       $allkeys.=$key.':';
1.591     albertel 3501:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3502:     }
                   3503:     $hash{"$version:$symb:timestamp"}=$now;
                   3504:     $allkeys.='timestamp';
                   3505:     $hash{"$version:keys:$symb"}=$allkeys;
                   3506:     if (untie(%hash)) {
                   3507:       return 'ok';
                   3508:     } else {
                   3509:       return "error:$!";
                   3510:     }
                   3511:   } else {
                   3512:     return "error:$!";
                   3513:   }
                   3514: }
1.167     albertel 3515: 
1.168     albertel 3516: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3517: 
1.168     albertel 3518: sub tmprestore {
                   3519:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3520: 
1.168     albertel 3521:   if (!$symb) {
                   3522:     $symb=&symbread();
1.620     albertel 3523:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3524:   }
                   3525:   $symb=escape($symb);
                   3526: 
1.620     albertel 3527:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3528: 
1.620     albertel 3529:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3530:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3531:   if ($domain eq 'public' && $stuname eq 'public') {
                   3532:       $stuname=$ENV{'REMOTE_ADDR'};
                   3533:   }
1.168     albertel 3534:   my %returnhash;
                   3535:   $namespace=~s/\//\_/g;
                   3536:   $namespace=~s/\W//g;
                   3537:   my %hash;
                   3538:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3539:   if (tie(%hash,'GDBM_File',
                   3540: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3541: 	  &GDBM_READER(),0640)) {
1.168     albertel 3542:     my $version=$hash{"version:$symb"};
                   3543:     $returnhash{'version'}=$version;
                   3544:     my $scope;
                   3545:     for ($scope=1;$scope<=$version;$scope++) {
                   3546:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3547:       my @keys=split(/:/,$vkeys);
                   3548:       my $key;
                   3549:       $returnhash{"$scope:keys"}=$vkeys;
                   3550:       foreach $key (@keys) {
1.591     albertel 3551: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3552: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3553:       }
                   3554:     }
1.168     albertel 3555:     if (!(untie(%hash))) {
                   3556:       return "error:$!";
                   3557:     }
                   3558:   } else {
                   3559:     return "error:$!";
                   3560:   }
                   3561:   return %returnhash;
1.167     albertel 3562: }
                   3563: 
1.9       www      3564: # ----------------------------------------------------------------------- Store
                   3565: 
                   3566: sub store {
1.124     www      3567:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3568:     my $home='';
                   3569: 
1.168     albertel 3570:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3571: 
1.213     www      3572:     $symb=&symbclean($symb);
1.122     albertel 3573:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3574: 
1.620     albertel 3575:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3576:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3577: 
                   3578:     &devalidate($symb,$stuname,$domain);
1.109     www      3579: 
                   3580:     $symb=escape($symb);
1.187     www      3581:     if (!$namespace) { 
1.620     albertel 3582:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3583:           return ''; 
                   3584:        } 
                   3585:     }
1.620     albertel 3586:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3587: 
                   3588:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3589:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3590: 
1.12      www      3591:     my $namevalue='';
1.800     albertel 3592:     foreach my $key (keys(%$storehash)) {
                   3593:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3594:     }
1.12      www      3595:     $namevalue=~s/\&$//;
1.187     www      3596:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3597:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3598: }
                   3599: 
1.47      www      3600: # -------------------------------------------------------------- Critical Store
                   3601: 
                   3602: sub cstore {
1.124     www      3603:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3604:     my $home='';
                   3605: 
1.168     albertel 3606:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3607: 
1.213     www      3608:     $symb=&symbclean($symb);
1.122     albertel 3609:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3610: 
1.620     albertel 3611:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3612:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3613: 
                   3614:     &devalidate($symb,$stuname,$domain);
1.109     www      3615: 
                   3616:     $symb=escape($symb);
1.187     www      3617:     if (!$namespace) { 
1.620     albertel 3618:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3619:           return ''; 
                   3620:        } 
                   3621:     }
1.620     albertel 3622:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3623: 
                   3624:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3625:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3626: 
1.47      www      3627:     my $namevalue='';
1.800     albertel 3628:     foreach my $key (keys(%$storehash)) {
                   3629:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3630:     }
1.47      www      3631:     $namevalue=~s/\&$//;
1.187     www      3632:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3633:     return critical
                   3634:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3635: }
                   3636: 
1.9       www      3637: # --------------------------------------------------------------------- Restore
                   3638: 
                   3639: sub restore {
1.124     www      3640:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3641:     my $home='';
                   3642: 
1.168     albertel 3643:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3644: 
1.122     albertel 3645:     if (!$symb) {
                   3646:       unless ($symb=escape(&symbread())) { return ''; }
                   3647:     } else {
1.213     www      3648:       $symb=&escape(&symbclean($symb));
1.122     albertel 3649:     }
1.188     www      3650:     if (!$namespace) { 
1.620     albertel 3651:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3652:           return ''; 
                   3653:        } 
                   3654:     }
1.620     albertel 3655:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3656:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3657:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3658:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3659: 
1.12      www      3660:     my %returnhash=();
1.800     albertel 3661:     foreach my $line (split(/\&/,$answer)) {
                   3662: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3663:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3664:     }
1.75      www      3665:     my $version;
                   3666:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3667:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3668:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3669:        }
1.75      www      3670:     }
1.13      www      3671:     return %returnhash;
1.34      www      3672: }
                   3673: 
                   3674: # ---------------------------------------------------------- Course Description
                   3675: 
                   3676: sub coursedescription {
1.731     albertel 3677:     my ($courseid,$args)=@_;
1.34      www      3678:     $courseid=~s/^\///;
1.49      www      3679:     $courseid=~s/\_/\//g;
1.34      www      3680:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3681:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3682:     my $normalid=$cdomain.'_'.$cnum;
                   3683:     # need to always cache even if we get errors otherwise we keep 
                   3684:     # trying and trying and trying to get the course description.
                   3685:     my %envhash=();
                   3686:     my %returnhash=();
1.731     albertel 3687:     
                   3688:     my $expiretime=600;
                   3689:     if ($env{'request.course.id'} eq $normalid) {
                   3690: 	$expiretime=120;
                   3691:     }
                   3692: 
                   3693:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3694:     if (!$args->{'freshen_cache'}
                   3695: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3696: 	foreach my $key (keys(%env)) {
                   3697: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3698: 	    my ($setting) = $1;
                   3699: 	    $returnhash{$setting} = $env{$key};
                   3700: 	}
                   3701: 	return %returnhash;
                   3702:     }
                   3703: 
                   3704:     # get the data agin
                   3705:     if (!$args->{'one_time'}) {
                   3706: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3707:     }
1.811     albertel 3708: 
1.34      www      3709:     if ($chome ne 'no_host') {
1.302     albertel 3710:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3711:        if (!exists($returnhash{'con_lost'})) {
                   3712:            $returnhash{'home'}= $chome;
                   3713: 	   $returnhash{'domain'} = $cdomain;
                   3714: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3715:            if (!defined($returnhash{'type'})) {
                   3716:                $returnhash{'type'} = 'Course';
                   3717:            }
1.130     albertel 3718:            while (my ($name,$value) = each %returnhash) {
1.53      www      3719:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3720:            }
1.270     www      3721:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3722:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3723: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3724:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3725:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3726:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3727:        }
                   3728:     }
1.731     albertel 3729:     if (!$args->{'one_time'}) {
1.949     raeburn  3730: 	&appenv(\%envhash);
1.731     albertel 3731:     }
1.302     albertel 3732:     return %returnhash;
1.461     www      3733: }
                   3734: 
                   3735: # -------------------------------------------------See if a user is privileged
                   3736: 
                   3737: sub privileged {
                   3738:     my ($username,$domain)=@_;
                   3739:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3740: 			&homeserver($username,$domain));
                   3741:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3742:     my $now=time;
                   3743:     if ($rolesdump ne '') {
1.800     albertel 3744:         foreach my $entry (split(/&/,$rolesdump)) {
                   3745: 	    if ($entry!~/^rolesdef_/) {
                   3746: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3747: 		$area=~s/\_\w\w$//;
                   3748: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3749: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3750: 		    my $active=1;
                   3751: 		    if ($tend) {
                   3752: 			if ($tend<$now) { $active=0; }
                   3753: 		    }
                   3754: 		    if ($tstart) {
                   3755: 			if ($tstart>$now) { $active=0; }
                   3756: 		    }
                   3757: 		    if ($active) { return 1; }
                   3758: 		}
                   3759: 	    }
                   3760: 	}
                   3761:     }
                   3762:     return 0;
1.9       www      3763: }
1.1       albertel 3764: 
1.103     harris41 3765: # -------------------------------------------------------- Get user privileges
1.11      www      3766: 
                   3767: sub rolesinit {
                   3768:     my ($domain,$username,$authhost)=@_;
1.966     raeburn  3769:     my %userroles;
1.11      www      3770:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.966     raeburn  3771:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
1.11      www      3772:     my %allroles=();
1.678     raeburn  3773:     my %allgroups=();   
1.11      www      3774:     my $now=time;
1.966     raeburn  3775:     %userroles = ('user.login.time' => $now);
1.678     raeburn  3776:     my $group_privs;
1.11      www      3777: 
                   3778:     if ($rolesdump ne '') {
1.800     albertel 3779:         foreach my $entry (split(/&/,$rolesdump)) {
                   3780: 	  if ($entry!~/^rolesdef_/) {
                   3781:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3782: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3783:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3784: 	    if ($role=~/^cr/) { 
1.807     albertel 3785: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3786: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3787: 		    ($tend,$tstart)=split('_',$trest);
                   3788: 		} else {
                   3789: 		    $trole=$role;
                   3790: 		}
1.678     raeburn  3791:             } elsif ($role =~ m|^gr/|) {
                   3792:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3793:                 ($trole,$group_privs) = split(/\//,$trole);
                   3794:                 $group_privs = &unescape($group_privs);
1.587     albertel 3795: 	    } else {
                   3796: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3797: 	    }
1.743     albertel 3798: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3799: 					 $username);
                   3800: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3801:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3802:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3803:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3804: 		my $spec=$trole.'.'.$area;
                   3805: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3806: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3807:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3808:                 } elsif ($trole eq 'gr') {
                   3809:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3810: 		} else {
1.567     raeburn  3811:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3812: 		}
1.12      www      3813:             }
1.662     raeburn  3814:           }
1.191     harris41 3815:         }
1.743     albertel 3816:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3817:         $userroles{'user.adv'}    = $adv;
                   3818: 	$userroles{'user.author'} = $author;
1.620     albertel 3819:         $env{'user.adv'}=$adv;
1.11      www      3820:     }
1.743     albertel 3821:     return \%userroles;  
1.11      www      3822: }
                   3823: 
1.567     raeburn  3824: sub set_arearole {
                   3825:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3826: # log the associated role with the area
                   3827:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3828:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3829: }
                   3830: 
                   3831: sub custom_roleprivs {
                   3832:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3833:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3834:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3835:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3836:         my ($rdummy,$roledef)=
                   3837:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3838:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3839:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3840:             if (defined($syspriv)) {
                   3841:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3842:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3843:             }
                   3844:             if ($tdomain ne '') {
                   3845:                 if (defined($dompriv)) {
                   3846:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3847:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3848:                 }
                   3849:                 if (($trest ne '') && (defined($coursepriv))) {
                   3850:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3851:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3852:                 }
                   3853:             }
                   3854:         }
                   3855:     }
                   3856: }
                   3857: 
1.678     raeburn  3858: sub group_roleprivs {
                   3859:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3860:     my $access = 1;
                   3861:     my $now = time;
                   3862:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3863:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3864:     if ($access) {
1.811     albertel 3865:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3866:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3867:     }
                   3868: }
1.567     raeburn  3869: 
                   3870: sub standard_roleprivs {
                   3871:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3872:     if (defined($pr{$trole.':s'})) {
                   3873:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3874:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3875:     }
                   3876:     if ($tdomain ne '') {
                   3877:         if (defined($pr{$trole.':d'})) {
                   3878:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3879:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3880:         }
                   3881:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3882:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3883:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3884:         }
                   3885:     }
                   3886: }
                   3887: 
                   3888: sub set_userprivs {
1.678     raeburn  3889:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3890:     my $author=0;
                   3891:     my $adv=0;
1.678     raeburn  3892:     my %grouproles = ();
                   3893:     if (keys(%{$allgroups}) > 0) {
1.1000    raeburn  3894:         foreach my $role (keys(%{$allroles})) {
1.681     raeburn  3895:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3896:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3897:                 $trole = $1;
                   3898:                 $area = $2;
1.681     raeburn  3899:                 $sec = $3;
                   3900:                 $extendedarea = $area.$sec;
                   3901:                 if (exists($$allgroups{$area})) {
                   3902:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3903:                         my $spec = $trole.'.'.$extendedarea;
                   3904:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3905:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3906:                     }
                   3907:                 }
                   3908:             }
                   3909:         }
                   3910:     }
1.800     albertel 3911:     foreach my $group (keys(%grouproles)) {
                   3912:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3913:     }
1.800     albertel 3914:     foreach my $role (keys(%{$allroles})) {
                   3915:         my %thesepriv;
1.941     raeburn  3916:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3917:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3918:             if ($item ne '') {
                   3919:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3920:                 if ($restrictions eq '') {
                   3921:                     $thesepriv{$privilege}='F';
                   3922:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3923:                     $thesepriv{$privilege}.=$restrictions;
                   3924:                 }
                   3925:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3926:             }
                   3927:         }
                   3928:         my $thesestr='';
1.800     albertel 3929:         foreach my $priv (keys(%thesepriv)) {
                   3930: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3931: 	}
                   3932:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3933:     }
                   3934:     return ($author,$adv);
                   3935: }
                   3936: 
1.994     raeburn  3937: sub role_status {
1.1002    raeburn  3938:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  3939:     my @pwhere = ();
                   3940:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   3941:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   3942:         unless (!defined($$role) || $$role eq '') {
                   3943:             $$where=join('.',@pwhere);
                   3944:             $$trolecode=$$role.'.'.$$where;
                   3945:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   3946:             $$tstatus='is';
                   3947:             if ($$tstart && $$tstart>$then) {
                   3948:                 $$tstatus='future';
1.1002    raeburn  3949:                 if ($$tstart && $$tstart>$refresh) {
                   3950:                     if ($$tstart<$now) {
                   3951:                         if (($$where ne '') && ($$role ne '')) {
                   3952:                             my (%allroles,%allgroups,$group_privs);
                   3953:                             my %userroles = (
                   3954:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   3955:                             );
                   3956:                             my $spec=$$role.'.'.$$where;
                   3957:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   3958:                             if ($$role eq 'gr') {
                   3959:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   3960:                                                     $env{'user.name'})=@_;
                   3961:                                 my ($trole) = split('_',$role,1);
                   3962:                                 (undef,my $group_privs) = split(/\//,$trole);
                   3963:                                 $group_privs = &unescape($group_privs);
                   3964:                             }
                   3965:                             if ($$role =~ /^cr\//) {
                   3966:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
                   3967:                             } elsif ($$role eq 'gr') {
                   3968:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   3969:                                                     $env{'user.name'});
                   3970:                                 my $trole = split('_',$rolehash{$$where.'_'.$$role},1);
                   3971:                                 (undef,my $group_privs) = split(/\//,$trole);
                   3972:                                 $group_privs = &unescape($group_privs);
                   3973:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
                   3974:                             } else {
                   3975:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   3976:                             }
                   3977:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3978:                             &appenv(\%userroles,[$$role,'cm']);
                   3979:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   3980:                             $$tstatus = 'is';
                   3981:                         }
                   3982:                     }
                   3983:                 }
1.994     raeburn  3984:             }
                   3985:             if ($$tend) {
                   3986:                 if ($$tend<$then) {
                   3987:                     $$tstatus='expired';
                   3988:                 } elsif ($$tend<$now) {
                   3989:                     $$tstatus='will_not';
                   3990:                 }
                   3991:             }
                   3992:         }
                   3993:     }
                   3994: }
                   3995: 
                   3996: sub check_adhoc_privs {
1.1002    raeburn  3997:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
1.994     raeburn  3998:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   3999:     if ($env{$cckey}) {
                   4000:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002    raeburn  4001:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4002:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
                   4003:             &set_adhoc_privileges($cdom,$cnum,$checkrole);
                   4004:         }
                   4005:     } else {
                   4006:         &set_adhoc_privileges($cdom,$cnum,$checkrole);
                   4007:     }
                   4008: }
                   4009: 
                   4010: sub set_adhoc_privileges {
                   4011: # role can be cc or ca
                   4012:     my ($dcdom,$pickedcourse,$role) = @_;
                   4013:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4014:     my $spec = $role.'.'.$area;
                   4015:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4016:                                   $env{'user.name'});
                   4017:     my %ccrole = ();
                   4018:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4019:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4020:     &appenv(\%userroles,[$role,'cm']);
                   4021:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4022:     &appenv( {'request.role'        => $spec,
                   4023:               'request.role.domain' => $dcdom,
                   4024:               'request.course.sec'  => ''
                   4025:              }
                   4026:            );
                   4027:     my $tadv=0;
                   4028:     if (&allowed('adv') eq 'F') { $tadv=1; }
                   4029:     &appenv({'request.role.adv'    => $tadv});
                   4030: }
                   4031: 
1.12      www      4032: # --------------------------------------------------------------- get interface
                   4033: 
                   4034: sub get {
1.131     albertel 4035:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4036:    my $items='';
1.800     albertel 4037:    foreach my $item (@$storearr) {
                   4038:        $items.=&escape($item).'&';
1.191     harris41 4039:    }
1.12      www      4040:    $items=~s/\&$//;
1.620     albertel 4041:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4042:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4043:    my $uhome=&homeserver($uname,$udomain);
                   4044: 
1.133     albertel 4045:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4046:    my @pairs=split(/\&/,$rep);
1.273     albertel 4047:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4048:      return @pairs;
                   4049:    }
1.15      www      4050:    my %returnhash=();
1.42      www      4051:    my $i=0;
1.800     albertel 4052:    foreach my $item (@$storearr) {
                   4053:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4054:       $i++;
1.191     harris41 4055:    }
1.15      www      4056:    return %returnhash;
1.27      www      4057: }
                   4058: 
                   4059: # --------------------------------------------------------------- del interface
                   4060: 
                   4061: sub del {
1.133     albertel 4062:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4063:    my $items='';
1.800     albertel 4064:    foreach my $item (@$storearr) {
                   4065:        $items.=&escape($item).'&';
1.191     harris41 4066:    }
1.984     neumanie 4067: 
1.27      www      4068:    $items=~s/\&$//;
1.620     albertel 4069:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4070:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4071:    my $uhome=&homeserver($uname,$udomain);
                   4072:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4073: }
                   4074: 
                   4075: # -------------------------------------------------------------- dump interface
                   4076: 
                   4077: sub dump {
1.755     albertel 4078:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   4079:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4080:     if (!$uname) { $uname=$env{'user.name'}; }
                   4081:     my $uhome=&homeserver($uname,$udomain);
                   4082:     if ($regexp) {
                   4083: 	$regexp=&escape($regexp);
                   4084:     } else {
                   4085: 	$regexp='.';
                   4086:     }
                   4087:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4088:     my @pairs=split(/\&/,$rep);
                   4089:     my %returnhash=();
                   4090:     foreach my $item (@pairs) {
                   4091: 	my ($key,$value)=split(/=/,$item,2);
                   4092: 	$key = &unescape($key);
                   4093: 	next if ($key =~ /^error: 2 /);
                   4094: 	$returnhash{$key}=&thaw_unescape($value);
                   4095:     }
                   4096:     return %returnhash;
1.407     www      4097: }
                   4098: 
1.717     albertel 4099: # --------------------------------------------------------- dumpstore interface
                   4100: 
                   4101: sub dumpstore {
                   4102:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4103:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4104:    if (!$uname) { $uname=$env{'user.name'}; }
                   4105:    my $uhome=&homeserver($uname,$udomain);
                   4106:    if ($regexp) {
                   4107:        $regexp=&escape($regexp);
                   4108:    } else {
                   4109:        $regexp='.';
                   4110:    }
                   4111:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4112:    my @pairs=split(/\&/,$rep);
                   4113:    my %returnhash=();
                   4114:    foreach my $item (@pairs) {
                   4115:        my ($key,$value)=split(/=/,$item,2);
                   4116:        next if ($key =~ /^error: 2 /);
                   4117:        $returnhash{$key}=&thaw_unescape($value);
                   4118:    }
                   4119:    return %returnhash;
1.717     albertel 4120: }
                   4121: 
1.407     www      4122: # -------------------------------------------------------------- keys interface
                   4123: 
                   4124: sub getkeys {
                   4125:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4126:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4127:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4128:    my $uhome=&homeserver($uname,$udomain);
                   4129:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4130:    my @keyarray=();
1.800     albertel 4131:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4132:       next if ($key =~ /^error: 2 /);
1.800     albertel 4133:       push(@keyarray,&unescape($key));
1.407     www      4134:    }
                   4135:    return @keyarray;
1.318     matthew  4136: }
                   4137: 
1.319     matthew  4138: # --------------------------------------------------------------- currentdump
                   4139: sub currentdump {
1.328     matthew  4140:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4141:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4142:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4143:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4144:    my $uhome = &homeserver($sname,$sdom);
                   4145:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4146:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4147:    #
1.318     matthew  4148:    my %returnhash=();
1.319     matthew  4149:    #
                   4150:    if ($rep eq "unknown_cmd") { 
                   4151:        # an old lond will not know currentdump
                   4152:        # Do a dump and make it look like a currentdump
1.822     albertel 4153:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4154:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4155:        my %hash = @tmp;
                   4156:        @tmp=();
1.424     matthew  4157:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4158:    } else {
                   4159:        my @pairs=split(/\&/,$rep);
1.800     albertel 4160:        foreach my $pair (@pairs) {
                   4161:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4162:            my ($symb,$param) = split(/:/,$key);
                   4163:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4164:                                                         &thaw_unescape($value);
1.319     matthew  4165:        }
1.191     harris41 4166:    }
1.12      www      4167:    return %returnhash;
1.424     matthew  4168: }
                   4169: 
                   4170: sub convert_dump_to_currentdump{
                   4171:     my %hash = %{shift()};
                   4172:     my %returnhash;
                   4173:     # Code ripped from lond, essentially.  The only difference
                   4174:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4175:     # we might run in to problems with parameter names =~ /^v\./
                   4176:     while (my ($key,$value) = each(%hash)) {
                   4177:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4178: 	$symb  = &unescape($symb);
                   4179: 	$param = &unescape($param);
1.424     matthew  4180:         next if ($v eq 'version' || $symb eq 'keys');
                   4181:         next if (exists($returnhash{$symb}) &&
                   4182:                  exists($returnhash{$symb}->{$param}) &&
                   4183:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4184:         $returnhash{$symb}->{$param}=$value;
                   4185:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4186:     }
                   4187:     #
                   4188:     # Remove all of the keys in the hashes which keep track of
                   4189:     # the version of the parameter.
                   4190:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4191:         # use a foreach because we are going to delete from the hash.
                   4192:         foreach my $key (keys(%$param_hash)) {
                   4193:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4194:         }
                   4195:     }
                   4196:     return \%returnhash;
1.12      www      4197: }
                   4198: 
1.627     albertel 4199: # ------------------------------------------------------ critical inc interface
                   4200: 
                   4201: sub cinc {
                   4202:     return &inc(@_,'critical');
                   4203: }
                   4204: 
1.449     matthew  4205: # --------------------------------------------------------------- inc interface
                   4206: 
                   4207: sub inc {
1.627     albertel 4208:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4209:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4210:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4211:     my $uhome=&homeserver($uname,$udomain);
                   4212:     my $items='';
                   4213:     if (! ref($store)) {
                   4214:         # got a single value, so use that instead
                   4215:         $items = &escape($store).'=&';
                   4216:     } elsif (ref($store) eq 'SCALAR') {
                   4217:         $items = &escape($$store).'=&';        
                   4218:     } elsif (ref($store) eq 'ARRAY') {
                   4219:         $items = join('=&',map {&escape($_);} @{$store});
                   4220:     } elsif (ref($store) eq 'HASH') {
                   4221:         while (my($key,$value) = each(%{$store})) {
                   4222:             $items.= &escape($key).'='.&escape($value).'&';
                   4223:         }
                   4224:     }
                   4225:     $items=~s/\&$//;
1.627     albertel 4226:     if ($critical) {
                   4227: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4228:     } else {
                   4229: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4230:     }
1.449     matthew  4231: }
                   4232: 
1.12      www      4233: # --------------------------------------------------------------- put interface
                   4234: 
                   4235: sub put {
1.134     albertel 4236:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4237:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4238:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4239:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4240:    my $items='';
1.800     albertel 4241:    foreach my $item (keys(%$storehash)) {
                   4242:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4243:    }
1.12      www      4244:    $items=~s/\&$//;
1.134     albertel 4245:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4246: }
                   4247: 
1.631     albertel 4248: # ------------------------------------------------------------ newput interface
                   4249: 
                   4250: sub newput {
                   4251:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4252:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4253:    if (!$uname) { $uname=$env{'user.name'}; }
                   4254:    my $uhome=&homeserver($uname,$udomain);
                   4255:    my $items='';
                   4256:    foreach my $key (keys(%$storehash)) {
                   4257:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4258:    }
                   4259:    $items=~s/\&$//;
                   4260:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4261: }
                   4262: 
                   4263: # ---------------------------------------------------------  putstore interface
                   4264: 
1.524     raeburn  4265: sub putstore {
1.715     albertel 4266:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4267:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4268:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4269:    my $uhome=&homeserver($uname,$udomain);
                   4270:    my $items='';
1.715     albertel 4271:    foreach my $key (keys(%$storehash)) {
                   4272:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4273:    }
1.715     albertel 4274:    $items=~s/\&$//;
1.716     albertel 4275:    my $esc_symb=&escape($symb);
                   4276:    my $esc_v=&escape($version);
1.715     albertel 4277:    my $reply =
1.716     albertel 4278:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4279: 	      $uhome);
                   4280:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4281:        # gfall back to way things use to be done
1.715     albertel 4282:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4283: 			    $uname);
1.524     raeburn  4284:    }
1.715     albertel 4285:    return $reply;
                   4286: }
                   4287: 
                   4288: sub old_putstore {
1.716     albertel 4289:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4290:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4291:     if (!$uname) { $uname=$env{'user.name'}; }
                   4292:     my $uhome=&homeserver($uname,$udomain);
                   4293:     my %newstorehash;
1.800     albertel 4294:     foreach my $item (keys(%$storehash)) {
                   4295: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4296: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4297:     }
                   4298:     my $items='';
                   4299:     my %allitems = ();
1.800     albertel 4300:     foreach my $item (keys(%newstorehash)) {
                   4301: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4302: 	    my $key = $1.':keys:'.$2;
                   4303: 	    $allitems{$key} .= $3.':';
                   4304: 	}
1.800     albertel 4305: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4306:     }
1.800     albertel 4307:     foreach my $item (keys(%allitems)) {
                   4308: 	$allitems{$item} =~ s/\:$//;
                   4309: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4310:     }
                   4311:     $items=~s/\&$//;
                   4312:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4313: }
                   4314: 
1.47      www      4315: # ------------------------------------------------------ critical put interface
                   4316: 
                   4317: sub cput {
1.134     albertel 4318:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4319:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4320:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4321:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4322:    my $items='';
1.800     albertel 4323:    foreach my $item (keys(%$storehash)) {
                   4324:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4325:    }
1.47      www      4326:    $items=~s/\&$//;
1.134     albertel 4327:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4328: }
                   4329: 
                   4330: # -------------------------------------------------------------- eget interface
                   4331: 
                   4332: sub eget {
1.133     albertel 4333:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4334:    my $items='';
1.800     albertel 4335:    foreach my $item (@$storearr) {
                   4336:        $items.=&escape($item).'&';
1.191     harris41 4337:    }
1.12      www      4338:    $items=~s/\&$//;
1.620     albertel 4339:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4340:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4341:    my $uhome=&homeserver($uname,$udomain);
                   4342:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4343:    my @pairs=split(/\&/,$rep);
                   4344:    my %returnhash=();
1.42      www      4345:    my $i=0;
1.800     albertel 4346:    foreach my $item (@$storearr) {
                   4347:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4348:       $i++;
1.191     harris41 4349:    }
1.12      www      4350:    return %returnhash;
                   4351: }
                   4352: 
1.667     albertel 4353: # ------------------------------------------------------------ tmpput interface
                   4354: sub tmpput {
1.802     raeburn  4355:     my ($storehash,$server,$context)=@_;
1.667     albertel 4356:     my $items='';
1.800     albertel 4357:     foreach my $item (keys(%$storehash)) {
                   4358: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4359:     }
                   4360:     $items=~s/\&$//;
1.802     raeburn  4361:     if (defined($context)) {
                   4362:         $items .= ':'.&escape($context);
                   4363:     }
1.667     albertel 4364:     return &reply("tmpput:$items",$server);
                   4365: }
                   4366: 
                   4367: # ------------------------------------------------------------ tmpget interface
                   4368: sub tmpget {
1.688     albertel 4369:     my ($token,$server)=@_;
                   4370:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4371:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4372:     my %returnhash;
                   4373:     foreach my $item (split(/\&/,$rep)) {
                   4374: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4375:         next if ($key =~ /^error: 2 /);
1.667     albertel 4376: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4377:     }
                   4378:     return %returnhash;
                   4379: }
                   4380: 
1.688     albertel 4381: # ------------------------------------------------------------ tmpget interface
                   4382: sub tmpdel {
                   4383:     my ($token,$server)=@_;
                   4384:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4385:     return &reply("tmpdel:$token",$server);
                   4386: }
                   4387: 
1.765     albertel 4388: # -------------------------------------------------- portfolio access checking
                   4389: 
                   4390: sub portfolio_access {
1.766     albertel 4391:     my ($requrl) = @_;
1.765     albertel 4392:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4393:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4394:     if ($result) {
                   4395:         my %setters;
                   4396:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4397:             my ($startblock,$endblock) =
                   4398:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4399:             if ($startblock && $endblock) {
                   4400:                 return 'B';
                   4401:             }
                   4402:         } else {
                   4403:             my ($startblock,$endblock) =
                   4404:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4405:             if ($startblock && $endblock) {
                   4406:                 return 'B';
                   4407:             }
                   4408:         }
                   4409:     }
1.765     albertel 4410:     if ($result eq 'ok') {
1.766     albertel 4411:        return 'F';
1.765     albertel 4412:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4413:        return 'A';
1.765     albertel 4414:     }
1.766     albertel 4415:     return '';
1.765     albertel 4416: }
                   4417: 
                   4418: sub get_portfolio_access {
1.767     albertel 4419:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4420: 
                   4421:     if (!ref($access_hash)) {
                   4422: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4423: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4424: 						   $file_name);
                   4425: 	$access_hash = $access_controls{$file_name};
                   4426:     }
                   4427: 
1.765     albertel 4428:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4429:     my $now = time;
                   4430:     if (ref($access_hash) eq 'HASH') {
                   4431:         foreach my $key (keys(%{$access_hash})) {
                   4432:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4433:             if ($start > $now) {
                   4434:                 next;
                   4435:             }
                   4436:             if ($end && $end<$now) {
                   4437:                 next;
                   4438:             }
                   4439:             if ($scope eq 'public') {
                   4440:                 $public = $key;
                   4441:                 last;
                   4442:             } elsif ($scope eq 'guest') {
                   4443:                 $guest = $key;
                   4444:             } elsif ($scope eq 'domains') {
                   4445:                 push(@domains,$key);
                   4446:             } elsif ($scope eq 'users') {
                   4447:                 push(@users,$key);
                   4448:             } elsif ($scope eq 'course') {
                   4449:                 push(@courses,$key);
                   4450:             } elsif ($scope eq 'group') {
                   4451:                 push(@groups,$key);
                   4452:             }
                   4453:         }
                   4454:         if ($public) {
                   4455:             return 'ok';
                   4456:         }
                   4457:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4458:             if ($guest) {
                   4459:                 return $guest;
                   4460:             }
                   4461:         } else {
                   4462:             if (@domains > 0) {
                   4463:                 foreach my $domkey (@domains) {
                   4464:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4465:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4466:                             return 'ok';
                   4467:                         }
                   4468:                     }
                   4469:                 }
                   4470:             }
                   4471:             if (@users > 0) {
                   4472:                 foreach my $userkey (@users) {
1.865     raeburn  4473:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4474:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4475:                             if (ref($item) eq 'HASH') {
                   4476:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4477:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4478:                                     return 'ok';
                   4479:                                 }
                   4480:                             }
                   4481:                         }
                   4482:                     } 
1.765     albertel 4483:                 }
                   4484:             }
                   4485:             my %roleshash;
                   4486:             my @courses_and_groups = @courses;
                   4487:             push(@courses_and_groups,@groups); 
                   4488:             if (@courses_and_groups > 0) {
                   4489:                 my (%allgroups,%allroles); 
                   4490:                 my ($start,$end,$role,$sec,$group);
                   4491:                 foreach my $envkey (%env) {
1.811     albertel 4492:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4493:                         my $cid = $2.'_'.$3; 
                   4494:                         if ($1 eq 'gr') {
                   4495:                             $group = $4;
                   4496:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4497:                         } else {
                   4498:                             if ($4 eq '') {
                   4499:                                 $sec = 'none';
                   4500:                             } else {
                   4501:                                 $sec = $4;
                   4502:                             }
                   4503:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4504:                         }
1.811     albertel 4505:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4506:                         my $cid = $2.'_'.$3;
                   4507:                         if ($4 eq '') {
                   4508:                             $sec = 'none';
                   4509:                         } else {
                   4510:                             $sec = $4;
                   4511:                         }
                   4512:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4513:                     }
                   4514:                 }
                   4515:                 if (keys(%allroles) == 0) {
                   4516:                     return;
                   4517:                 }
                   4518:                 foreach my $key (@courses_and_groups) {
                   4519:                     my %content = %{$$access_hash{$key}};
                   4520:                     my $cnum = $content{'number'};
                   4521:                     my $cdom = $content{'domain'};
                   4522:                     my $cid = $cdom.'_'.$cnum;
                   4523:                     if (!exists($allroles{$cid})) {
                   4524:                         next;
                   4525:                     }    
                   4526:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4527:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4528:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4529:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4530:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4531:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4532:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4533:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4534:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4535:                                         if (grep/^all$/,@sections) {
                   4536:                                             return 'ok';
                   4537:                                         } else {
                   4538:                                             if (grep/^$sec$/,@sections) {
                   4539:                                                 return 'ok';
                   4540:                                             }
                   4541:                                         }
                   4542:                                     }
                   4543:                                 }
                   4544:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4545:                                     if (grep/^none$/,@groups) {
                   4546:                                         return 'ok';
                   4547:                                     }
                   4548:                                 } else {
                   4549:                                     if (grep/^all$/,@groups) {
                   4550:                                         return 'ok';
                   4551:                                     } 
                   4552:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4553:                                         if (grep/^$group$/,@groups) {
                   4554:                                             return 'ok';
                   4555:                                         }
                   4556:                                     }
                   4557:                                 } 
                   4558:                             }
                   4559:                         }
                   4560:                     }
                   4561:                 }
                   4562:             }
                   4563:             if ($guest) {
                   4564:                 return $guest;
                   4565:             }
                   4566:         }
                   4567:     }
                   4568:     return;
                   4569: }
                   4570: 
                   4571: sub course_group_datechecker {
                   4572:     my ($dates,$now,$status) = @_;
                   4573:     my ($start,$end) = split(/\./,$dates);
                   4574:     if (!$start && !$end) {
                   4575:         return 'ok';
                   4576:     }
                   4577:     if (grep/^active$/,@{$status}) {
                   4578:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4579:             return 'ok';
                   4580:         }
                   4581:     }
                   4582:     if (grep/^previous$/,@{$status}) {
                   4583:         if ($end > $now ) {
                   4584:             return 'ok';
                   4585:         }
                   4586:     }
                   4587:     if (grep/^future$/,@{$status}) {
                   4588:         if ($start > $now) {
                   4589:             return 'ok';
                   4590:         }
                   4591:     }
                   4592:     return; 
                   4593: }
                   4594: 
                   4595: sub parse_portfolio_url {
                   4596:     my ($url) = @_;
                   4597: 
                   4598:     my ($type,$udom,$unum,$group,$file_name);
                   4599:     
1.823     albertel 4600:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4601: 	$type = 1;
                   4602:         $udom = $1;
                   4603:         $unum = $2;
                   4604:         $file_name = $3;
1.823     albertel 4605:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4606: 	$type = 2;
                   4607:         $udom = $1;
                   4608:         $unum = $2;
                   4609:         $group = $3;
                   4610:         $file_name = $3.'/'.$4;
                   4611:     }
                   4612:     if (wantarray) {
                   4613: 	return ($type,$udom,$unum,$file_name,$group);
                   4614:     }
                   4615:     return $type;
                   4616: }
                   4617: 
                   4618: sub is_portfolio_url {
                   4619:     my ($url) = @_;
                   4620:     return scalar(&parse_portfolio_url($url));
                   4621: }
                   4622: 
1.798     raeburn  4623: sub is_portfolio_file {
                   4624:     my ($file) = @_;
1.820     raeburn  4625:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4626:         return 1;
                   4627:     }
                   4628:     return;
                   4629: }
                   4630: 
1.976     raeburn  4631: sub usertools_access {
1.985     raeburn  4632:     my ($uname,$udom,$tool,$action,$context) = @_;
                   4633:     my ($access,%tools);
                   4634:     if ($context eq '') {
                   4635:         $context = 'tools';
                   4636:     }
                   4637:     if ($context eq 'requestcourses') {
                   4638:         %tools = (
                   4639:                       official   => 1,
                   4640:                       unofficial => 1,
1.1006    raeburn  4641:                       community  => 1,
1.985     raeburn  4642:                  );
                   4643:     } else {
                   4644:         %tools = (
                   4645:                       aboutme   => 1,
                   4646:                       blog      => 1,
                   4647:                       portfolio => 1,
                   4648:                  );
                   4649:     }
1.976     raeburn  4650:     return if (!defined($tools{$tool}));
                   4651: 
                   4652:     if ((!defined($udom)) || (!defined($uname))) {
                   4653:         $udom = $env{'user.domain'};
                   4654:         $uname = $env{'user.name'};
                   4655:     }
                   4656: 
1.978     raeburn  4657:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4658:         if ($action ne 'reload') {
1.985     raeburn  4659:             if ($context eq 'requestcourses') {
                   4660:                 return $env{'environment.canrequest.'.$tool};
                   4661:             } else {
                   4662:                 return $env{'environment.availabletools.'.$tool};
                   4663:             }
                   4664:         }
1.976     raeburn  4665:     }
                   4666: 
                   4667:     my ($toolstatus,$inststatus);
                   4668: 
1.985     raeburn  4669:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   4670:          ($action ne 'reload')) {
                   4671:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  4672:         $inststatus = $env{'environment.inststatus'};
                   4673:     } else {
1.985     raeburn  4674:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool);
                   4675:         $toolstatus = $userenv{$context.'.'.$tool};
1.976     raeburn  4676:         $inststatus = $userenv{'inststatus'};
                   4677:     }
                   4678: 
                   4679:     if ($toolstatus ne '') {
                   4680:         if ($toolstatus) {
                   4681:             $access = 1;
                   4682:         } else {
                   4683:             $access = 0;
                   4684:         }
                   4685:         return $access;
                   4686:     }
                   4687: 
                   4688:     my $is_adv = &is_advanced_user($udom,$uname);
                   4689:     my %domdef = &get_domain_defaults($udom);
                   4690:     if (ref($domdef{$tool}) eq 'HASH') {
                   4691:         if ($is_adv) {
                   4692:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   4693:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   4694:                     $access = 1;
                   4695:                 } else {
                   4696:                     $access = 0;
                   4697:                 }
                   4698:                 return $access;
                   4699:             }
                   4700:         }
                   4701:         if ($inststatus ne '') {
                   4702:             my ($hasaccess,$hasnoaccess);
                   4703:             foreach my $affiliation (split(/:/,$inststatus)) {
                   4704:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   4705:                     if ($domdef{$tool}{$affiliation}) {
                   4706:                         $hasaccess = 1;
                   4707:                     } else {
                   4708:                         $hasnoaccess = 1;
                   4709:                     }
                   4710:                 }
                   4711:             }
                   4712:             if ($hasaccess || $hasnoaccess) {
                   4713:                 if ($hasaccess) {
                   4714:                     $access = 1;
                   4715:                 } elsif ($hasnoaccess) {
                   4716:                     $access = 0; 
                   4717:                 }
                   4718:                 return $access;
                   4719:             }
                   4720:         } else {
                   4721:             if ($domdef{$tool}{'default'} ne '') {
                   4722:                 if ($domdef{$tool}{'default'}) {
                   4723:                     $access = 1;
                   4724:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   4725:                     $access = 0;
                   4726:                 }
                   4727:                 return $access;
                   4728:             }
                   4729:         }
                   4730:     } else {
1.985     raeburn  4731:         if ($context eq 'tools') {
                   4732:             $access = 1;
                   4733:         } else {
                   4734:             $access = 0;
                   4735:         }
1.976     raeburn  4736:         return $access;
                   4737:     }
                   4738: }
                   4739: 
                   4740: sub is_advanced_user {
                   4741:     my ($udom,$uname) = @_;
                   4742:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   4743:     my %allroles;
                   4744:     my $is_adv;
                   4745:     foreach my $role (keys(%roleshash)) {
                   4746:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   4747:         my $area = '/'.$tdomain.'/'.$trest;
                   4748:         if ($sec ne '') {
                   4749:             $area .= '/'.$sec;
                   4750:         }
                   4751:         if (($area ne '') && ($trole ne '')) {
                   4752:             my $spec=$trole.'.'.$area;
                   4753:             if ($trole =~ /^cr\//) {
                   4754:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4755:             } elsif ($trole ne 'gr') {
                   4756:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4757:             }
                   4758:         }
                   4759:     }
                   4760:     foreach my $role (keys(%allroles)) {
                   4761:         last if ($is_adv);
                   4762:         foreach my $item (split(/:/,$allroles{$role})) {
                   4763:             if ($item ne '') {
                   4764:                 my ($privilege,$restrictions)=split(/&/,$item);
                   4765:                 if ($privilege eq 'adv') {
                   4766:                     $is_adv = 1;
                   4767:                     last;
                   4768:                 }
                   4769:             }
                   4770:         }
                   4771:     }
                   4772:     return $is_adv;
                   4773: }
1.798     raeburn  4774: 
1.341     www      4775: # ---------------------------------------------- Custom access rule evaluation
                   4776: 
                   4777: sub customaccess {
                   4778:     my ($priv,$uri)=@_;
1.807     albertel 4779:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4780:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4781:     $udom = &LONCAPA::clean_domain($udom);
                   4782:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4783:     my $access=0;
1.800     albertel 4784:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4785: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4786: 	if ($type eq 'user') {
                   4787: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4788: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4789: 		if ($tdom) {
                   4790: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4791: 		}
1.896     albertel 4792: 		if ($tuname) {
                   4793: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4794: 		}
                   4795: 		$access=($effect eq 'allow');
                   4796: 		last;
                   4797: 	    }
                   4798: 	} else {
                   4799: 	    if ($role) {
                   4800: 		if ($role ne $urole) { next; }
                   4801: 	    }
                   4802: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4803: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4804: 		if ($tdom) {
                   4805: 		    if ($tdom ne $udom) { next; }
                   4806: 		}
                   4807: 		if ($tcrs) {
                   4808: 		    if ($tcrs ne $ucrs) { next; }
                   4809: 		}
                   4810: 		if ($tsec) {
                   4811: 		    if ($tsec ne $usec) { next; }
                   4812: 		}
                   4813: 		$access=($effect eq 'allow');
                   4814: 		last;
                   4815: 	    }
                   4816: 	    if ($realm eq '' && $role eq '') {
                   4817: 		$access=($effect eq 'allow');
                   4818: 	    }
1.402     bowersj2 4819: 	}
1.341     www      4820:     }
                   4821:     return $access;
                   4822: }
                   4823: 
1.103     harris41 4824: # ------------------------------------------------- Check for a user privilege
1.12      www      4825: 
                   4826: sub allowed {
1.810     raeburn  4827:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4828:     my $ver_orguri=$uri;
1.439     www      4829:     $uri=&deversion($uri);
1.152     www      4830:     my $orguri=$uri;
1.52      www      4831:     $uri=&declutter($uri);
1.809     raeburn  4832: 
1.810     raeburn  4833:     if ($priv eq 'evb') {
                   4834: # Evade communication block restrictions for specified role in a course
                   4835:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4836:             return $1;
                   4837:         } else {
                   4838:             return;
                   4839:         }
                   4840:     }
                   4841: 
1.620     albertel 4842:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4843: # Free bre access to adm and meta resources
1.775     albertel 4844:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4845: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4846: 	&& ($priv eq 'bre')) {
1.14      www      4847: 	return 'F';
1.159     www      4848:     }
                   4849: 
1.545     banghart 4850: # Free bre access to user's own portfolio contents
1.714     raeburn  4851:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4852:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4853: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4854:         my %setters;
                   4855:         my ($startblock,$endblock) = 
                   4856:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4857:         if ($startblock && $endblock) {
                   4858:             return 'B';
                   4859:         } else {
                   4860:             return 'F';
                   4861:         }
1.545     banghart 4862:     }
                   4863: 
1.762     raeburn  4864: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4865:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4866:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4867:         if (exists($env{'request.course.id'})) {
                   4868:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4869:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4870:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4871:                 my $courseprivid=$env{'request.course.id'};
                   4872:                 $courseprivid=~s/\_/\//;
                   4873:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4874:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4875:                     return $1; 
1.762     raeburn  4876:                 } else {
                   4877:                     if ($env{'request.course.sec'}) {
                   4878:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4879:                     }
                   4880:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4881:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4882:                         return $2;
                   4883:                     }
1.714     raeburn  4884:                 }
                   4885:             }
                   4886:         }
                   4887:     }
                   4888: 
1.159     www      4889: # Free bre to public access
                   4890: 
                   4891:     if ($priv eq 'bre') {
1.238     www      4892:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4893: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4894:            return 'F'; 
                   4895:         }
1.238     www      4896:         if ($copyright eq 'priv') {
                   4897:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4898: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4899: 		return '';
                   4900:             }
                   4901:         }
                   4902:         if ($copyright eq 'domain') {
                   4903:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4904: 	    unless (($env{'user.domain'} eq $1) ||
                   4905:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4906: 		return '';
                   4907:             }
1.262     matthew  4908:         }
1.620     albertel 4909:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4910:             # Library role, so allow browsing of resources in this domain.
                   4911:             return 'F';
1.238     www      4912:         }
1.341     www      4913:         if ($copyright eq 'custom') {
                   4914: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4915:         }
1.14      www      4916:     }
1.264     matthew  4917:     # Domain coordinator is trying to create a course
1.620     albertel 4918:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4919:         # uri is the requested domain in this case.
                   4920:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4921:         # a role of dc for the domain in question.
1.620     albertel 4922:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4923:     }
1.29      www      4924: 
1.52      www      4925:     my $thisallowed='';
                   4926:     my $statecond=0;
                   4927:     my $courseprivid='';
                   4928: 
                   4929: # Course
                   4930: 
1.620     albertel 4931:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4932:        $thisallowed.=$1;
                   4933:     }
1.29      www      4934: 
1.52      www      4935: # Domain
                   4936: 
1.620     albertel 4937:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4938:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4939:        $thisallowed.=$1;
                   4940:     }
1.52      www      4941: 
                   4942: # Course: uri itself is a course
1.66      www      4943:     my $courseuri=$uri;
                   4944:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4945:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4946: 
1.620     albertel 4947:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4948:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4949:        $thisallowed.=$1;
                   4950:     }
1.29      www      4951: 
1.665     albertel 4952: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4953: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4954:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4955: 	$thisallowed='';
1.671     raeburn  4956:         my ($match)=&is_on_map($uri);
                   4957:         if ($match) {
                   4958:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4959:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4960:                 $thisallowed.=$1;
                   4961:             }
                   4962:         } else {
1.705     albertel 4963:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4964:             if ($refuri) {
                   4965:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4966:                     $thisallowed='F';
1.671     raeburn  4967:                 } else {
                   4968:                     $refuri=&declutter($refuri);
                   4969:                     my ($match) = &is_on_map($refuri);
                   4970:                     if ($match) {
                   4971:                         $thisallowed='F';
                   4972:                     }
1.669     raeburn  4973:                 }
1.671     raeburn  4974:             }
                   4975:         }
1.314     www      4976:     }
1.492     albertel 4977: 
1.766     albertel 4978:     if ($priv eq 'bre'
                   4979: 	&& $thisallowed ne 'F' 
                   4980: 	&& $thisallowed ne '2'
                   4981: 	&& &is_portfolio_url($uri)) {
                   4982: 	$thisallowed = &portfolio_access($uri);
                   4983:     }
                   4984:     
1.52      www      4985: # Full access at system, domain or course-wide level? Exit.
1.29      www      4986:     if ($thisallowed=~/F/) {
                   4987: 	return 'F';
                   4988:     }
                   4989: 
1.52      www      4990: # If this is generating or modifying users, exit with special codes
1.29      www      4991: 
1.643     www      4992:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4993: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4994: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4995: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4996: 	    unless ($auname) { return $thisallowed; }
                   4997: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4998: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4999: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5000: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5001: 	}
1.52      www      5002: 	return $thisallowed;
                   5003:     }
                   5004: #
1.103     harris41 5005: # Gathered so far: system, domain and course wide privileges
1.52      www      5006: #
                   5007: # Course: See if uri or referer is an individual resource that is part of 
                   5008: # the course
                   5009: 
1.620     albertel 5010:     if ($env{'request.course.id'}) {
1.232     www      5011: 
1.620     albertel 5012:        $courseprivid=$env{'request.course.id'};
                   5013:        if ($env{'request.course.sec'}) {
                   5014:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5015:        }
                   5016:        $courseprivid=~s/\_/\//;
                   5017:        my $checkreferer=1;
1.232     www      5018:        my ($match,$cond)=&is_on_map($uri);
                   5019:        if ($match) {
                   5020:            $statecond=$cond;
1.620     albertel 5021:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5022:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5023:                $thisallowed.=$1;
                   5024:                $checkreferer=0;
                   5025:            }
1.29      www      5026:        }
1.83      www      5027:        
1.148     www      5028:        if ($checkreferer) {
1.620     albertel 5029: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5030:             unless ($refuri) {
1.800     albertel 5031:                 foreach my $key (keys(%env)) {
                   5032: 		    if ($key=~/^httpref\..*\*/) {
                   5033: 			my $pattern=$key;
1.156     www      5034:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5035:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5036:                         $pattern=~s/\//\\\//g;
1.152     www      5037:                         if ($orguri=~/$pattern/) {
1.800     albertel 5038: 			    $refuri=$env{$key};
1.148     www      5039:                         }
                   5040:                     }
1.191     harris41 5041:                 }
1.148     www      5042:             }
1.232     www      5043: 
1.148     www      5044:          if ($refuri) { 
1.152     www      5045: 	  $refuri=&declutter($refuri);
1.232     www      5046:           my ($match,$cond)=&is_on_map($refuri);
                   5047:             if ($match) {
                   5048:               my $refstatecond=$cond;
1.620     albertel 5049:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5050:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5051:                   $thisallowed.=$1;
1.53      www      5052:                   $uri=$refuri;
                   5053:                   $statecond=$refstatecond;
1.52      www      5054:               }
                   5055:           }
1.148     www      5056:         }
1.29      www      5057:        }
1.52      www      5058:    }
1.29      www      5059: 
1.52      www      5060: #
1.103     harris41 5061: # Gathered now: all privileges that could apply, and condition number
1.52      www      5062: # 
                   5063: #
                   5064: # Full or no access?
                   5065: #
1.29      www      5066: 
1.52      www      5067:     if ($thisallowed=~/F/) {
                   5068: 	return 'F';
                   5069:     }
1.29      www      5070: 
1.52      www      5071:     unless ($thisallowed) {
                   5072:         return '';
                   5073:     }
1.29      www      5074: 
1.52      www      5075: # Restrictions exist, deal with them
                   5076: #
                   5077: #   C:according to course preferences
                   5078: #   R:according to resource settings
                   5079: #   L:unless locked
                   5080: #   X:according to user session state
                   5081: #
                   5082: 
                   5083: # Possibly locked functionality, check all courses
1.54      www      5084: # Locks might take effect only after 10 minutes cache expiration for other
                   5085: # courses, and 2 minutes for current course
1.52      www      5086: 
                   5087:     my $envkey;
                   5088:     if ($thisallowed=~/L/) {
1.1000    raeburn  5089:         foreach $envkey (keys(%env)) {
1.54      www      5090:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5091:                my $courseid=$2;
                   5092:                my $roleid=$1.'.'.$2;
1.92      www      5093:                $courseid=~s/^\///;
1.54      www      5094:                my $expiretime=600;
1.620     albertel 5095:                if ($env{'request.role'} eq $roleid) {
1.54      www      5096: 		  $expiretime=120;
                   5097:                }
                   5098: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5099:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5100:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5101: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5102:                }
1.620     albertel 5103:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5104:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5105: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5106:                        &log($env{'user.domain'},$env{'user.name'},
                   5107:                             $env{'user.home'},
1.57      www      5108:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5109:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5110:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5111: 		       return '';
                   5112:                    }
                   5113:                }
1.620     albertel 5114:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5115:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5116: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5117:                        &log($env{'user.domain'},$env{'user.name'},
                   5118:                             $env{'user.home'},
1.57      www      5119:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5120:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5121:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5122: 		       return '';
                   5123:                    }
                   5124:                }
                   5125: 	   }
1.29      www      5126:        }
1.52      www      5127:     }
                   5128:    
                   5129: #
                   5130: # Rest of the restrictions depend on selected course
                   5131: #
                   5132: 
1.620     albertel 5133:     unless ($env{'request.course.id'}) {
1.766     albertel 5134: 	if ($thisallowed eq 'A') {
                   5135: 	    return 'A';
1.814     raeburn  5136:         } elsif ($thisallowed eq 'B') {
                   5137:             return 'B';
1.766     albertel 5138: 	} else {
                   5139: 	    return '1';
                   5140: 	}
1.52      www      5141:     }
1.29      www      5142: 
1.52      www      5143: #
                   5144: # Now user is definitely in a course
                   5145: #
1.53      www      5146: 
                   5147: 
                   5148: # Course preferences
                   5149: 
                   5150:    if ($thisallowed=~/C/) {
1.620     albertel 5151:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5152:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5153:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5154: 	   =~/\Q$rolecode\E/) {
1.689     albertel 5155: 	   if ($priv ne 'pch') { 
                   5156: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5157: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5158: 			$env{'request.course.id'});
                   5159: 	   }
1.237     www      5160:            return '';
                   5161:        }
                   5162: 
1.620     albertel 5163:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5164: 	   =~/\Q$unamedom\E/) {
1.689     albertel 5165: 	   if ($priv ne 'pch') { 
                   5166: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5167: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5168: 			$env{'request.course.id'});
                   5169: 	   }
1.54      www      5170:            return '';
                   5171:        }
1.53      www      5172:    }
                   5173: 
                   5174: # Resource preferences
                   5175: 
                   5176:    if ($thisallowed=~/R/) {
1.620     albertel 5177:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5178:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 5179: 	   if ($priv ne 'pch') { 
                   5180: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5181: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5182: 	   }
                   5183: 	   return '';
1.54      www      5184:        }
1.53      www      5185:    }
1.30      www      5186: 
1.246     www      5187: # Restricted by state or randomout?
1.30      www      5188: 
1.52      www      5189:    if ($thisallowed=~/X/) {
1.620     albertel 5190:       if ($env{'acc.randomout'}) {
1.579     albertel 5191: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5192:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5193:             return ''; 
                   5194:          }
1.247     www      5195:       }
                   5196:       if (&condval($statecond)) {
1.52      www      5197: 	 return '2';
                   5198:       } else {
                   5199:          return '';
                   5200:       }
                   5201:    }
1.30      www      5202: 
1.766     albertel 5203:     if ($thisallowed eq 'A') {
                   5204: 	return 'A';
1.814     raeburn  5205:     } elsif ($thisallowed eq 'B') {
                   5206:         return 'B';
1.766     albertel 5207:     }
1.52      www      5208:    return 'F';
1.232     www      5209: }
                   5210: 
1.710     albertel 5211: sub split_uri_for_cond {
                   5212:     my $uri=&deversion(&declutter(shift));
                   5213:     my @uriparts=split(/\//,$uri);
                   5214:     my $filename=pop(@uriparts);
                   5215:     my $pathname=join('/',@uriparts);
                   5216:     return ($pathname,$filename);
                   5217: }
1.232     www      5218: # --------------------------------------------------- Is a resource on the map?
                   5219: 
                   5220: sub is_on_map {
1.710     albertel 5221:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5222:     #Trying to find the conditional for the file
1.620     albertel 5223:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5224: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5225:     if ($match) {
1.289     bowersj2 5226: 	return (1,$1);
                   5227:     } else {
1.434     www      5228: 	return (0,0);
1.289     bowersj2 5229:     }
1.12      www      5230: }
                   5231: 
1.427     www      5232: # --------------------------------------------------------- Get symb from alias
                   5233: 
                   5234: sub get_symb_from_alias {
                   5235:     my $symb=shift;
                   5236:     my ($map,$resid,$url)=&decode_symb($symb);
                   5237: # Already is a symb
                   5238:     if ($url) { return $symb; }
                   5239: # Must be an alias
                   5240:     my $aliassymb='';
                   5241:     my %bighash;
1.620     albertel 5242:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5243:                             &GDBM_READER(),0640)) {
                   5244:         my $rid=$bighash{'mapalias_'.$symb};
                   5245: 	if ($rid) {
                   5246: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5247: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5248: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5249: 	}
                   5250:         untie %bighash;
                   5251:     }
                   5252:     return $aliassymb;
                   5253: }
                   5254: 
1.12      www      5255: # ----------------------------------------------------------------- Define Role
                   5256: 
                   5257: sub definerole {
                   5258:   if (allowed('mcr','/')) {
                   5259:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5260:     foreach my $role (split(':',$sysrole)) {
                   5261: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5262:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5263:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5264: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5265:                return "refused:s:$crole&$cqual"; 
                   5266:             }
                   5267:         }
1.191     harris41 5268:     }
1.800     albertel 5269:     foreach my $role (split(':',$domrole)) {
                   5270: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5271:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5272:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5273: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5274:                return "refused:d:$crole&$cqual"; 
                   5275:             }
                   5276:         }
1.191     harris41 5277:     }
1.800     albertel 5278:     foreach my $role (split(':',$courole)) {
                   5279: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5280:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5281:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5282: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5283:                return "refused:c:$crole&$cqual"; 
                   5284:             }
                   5285:         }
1.191     harris41 5286:     }
1.620     albertel 5287:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5288:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5289: 	        "rolesdef_$rolename=".
                   5290:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5291:     return reply($command,$env{'user.home'});
1.12      www      5292:   } else {
                   5293:     return 'refused';
                   5294:   }
1.105     harris41 5295: }
                   5296: 
                   5297: # ---------------- Make a metadata query against the network of library servers
                   5298: 
                   5299: sub metadata_query {
1.244     matthew  5300:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5301:     my %rhash;
1.845     albertel 5302:     my %libserv = &all_library();
1.244     matthew  5303:     my @server_list = (defined($server_array) ? @$server_array
                   5304:                                               : keys(%libserv) );
                   5305:     for my $server (@server_list) {
1.118     harris41 5306: 	unless ($custom or $customshow) {
                   5307: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5308: 	    $rhash{$server}=$reply;
                   5309: 	}
                   5310: 	else {
                   5311: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5312: 			     &escape($custom).':'.&escape($customshow),
                   5313: 			     $server);
                   5314: 	    $rhash{$server}=$reply;
                   5315: 	}
1.112     harris41 5316:     }
1.118     harris41 5317:     return \%rhash;
1.240     www      5318: }
                   5319: 
                   5320: # ----------------------------------------- Send log queries and wait for reply
                   5321: 
                   5322: sub log_query {
                   5323:     my ($uname,$udom,$query,%filters)=@_;
                   5324:     my $uhome=&homeserver($uname,$udom);
                   5325:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5326:     my $uhost=&hostname($uhome);
1.800     albertel 5327:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5328:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5329:                        $uhome);
1.479     albertel 5330:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5331:     return get_query_reply($queryid);
                   5332: }
                   5333: 
1.818     raeburn  5334: # -------------------------- Update MySQL table for portfolio file
                   5335: 
                   5336: sub update_portfolio_table {
1.821     raeburn  5337:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5338:     if ($group ne '') {
                   5339:         $file_name =~s /^\Q$group\E//;
                   5340:     }
1.818     raeburn  5341:     my $homeserver = &homeserver($uname,$udom);
                   5342:     my $queryid=
1.821     raeburn  5343:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5344:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5345:     my $reply = &get_query_reply($queryid);
                   5346:     return $reply;
                   5347: }
                   5348: 
1.899     raeburn  5349: # -------------------------- Update MySQL allusers table
                   5350: 
                   5351: sub update_allusers_table {
                   5352:     my ($uname,$udom,$names) = @_;
                   5353:     my $homeserver = &homeserver($uname,$udom);
                   5354:     my $queryid=
                   5355:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5356:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5357:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5358:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5359:                'generation='.&escape($names->{'generation'}).'%%'.
                   5360:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5361:                'id='.&escape($names->{'id'}),$homeserver);
                   5362:     my $reply = &get_query_reply($queryid);
                   5363:     return $reply;
                   5364: }
                   5365: 
1.508     raeburn  5366: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5367: 
                   5368: sub fetch_enrollment_query {
1.511     raeburn  5369:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5370:     my $homeserver;
1.547     raeburn  5371:     my $maxtries = 1;
1.508     raeburn  5372:     if ($context eq 'automated') {
                   5373:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5374:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5375:     } else {
                   5376:         $homeserver = &homeserver($cnum,$dom);
                   5377:     }
1.838     albertel 5378:     my $host=&hostname($homeserver);
1.506     raeburn  5379:     my $cmd = '';
1.1000    raeburn  5380:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 5381:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5382:     }
                   5383:     $cmd =~ s/%%$//;
                   5384:     $cmd = &escape($cmd);
                   5385:     my $query = 'fetchenrollment';
1.620     albertel 5386:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5387:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5388:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5389:         return 'error: '.$queryid;
                   5390:     }
1.506     raeburn  5391:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5392:     my $tries = 1;
                   5393:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5394:         $reply = &get_query_reply($queryid);
                   5395:         $tries ++;
                   5396:     }
1.526     raeburn  5397:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5398:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5399:     } else {
1.901     albertel 5400:         my @responses = split(/:/,$reply);
1.515     raeburn  5401:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5402:             foreach my $line (@responses) {
                   5403:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5404:                 $$replyref{$key} = $value;
                   5405:             }
                   5406:         } else {
1.506     raeburn  5407:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5408:             foreach my $line (@responses) {
                   5409:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5410:                 $$replyref{$key} = $value;
                   5411:                 if ($value > 0) {
1.800     albertel 5412:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5413:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5414:                         my $destname = $pathname.'/'.$filename;
                   5415:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5416:                         if ($xml_classlist =~ /^error/) {
                   5417:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5418:                         } else {
1.506     raeburn  5419:                             if ( open(FILE,">$destname") ) {
                   5420:                                 print FILE &unescape($xml_classlist);
                   5421:                                 close(FILE);
1.526     raeburn  5422:                             } else {
                   5423:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5424:                             }
                   5425:                         }
                   5426:                     }
                   5427:                 }
                   5428:             }
                   5429:         }
                   5430:         return 'ok';
                   5431:     }
                   5432:     return 'error';
                   5433: }
                   5434: 
1.242     www      5435: sub get_query_reply {
                   5436:     my $queryid=shift;
1.240     www      5437:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5438:     my $reply='';
                   5439:     for (1..100) {
                   5440: 	sleep 2;
                   5441:         if (-e $replyfile.'.end') {
1.448     albertel 5442: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5443: 		$reply = join('',<$fh>);
                   5444: 		close($fh);
1.240     www      5445: 	   } else { return 'error: reply_file_error'; }
1.242     www      5446:            return &unescape($reply);
                   5447: 	}
1.240     www      5448:     }
1.242     www      5449:     return 'timeout:'.$queryid;
1.240     www      5450: }
                   5451: 
                   5452: sub courselog_query {
1.241     www      5453: #
                   5454: # possible filters:
                   5455: # url: url or symb
                   5456: # username
                   5457: # domain
                   5458: # action: view, submit, grade
                   5459: # start: timestamp
                   5460: # end: timestamp
                   5461: #
1.240     www      5462:     my (%filters)=@_;
1.620     albertel 5463:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5464:     if ($filters{'url'}) {
                   5465: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5466:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5467:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5468:     }
1.620     albertel 5469:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5470:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5471:     return &log_query($cname,$cdom,'courselog',%filters);
                   5472: }
                   5473: 
                   5474: sub userlog_query {
1.858     raeburn  5475: #
                   5476: # possible filters:
                   5477: # action: log check role
                   5478: # start: timestamp
                   5479: # end: timestamp
                   5480: #
1.240     www      5481:     my ($uname,$udom,%filters)=@_;
                   5482:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5483: }
                   5484: 
1.506     raeburn  5485: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5486: 
                   5487: sub auto_run {
1.508     raeburn  5488:     my ($cnum,$cdom) = @_;
1.876     raeburn  5489:     my $response = 0;
                   5490:     my $settings;
                   5491:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5492:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5493:         $settings = $domconfig{'autoenroll'};
                   5494:         if ($settings->{'run'} eq '1') {
                   5495:             $response = 1;
                   5496:         }
                   5497:     } else {
1.934     raeburn  5498:         my $homeserver;
                   5499:         if (&is_course($cdom,$cnum)) {
                   5500:             $homeserver = &homeserver($cnum,$cdom);
                   5501:         } else {
                   5502:             $homeserver = &domain($cdom,'primary');
                   5503:         }
                   5504:         if ($homeserver ne 'no_host') {
                   5505:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5506:         }
1.876     raeburn  5507:     }
1.506     raeburn  5508:     return $response;
                   5509: }
1.776     albertel 5510: 
1.506     raeburn  5511: sub auto_get_sections {
1.508     raeburn  5512:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  5513:     my $homeserver;
                   5514:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   5515:         $homeserver = &homeserver($cnum,$cdom);
                   5516:     }
                   5517:     if (!defined($homeserver)) { 
                   5518:         if ($cdom =~ /^$match_domain$/) {
                   5519:             $homeserver = &domain($cdom,'primary');
                   5520:         }
                   5521:     }
                   5522:     my @secs;
                   5523:     if (defined($homeserver)) {
                   5524:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   5525:         unless ($response eq 'refused') {
                   5526:             @secs = split(/:/,$response);
                   5527:         }
1.506     raeburn  5528:     }
                   5529:     return @secs;
                   5530: }
1.776     albertel 5531: 
1.506     raeburn  5532: sub auto_new_course {
1.508     raeburn  5533:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5534:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5535:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5536:     return $response;
                   5537: }
1.776     albertel 5538: 
1.506     raeburn  5539: sub auto_validate_courseID {
1.508     raeburn  5540:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5541:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5542:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5543:     return $response;
                   5544: }
1.776     albertel 5545: 
1.1007    raeburn  5546: sub auto_validate_instcode {
                   5547:     my ($cnum,$cdom,$instcode,$owner) = @_;
                   5548:     my ($homeserver,$response);
                   5549:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5550:         $homeserver = &homeserver($cnum,$cdom);
                   5551:     }
                   5552:     if (!defined($homeserver)) {
                   5553:         if ($cdom =~ /^$match_domain$/) {
                   5554:             $homeserver = &domain($cdom,'primary');
                   5555:         }
                   5556:     }
                   5557:     my $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   5558:                            &escape($instcode).':'.&escape($owner),$homeserver));
                   5559:     return $response;
                   5560: }
                   5561: 
1.506     raeburn  5562: sub auto_create_password {
1.873     raeburn  5563:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5564:     my ($homeserver,$response);
1.506     raeburn  5565:     my $create_passwd = 0;
                   5566:     my $authchk = '';
1.873     raeburn  5567:     if ($udom =~ /^$match_domain$/) {
                   5568:         $homeserver = &domain($udom,'primary');
                   5569:     }
                   5570:     if ($homeserver eq '') {
                   5571:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5572:             $homeserver = &homeserver($cnum,$cdom);
                   5573:         }
                   5574:     }
                   5575:     if ($homeserver eq '') {
                   5576:         $authchk = 'nodomain';
1.506     raeburn  5577:     } else {
1.873     raeburn  5578:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5579:         if ($response eq 'refused') {
                   5580:             $authchk = 'refused';
                   5581:         } else {
1.901     albertel 5582:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5583:         }
1.506     raeburn  5584:     }
                   5585:     return ($authparam,$create_passwd,$authchk);
                   5586: }
                   5587: 
1.706     raeburn  5588: sub auto_photo_permission {
                   5589:     my ($cnum,$cdom,$students) = @_;
                   5590:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5591:     my ($outcome,$perm_reqd,$conditions) = 
                   5592: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5593:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5594: 	return (undef,undef);
                   5595:     }
1.706     raeburn  5596:     return ($outcome,$perm_reqd,$conditions);
                   5597: }
                   5598: 
                   5599: sub auto_checkphotos {
                   5600:     my ($uname,$udom,$pid) = @_;
                   5601:     my $homeserver = &homeserver($uname,$udom);
                   5602:     my ($result,$resulttype);
                   5603:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5604: 				   &escape($uname).':'.&escape($pid),
                   5605: 				   $homeserver));
1.709     albertel 5606:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5607: 	return (undef,undef);
                   5608:     }
1.706     raeburn  5609:     if ($outcome) {
                   5610:         ($result,$resulttype) = split(/:/,$outcome);
                   5611:     } 
                   5612:     return ($result,$resulttype);
                   5613: }
                   5614: 
                   5615: sub auto_photochoice {
                   5616:     my ($cnum,$cdom) = @_;
                   5617:     my $homeserver = &homeserver($cnum,$cdom);
                   5618:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5619: 						       &escape($cdom),
                   5620: 						       $homeserver)));
1.709     albertel 5621:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5622: 	return (undef,undef);
                   5623:     }
1.706     raeburn  5624:     return ($update,$comment);
                   5625: }
                   5626: 
                   5627: sub auto_photoupdate {
                   5628:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5629:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5630:     my $host=&hostname($homeserver);
1.706     raeburn  5631:     my $cmd = '';
                   5632:     my $maxtries = 1;
1.800     albertel 5633:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5634:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5635:     }
                   5636:     $cmd =~ s/%%$//;
                   5637:     $cmd = &escape($cmd);
                   5638:     my $query = 'institutionalphotos';
                   5639:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5640:     unless ($queryid=~/^\Q$host\E\_/) {
                   5641:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5642:         return 'error: '.$queryid;
                   5643:     }
                   5644:     my $reply = &get_query_reply($queryid);
                   5645:     my $tries = 1;
                   5646:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5647:         $reply = &get_query_reply($queryid);
                   5648:         $tries ++;
                   5649:     }
                   5650:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5651:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5652:     } else {
                   5653:         my @responses = split(/:/,$reply);
                   5654:         my $outcome = shift(@responses); 
                   5655:         foreach my $item (@responses) {
                   5656:             my ($key,$value) = split(/=/,$item);
                   5657:             $$photo{$key} = $value;
                   5658:         }
                   5659:         return $outcome;
                   5660:     }
                   5661:     return 'error';
                   5662: }
                   5663: 
1.521     raeburn  5664: sub auto_instcode_format {
1.793     albertel 5665:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5666: 	$cat_order) = @_;
1.521     raeburn  5667:     my $courses = '';
1.772     raeburn  5668:     my @homeservers;
1.521     raeburn  5669:     if ($caller eq 'global') {
1.841     albertel 5670: 	my %servers = &get_servers($codedom,'library');
                   5671: 	foreach my $tryserver (keys(%servers)) {
                   5672: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5673: 		push(@homeservers,$tryserver);
                   5674: 	    }
1.584     raeburn  5675:         }
1.521     raeburn  5676:     } else {
1.772     raeburn  5677:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5678:     }
1.793     albertel 5679:     foreach my $code (keys(%{$instcodes})) {
                   5680:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5681:     }
                   5682:     chop($courses);
1.772     raeburn  5683:     my $ok_response = 0;
                   5684:     my $response;
                   5685:     while (@homeservers > 0 && $ok_response == 0) {
                   5686:         my $server = shift(@homeservers); 
                   5687:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5688:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5689:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5690: 		split(/:/,$response);
1.772     raeburn  5691:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5692:             push(@{$codetitles},&str2array($codetitles_str));
                   5693:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5694:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5695:             $ok_response = 1;
                   5696:         }
                   5697:     }
                   5698:     if ($ok_response) {
1.521     raeburn  5699:         return 'ok';
1.772     raeburn  5700:     } else {
                   5701:         return $response;
1.521     raeburn  5702:     }
                   5703: }
                   5704: 
1.792     raeburn  5705: sub auto_instcode_defaults {
                   5706:     my ($domain,$returnhash,$code_order) = @_;
                   5707:     my @homeservers;
1.841     albertel 5708: 
                   5709:     my %servers = &get_servers($domain,'library');
                   5710:     foreach my $tryserver (keys(%servers)) {
                   5711: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5712: 	    push(@homeservers,$tryserver);
                   5713: 	}
1.792     raeburn  5714:     }
1.841     albertel 5715: 
1.792     raeburn  5716:     my $response;
1.841     albertel 5717:     foreach my $server (@homeservers) {
1.792     raeburn  5718:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5719:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5720: 	
                   5721: 	foreach my $pair (split(/\&/,$response)) {
                   5722: 	    my ($name,$value)=split(/\=/,$pair);
                   5723: 	    if ($name eq 'code_order') {
                   5724: 		@{$code_order} = split(/\&/,&unescape($value));
                   5725: 	    } else {
                   5726: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5727: 	    }
                   5728: 	}
                   5729: 	return 'ok';
1.792     raeburn  5730:     }
1.841     albertel 5731: 
                   5732:     return $response;
1.1003    raeburn  5733: }
                   5734: 
                   5735: sub auto_possible_instcodes {
1.1007    raeburn  5736:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   5737:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   5738:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   5739:         return;
                   5740:     }
1.1003    raeburn  5741:     my (@homeservers,$uhome);
                   5742:     if (defined(&domain($domain,'primary'))) {
                   5743:         $uhome=&domain($domain,'primary');
                   5744:         push(@homeservers,&domain($domain,'primary'));
                   5745:     } else {
                   5746:         my %servers = &get_servers($domain,'library');
                   5747:         foreach my $tryserver (keys(%servers)) {
                   5748:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5749:                 push(@homeservers,$tryserver);
                   5750:             }
                   5751:         }
                   5752:     }
                   5753:     my $response;
                   5754:     foreach my $server (@homeservers) {
                   5755:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   5756:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  5757:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   5758:             split(':',$response);
                   5759:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   5760:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  5761:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  5762:             my ($name,$value)=split('=',$item);
                   5763:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  5764:         }
                   5765:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  5766:             my ($name,$value)=split('=',$item);
                   5767:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  5768:         }
                   5769:         return 'ok';
                   5770:     }
                   5771:     return $response;
                   5772: }
1.792     raeburn  5773: 
1.1010    raeburn  5774: sub auto_courserequest_checks {
                   5775:     my ($dom) = @_;
                   5776:     my %validations;
                   5777:     return %validations; 
                   5778: }
                   5779: 
1.777     albertel 5780: sub auto_validate_class_sec {
1.918     raeburn  5781:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5782:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5783:     my $ownerlist;
                   5784:     if (ref($owners) eq 'ARRAY') {
                   5785:         $ownerlist = join(',',@{$owners});
                   5786:     } else {
                   5787:         $ownerlist = $owners;
                   5788:     }
1.773     raeburn  5789:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5790:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5791:     return $response;
                   5792: }
                   5793: 
1.679     raeburn  5794: # ------------------------------------------------------- Course Group routines
                   5795: 
                   5796: sub get_coursegroups {
1.809     raeburn  5797:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5798:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5799: }
                   5800: 
1.679     raeburn  5801: sub modify_coursegroup {
                   5802:     my ($cdom,$cnum,$groupsettings) = @_;
                   5803:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5804: }
                   5805: 
1.809     raeburn  5806: sub toggle_coursegroup_status {
                   5807:     my ($cdom,$cnum,$group,$action) = @_;
                   5808:     my ($from_namespace,$to_namespace);
                   5809:     if ($action eq 'delete') {
                   5810:         $from_namespace = 'coursegroups';
                   5811:         $to_namespace = 'deleted_groups';
                   5812:     } else {
                   5813:         $from_namespace = 'deleted_groups';
                   5814:         $to_namespace = 'coursegroups';
                   5815:     }
                   5816:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5817:     if (my $tmp = &error(%curr_group)) {
                   5818:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5819:         return ('read error',$tmp);
                   5820:     } else {
                   5821:         my %savedsettings = %curr_group; 
1.809     raeburn  5822:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5823:         my $deloutcome;
                   5824:         if ($result eq 'ok') {
1.809     raeburn  5825:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5826:         } else {
                   5827:             return ('write error',$result);
                   5828:         }
                   5829:         if ($deloutcome eq 'ok') {
                   5830:             return 'ok';
                   5831:         } else {
                   5832:             return ('delete error',$deloutcome);
                   5833:         }
                   5834:     }
                   5835: }
                   5836: 
1.679     raeburn  5837: sub modify_group_roles {
1.957     raeburn  5838:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  5839:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5840:     my $role = 'gr/'.&escape($userprivs);
                   5841:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  5842:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  5843:     if ($result eq 'ok') {
                   5844:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5845:     }
1.679     raeburn  5846:     return $result;
                   5847: }
                   5848: 
                   5849: sub modify_coursegroup_membership {
                   5850:     my ($cdom,$cnum,$membership) = @_;
                   5851:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5852:     return $result;
                   5853: }
                   5854: 
1.682     raeburn  5855: sub get_active_groups {
                   5856:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5857:     my $now = time;
                   5858:     my %groups = ();
                   5859:     foreach my $key (keys(%env)) {
1.811     albertel 5860:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5861:             my ($start,$end) = split(/\./,$env{$key});
                   5862:             if (($end!=0) && ($end<$now)) { next; }
                   5863:             if (($start!=0) && ($start>$now)) { next; }
                   5864:             if ($1 eq $cdom && $2 eq $cnum) {
                   5865:                 $groups{$3} = $env{$key} ;
                   5866:             }
                   5867:         }
                   5868:     }
                   5869:     return %groups;
                   5870: }
                   5871: 
1.683     raeburn  5872: sub get_group_membership {
                   5873:     my ($cdom,$cnum,$group) = @_;
                   5874:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5875: }
                   5876: 
                   5877: sub get_users_groups {
                   5878:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5879:     my @usersgroups;
1.683     raeburn  5880:     my $cachetime=1800;
                   5881: 
                   5882:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5883:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5884:     if (defined($cached)) {
1.734     albertel 5885:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5886:     } else {  
                   5887:         $grouplist = '';
1.816     raeburn  5888:         my $courseurl = &courseid_to_courseurl($courseid);
                   5889:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5890:         my $access_end = $env{'course.'.$courseid.
                   5891:                               '.default_enrollment_end_date'};
                   5892:         my $now = time;
                   5893:         foreach my $key (keys(%roleshash)) {
                   5894:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5895:                 my $group = $1;
                   5896:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5897:                     my $start = $2;
                   5898:                     my $end = $1;
                   5899:                     if ($start == -1) { next; } # deleted from group
                   5900:                     if (($start!=0) && ($start>$now)) { next; }
                   5901:                     if (($end!=0) && ($end<$now)) {
                   5902:                         if ($access_end && $access_end < $now) {
                   5903:                             if ($access_end - $end < 86400) {
                   5904:                                 push(@usersgroups,$group);
1.733     raeburn  5905:                             }
                   5906:                         }
1.817     raeburn  5907:                         next;
1.733     raeburn  5908:                     }
1.817     raeburn  5909:                     push(@usersgroups,$group);
1.683     raeburn  5910:                 }
                   5911:             }
                   5912:         }
1.817     raeburn  5913:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5914:         $grouplist = join(':',@usersgroups);
                   5915:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5916:     }
1.733     raeburn  5917:     return @usersgroups;
1.683     raeburn  5918: }
                   5919: 
                   5920: sub devalidate_getgroups_cache {
                   5921:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5922:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5923: 
1.683     raeburn  5924:     my $hashid="$udom:$uname:$courseid";
                   5925:     &devalidate_cache_new('getgroups',$hashid);
                   5926: }
                   5927: 
1.12      www      5928: # ------------------------------------------------------------------ Plain Text
                   5929: 
                   5930: sub plaintext {
1.988     raeburn  5931:     my ($short,$type,$cid,$forcedefault) = @_;
1.758     albertel 5932:     if ($short =~ /^cr/) {
                   5933: 	return (split('/',$short))[-1];
                   5934:     }
1.742     raeburn  5935:     if (!defined($cid)) {
                   5936:         $cid = $env{'request.course.id'};
                   5937:     }
1.988     raeburn  5938:     if (defined($cid) && ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '')) {
                   5939:         unless ($forcedefault) {
                   5940:             my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   5941:             &Apache::lonlocal::mt_escape(\$roletext);
                   5942:             return &Apache::lonlocal::mt($roletext);
                   5943:         }
1.742     raeburn  5944:     }
                   5945:     my %rolenames = (
1.1008    raeburn  5946:                       Course    => 'std',
                   5947:                       Community => 'alt1',
1.742     raeburn  5948:                     );
                   5949:     if (defined($type) && 
                   5950:          defined($rolenames{$type}) && 
                   5951:          defined($prp{$short}{$rolenames{$type}})) {
                   5952:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5953:     } else {
                   5954:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5955:     }
1.12      www      5956: }
                   5957: 
                   5958: # ----------------------------------------------------------------- Assign Role
                   5959: 
                   5960: sub assignrole {
1.957     raeburn  5961:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   5962:         $context)=@_;
1.21      www      5963:     my $mrole;
                   5964:     if ($role =~ /^cr\//) {
1.393     www      5965:         my $cwosec=$url;
1.811     albertel 5966:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5967: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5968:            &logthis('Refused custom assignrole: '.
                   5969:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5970: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5971:            return 'refused'; 
                   5972:         }
1.21      www      5973:         $mrole='cr';
1.678     raeburn  5974:     } elsif ($role =~ /^gr\//) {
                   5975:         my $cwogrp=$url;
1.811     albertel 5976:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5977:         unless (&allowed('mdg',$cwogrp)) {
                   5978:             &logthis('Refused group assignrole: '.
                   5979:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5980:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5981:             return 'refused';
                   5982:         }
                   5983:         $mrole='gr';
1.21      www      5984:     } else {
1.82      www      5985:         my $cwosec=$url;
1.811     albertel 5986:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5987:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5988:             my $refused;
                   5989:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5990:                 if (!(&allowed('c'.$role,$url))) {
                   5991:                     $refused = 1;
                   5992:                 }
                   5993:             } else {
                   5994:                 $refused = 1;
                   5995:             }
1.947     raeburn  5996:             if ($refused) {
                   5997:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5998:                     $refused = '';
                   5999:                 } else {
                   6000:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   6001:                              ' '.$role.' '.$end.' '.$start.' by '.
                   6002: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   6003:                     return 'refused';
                   6004:                 }
1.932     raeburn  6005:             }
1.104     www      6006:         }
1.21      www      6007:         $mrole=$role;
                   6008:     }
1.620     albertel 6009:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6010:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6011:     if ($end) { $command.='_'.$end; }
1.21      www      6012:     if ($start) {
                   6013: 	if ($end) { 
1.81      www      6014:            $command.='_'.$start; 
1.21      www      6015:         } else {
1.81      www      6016:            $command.='_0_'.$start;
1.21      www      6017:         }
                   6018:     }
1.739     raeburn  6019:     my $origstart = $start;
                   6020:     my $origend = $end;
1.957     raeburn  6021:     my $delflag;
1.357     www      6022: # actually delete
                   6023:     if ($deleteflag) {
1.373     www      6024: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6025: # modify command to delete the role
1.620     albertel 6026:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6027:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6028: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6029: # set start and finish to negative values for userrolelog
                   6030:            $start=-1;
                   6031:            $end=-1;
1.957     raeburn  6032:            $delflag = 1;
1.357     www      6033:         }
                   6034:     }
                   6035: # send command
1.349     www      6036:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6037: # log new user role if status is ok
1.349     www      6038:     if ($answer eq 'ok') {
1.663     raeburn  6039: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6040: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6041:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6042:         unless ($role =~ /^gr/) {
                   6043:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6044:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6045:         }
1.349     www      6046:     }
                   6047:     return $answer;
1.169     harris41 6048: }
                   6049: 
                   6050: # -------------------------------------------------- Modify user authentication
1.197     www      6051: # Overrides without validation
                   6052: 
1.169     harris41 6053: sub modifyuserauth {
                   6054:     my ($udom,$uname,$umode,$upass)=@_;
                   6055:     my $uhome=&homeserver($uname,$udom);
1.197     www      6056:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6057:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6058:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6059:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6060:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6061: 		     &escape($upass),$uhome);
1.620     albertel 6062:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6063:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6064:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6065:     &log($udom,,$uname,$uhome,
1.620     albertel 6066:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6067:                                      $env{'user.name'}.', '.$umode.
1.197     www      6068:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 6069:     unless ($reply eq 'ok') {
1.197     www      6070:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 6071: 	return 'error: '.$reply;
                   6072:     }   
1.170     harris41 6073:     return 'ok';
1.80      www      6074: }
                   6075: 
1.81      www      6076: # --------------------------------------------------------------- Modify a user
1.80      www      6077: 
1.81      www      6078: sub modifyuser {
1.206     matthew  6079:     my ($udom,    $uname, $uid,
                   6080:         $umode,   $upass, $first,
                   6081:         $middle,  $last,  $gene,
1.963     raeburn  6082:         $forceid, $desiredhome, $email, $inststatus)=@_;
1.807     albertel 6083:     $udom= &LONCAPA::clean_domain($udom);
                   6084:     $uname=&LONCAPA::clean_username($uname);
1.81      www      6085:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      6086:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  6087: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   6088:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   6089:                                      ' desiredhome not specified'). 
1.620     albertel 6090:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6091:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 6092:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      6093: # ----------------------------------------------------------------- Create User
1.406     albertel 6094:     if (($uhome eq 'no_host') && 
                   6095: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      6096:         my $unhome='';
1.844     albertel 6097:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  6098:             $unhome = $desiredhome;
1.620     albertel 6099: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   6100: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  6101:         } else { # load balancing routine for determining $unhome
1.81      www      6102:             my $loadm=10000000;
1.841     albertel 6103: 	    my %servers = &get_servers($udom,'library');
                   6104: 	    foreach my $tryserver (keys(%servers)) {
                   6105: 		my $answer=reply('load',$tryserver);
                   6106: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   6107: 		    $loadm=$answer;
                   6108: 		    $unhome=$tryserver;
                   6109: 		}
1.80      www      6110: 	    }
                   6111:         }
                   6112:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  6113: 	    return 'error: unable to find a home server for '.$uname.
                   6114:                    ' in domain '.$udom;
1.80      www      6115:         }
                   6116:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   6117:                          &escape($upass),$unhome);
                   6118: 	unless ($reply eq 'ok') {
                   6119:             return 'error: '.$reply;
                   6120:         }   
1.230     stredwic 6121:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      6122:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  6123: 	    return 'error: unable verify users home machine.';
1.80      www      6124:         }
1.209     matthew  6125:     }   # End of creation of new user
1.80      www      6126: # ---------------------------------------------------------------------- Add ID
                   6127:     if ($uid) {
                   6128:        $uid=~tr/A-Z/a-z/;
                   6129:        my %uidhash=&idrget($udom,$uname);
1.196     www      6130:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   6131:          && (!$forceid)) {
1.80      www      6132: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  6133: 	      return 'error: user id "'.$uid.'" does not match '.
                   6134:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      6135:           }
                   6136:        } else {
                   6137: 	  &idput($udom,($uname => $uid));
                   6138:        }
                   6139:     }
                   6140: # -------------------------------------------------------------- Add names, etc
1.313     matthew  6141:     my @tmp=&get('environment',
1.899     raeburn  6142: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  6143:                     'permanentemail','inststatus'],
1.134     albertel 6144: 		   $udom,$uname);
1.313     matthew  6145:     my %names;
                   6146:     if ($tmp[0] =~ m/^error:.*/) { 
                   6147:         %names=(); 
                   6148:     } else {
                   6149:         %names = @tmp;
                   6150:     }
1.388     www      6151: #
                   6152: # Make sure to not trash student environment if instructor does not bother
                   6153: # to supply name and email information
                   6154: #
                   6155:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  6156:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      6157:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  6158:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      6159:     if ($email) {
                   6160:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  6161:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      6162:     }
1.899     raeburn  6163:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  6164:     if (defined($inststatus)) {
                   6165:         $names{'inststatus'} = '';
                   6166:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   6167:         if (ref($usertypes) eq 'HASH') {
                   6168:             my @okstatuses; 
                   6169:             foreach my $item (split(/:/,$inststatus)) {
                   6170:                 if (defined($usertypes->{$item})) {
                   6171:                     push(@okstatuses,$item);  
                   6172:                 }
                   6173:             }
                   6174:             if (@okstatuses) {
                   6175:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   6176:             }
                   6177:         }
                   6178:     }
1.134     albertel 6179:     my $reply = &put('environment', \%names, $udom,$uname);
                   6180:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  6181:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      6182:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963     raeburn  6183:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
                   6184:                  $umode.', '.$first.', '.$middle.', '.
                   6185: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
                   6186:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   6187:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   6188:     } else {
                   6189:         $logmsg .= ' during self creation';
                   6190:     }
                   6191:     &logthis($logmsg);
1.134     albertel 6192:     return 'ok';
1.80      www      6193: }
                   6194: 
1.81      www      6195: # -------------------------------------------------------------- Modify student
1.80      www      6196: 
1.81      www      6197: sub modifystudent {
                   6198:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  6199:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  6200:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 6201:     if (!$cid) {
1.620     albertel 6202: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6203: 	    return 'not_in_class';
                   6204: 	}
1.80      www      6205:     }
                   6206: # --------------------------------------------------------------- Make the user
1.81      www      6207:     my $reply=&modifyuser
1.209     matthew  6208: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  6209:          $desiredhome,$email,$inststatus);
1.80      www      6210:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  6211:     # This will cause &modify_student_enrollment to get the uid from the
                   6212:     # students environment
                   6213:     $uid = undef if (!$forceid);
1.455     albertel 6214:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  6215: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  6216:     return $reply;
                   6217: }
                   6218: 
                   6219: sub modify_student_enrollment {
1.957     raeburn  6220:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 6221:     my ($cdom,$cnum,$chome);
                   6222:     if (!$cid) {
1.620     albertel 6223: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6224: 	    return 'not_in_class';
                   6225: 	}
1.620     albertel 6226: 	$cdom=$env{'course.'.$cid.'.domain'};
                   6227: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 6228:     } else {
                   6229: 	($cdom,$cnum)=split(/_/,$cid);
                   6230:     }
1.620     albertel 6231:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 6232:     if (!$chome) {
1.457     raeburn  6233: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  6234:     }
1.455     albertel 6235:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  6236:     # Make sure the user exists
1.81      www      6237:     my $uhome=&homeserver($uname,$udom);
                   6238:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6239: 	return 'error: no such user';
                   6240:     }
1.297     matthew  6241:     # Get student data if we were not given enough information
                   6242:     if (!defined($first)  || $first  eq '' || 
                   6243:         !defined($last)   || $last   eq '' || 
                   6244:         !defined($uid)    || $uid    eq '' || 
                   6245:         !defined($middle) || $middle eq '' || 
                   6246:         !defined($gene)   || $gene   eq '') {
1.294     matthew  6247:         # They did not supply us with enough data to enroll the student, so
                   6248:         # we need to pick up more information.
1.297     matthew  6249:         my %tmp = &get('environment',
1.294     matthew  6250:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  6251:                        ,$udom,$uname);
                   6252: 
1.800     albertel 6253:         #foreach my $key (keys(%tmp)) {
                   6254:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 6255:         #}
1.294     matthew  6256:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   6257:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   6258:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  6259:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  6260:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   6261:     }
1.556     albertel 6262:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 6263:     my $reply=cput('classlist',
                   6264: 		   {"$uname:$udom" => 
1.515     raeburn  6265: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 6266: 		   $cdom,$cnum);
1.81      www      6267:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   6268: 	return 'error: '.$reply;
1.652     albertel 6269:     } else {
                   6270: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      6271:     }
1.297     matthew  6272:     # Add student role to user
1.83      www      6273:     my $uurl='/'.$cid;
1.81      www      6274:     $uurl=~s/\_/\//g;
                   6275:     if ($usec) {
                   6276: 	$uurl.='/'.$usec;
                   6277:     }
1.957     raeburn  6278:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      6279: }
                   6280: 
1.556     albertel 6281: sub format_name {
                   6282:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   6283:     my $name;
                   6284:     if ($first ne 'lastname') {
                   6285: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   6286:     } else {
                   6287: 	if ($lastname=~/\S/) {
                   6288: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   6289: 	    $name=~s/\s+,/,/;
                   6290: 	} else {
                   6291: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   6292: 	}
                   6293:     }
                   6294:     $name=~s/^\s+//;
                   6295:     $name=~s/\s+$//;
                   6296:     $name=~s/\s+/ /g;
                   6297:     return $name;
                   6298: }
                   6299: 
1.84      www      6300: # ------------------------------------------------- Write to course preferences
                   6301: 
                   6302: sub writecoursepref {
                   6303:     my ($courseid,%prefs)=@_;
                   6304:     $courseid=~s/^\///;
                   6305:     $courseid=~s/\_/\//g;
                   6306:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   6307:     my $chome=homeserver($cnum,$cdomain);
                   6308:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   6309: 	return 'error: no such course';
                   6310:     }
                   6311:     my $cstring='';
1.800     albertel 6312:     foreach my $pref (keys(%prefs)) {
                   6313: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 6314:     }
1.84      www      6315:     $cstring=~s/\&$//;
                   6316:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   6317: }
                   6318: 
                   6319: # ---------------------------------------------------------- Make/modify course
                   6320: 
                   6321: sub createcourse {
1.741     raeburn  6322:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1011  ! raeburn  6323:         $course_owner,$crstype,$cnum)=@_;
1.84      www      6324:     $url=&declutter($url);
                   6325:     my $cid='';
1.264     matthew  6326:     unless (&allowed('ccc',$udom)) {
1.84      www      6327:         return 'refused';
                   6328:     }
1.1011  ! raeburn  6329: # --------------------------------------------------------------- Get Unique ID
        !          6330:     my $uname;
        !          6331:     if ($cnum =~ /^$match_courseid$/) {
        !          6332:         my $chome=&homeserver($cnum,$udom,'true');
        !          6333:         if (($chome eq '') || ($chome eq 'no_host')) {
        !          6334:             $uname = $cnum;
        !          6335:         } else {
        !          6336:             $uname = &generate_coursenum($udom);
        !          6337:         }
        !          6338:     } else {
        !          6339:         $uname = &generate_coursenum($udom);
        !          6340:     }
        !          6341:     return $uname if ($uname =~ /^error/);
        !          6342: # -------------------------------------------------- Check supplied server name
1.620     albertel 6343:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 6344:     if (! &is_library($course_server)) {
1.264     matthew  6345:         return 'error:bad server name '.$course_server;
                   6346:     }
1.84      www      6347: # ------------------------------------------------------------- Make the course
                   6348:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  6349:                       $course_server);
1.84      www      6350:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011  ! raeburn  6351:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      6352:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6353: 	return 'error: no such course';
                   6354:     }
1.271     www      6355: # ----------------------------------------------------------------- Course made
1.516     raeburn  6356: # log existence
1.918     raeburn  6357:     my $newcourse = {
                   6358:                     $udom.'_'.$uname => {
1.921     raeburn  6359:                                      description => $description,
                   6360:                                      inst_code   => $inst_code,
                   6361:                                      owner       => $course_owner,
                   6362:                                      type        => $crstype,
1.918     raeburn  6363:                                                 },
                   6364:                     };
1.921     raeburn  6365:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      6366: # set toplevel url
1.271     www      6367:     my $topurl=$url;
                   6368:     unless ($nonstandard) {
                   6369: # ------------------------------------------ For standard courses, make top url
                   6370:         my $mapurl=&clutter($url);
1.278     www      6371:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 6372:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      6373: <map>
                   6374: <resource id="1" type="start"></resource>
                   6375: <resource id="2" src="$mapurl"></resource>
                   6376: <resource id="3" type="finish"></resource>
                   6377: <link index="1" from="1" to="2"></link>
                   6378: <link index="2" from="2" to="3"></link>
                   6379: </map>
                   6380: ENDINITMAP
                   6381:         $topurl=&declutter(
1.638     albertel 6382:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      6383:                           );
                   6384:     }
                   6385: # ----------------------------------------------------------- Write preferences
1.84      www      6386:     &writecoursepref($udom.'_'.$uname,
                   6387:                      ('description' => $description,
1.271     www      6388:                       'url'         => $topurl));
1.84      www      6389:     return '/'.$udom.'/'.$uname;
                   6390: }
                   6391: 
1.1011  ! raeburn  6392: # ------------------------------------------------------------------- Create ID
        !          6393: sub generate_coursenum {
        !          6394:     my ($udom) = @_;
        !          6395:     my $domdesc = &domain($udom);
        !          6396:     return 'error: invalid domain' if ($domdesc eq '');
        !          6397:     my $uname=int(1+rand(9)).
        !          6398:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
        !          6399:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
        !          6400:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
        !          6401: # ----------------------------------------------- Make sure that does not exist
        !          6402:     my $uhome=&homeserver($uname,$udom,'true');
        !          6403:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
        !          6404:         $uname=int(1+rand(9)).
        !          6405:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
        !          6406:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
        !          6407:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
        !          6408:         $uhome=&homeserver($uname,$udom,'true');
        !          6409:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
        !          6410:             return 'error: unable to generate unique course-ID';
        !          6411:         }
        !          6412:     }
        !          6413:     return $uname;
        !          6414: }
        !          6415: 
1.813     albertel 6416: sub is_course {
                   6417:     my ($cdom,$cnum) = @_;
                   6418:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  6419: 				undef,'.');
1.813     albertel 6420:     if (exists($courses{$cdom.'_'.$cnum})) {
                   6421:         return 1;
                   6422:     }
                   6423:     return 0;
                   6424: }
                   6425: 
1.21      www      6426: # ---------------------------------------------------------- Assign Custom Role
                   6427: 
                   6428: sub assigncustomrole {
1.957     raeburn  6429:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6430:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  6431:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      6432: }
                   6433: 
                   6434: # ----------------------------------------------------------------- Revoke Role
                   6435: 
                   6436: sub revokerole {
1.957     raeburn  6437:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6438:     my $now=time;
1.965     raeburn  6439:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      6440: }
                   6441: 
                   6442: # ---------------------------------------------------------- Revoke Custom Role
                   6443: 
                   6444: sub revokecustomrole {
1.957     raeburn  6445:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6446:     my $now=time;
1.357     www      6447:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  6448:            $deleteflag,$selfenroll,$context);
1.17      www      6449: }
                   6450: 
1.533     banghart 6451: # ------------------------------------------------------------ Disk usage
1.535     albertel 6452: sub diskusage {
1.955     raeburn  6453:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   6454:     $directorypath =~ s/\/$//;
                   6455:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   6456:                        .&escape($getpropath).':'.&escape($uname).':'
                   6457:                        .&escape($udom),homeserver($uname,$udom));
                   6458:     if ($listing eq 'unknown_cmd') {
                   6459:         if ($getpropath) {
                   6460:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   6461:         }
                   6462:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   6463:     }
1.514     albertel 6464:     return $listing;
1.512     banghart 6465: }
                   6466: 
1.566     banghart 6467: sub is_locked {
                   6468:     my ($file_name, $domain, $user) = @_;
                   6469:     my @check;
                   6470:     my $is_locked;
                   6471:     push @check, $file_name;
1.613     albertel 6472:     my %locked = &get('file_permissions',\@check,
1.620     albertel 6473: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 6474:     my ($tmp)=keys(%locked);
                   6475:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  6476:     
1.566     banghart 6477:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  6478:         $is_locked = 'false';
                   6479:         foreach my $entry (@{$locked{$file_name}}) {
                   6480:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  6481:                $is_locked = 'true';
                   6482:                last;
1.745     raeburn  6483:            }
                   6484:        }
1.566     banghart 6485:     } else {
                   6486:         $is_locked = 'false';
                   6487:     }
                   6488: }
                   6489: 
1.759     albertel 6490: sub declutter_portfile {
                   6491:     my ($file) = @_;
1.833     albertel 6492:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 6493:     return $file;
                   6494: }
                   6495: 
1.559     banghart 6496: # ------------------------------------------------------------- Mark as Read Only
                   6497: 
                   6498: sub mark_as_readonly {
                   6499:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 6500:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6501:     my ($tmp)=keys(%current_permissions);
                   6502:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 6503:     foreach my $file (@{$files}) {
1.759     albertel 6504: 	$file = &declutter_portfile($file);
1.561     banghart 6505:         push(@{$current_permissions{$file}},$what);
1.559     banghart 6506:     }
1.613     albertel 6507:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6508:     return;
                   6509: }
                   6510: 
1.572     banghart 6511: # ------------------------------------------------------------Save Selected Files
                   6512: 
                   6513: sub save_selected_files {
                   6514:     my ($user, $path, @files) = @_;
                   6515:     my $filename = $user."savedfiles";
1.573     banghart 6516:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 6517:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 6518:     foreach my $file (@files) {
1.620     albertel 6519:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 6520:     }
                   6521:     foreach my $file (@other_files) {
1.574     banghart 6522:         print (OUT $file."\n");
1.572     banghart 6523:     }
1.574     banghart 6524:     close (OUT);
1.572     banghart 6525:     return 'ok';
                   6526: }
                   6527: 
1.574     banghart 6528: sub clear_selected_files {
                   6529:     my ($user) = @_;
                   6530:     my $filename = $user."savedfiles";
                   6531:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6532:     print (OUT undef);
                   6533:     close (OUT);
                   6534:     return ("ok");    
                   6535: }
                   6536: 
1.572     banghart 6537: sub files_in_path {
                   6538:     my ($user, $path) = @_;
                   6539:     my $filename = $user."savedfiles";
                   6540:     my %return_files;
1.574     banghart 6541:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 6542:     while (my $line_in = <IN>) {
1.574     banghart 6543:         chomp ($line_in);
                   6544:         my @paths_and_file = split (m!/!, $line_in);
                   6545:         my $file_part = pop (@paths_and_file);
                   6546:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 6547:         $path_part.='/';
                   6548:         my $path_and_file = $path_part.$file_part;
                   6549:         if ($path_part eq $path) {
                   6550:             $return_files{$file_part}= 'selected';
                   6551:         }
                   6552:     }
1.574     banghart 6553:     close (IN);
                   6554:     return (\%return_files);
1.572     banghart 6555: }
                   6556: 
                   6557: # called in portfolio select mode, to show files selected NOT in current directory
                   6558: sub files_not_in_path {
                   6559:     my ($user, $path) = @_;
                   6560:     my $filename = $user."savedfiles";
                   6561:     my @return_files;
                   6562:     my $path_part;
1.800     albertel 6563:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6564:     while (my $line = <IN>) {
1.572     banghart 6565:         #ok, I know it's clunky, but I want it to work
1.800     albertel 6566:         my @paths_and_file = split(m|/|, $line);
                   6567:         my $file_part = pop(@paths_and_file);
                   6568:         chomp($file_part);
                   6569:         my $path_part = join('/', @paths_and_file);
1.572     banghart 6570:         $path_part .= '/';
                   6571:         my $path_and_file = $path_part.$file_part;
                   6572:         if ($path_part ne $path) {
1.800     albertel 6573:             push(@return_files, ($path_and_file));
1.572     banghart 6574:         }
                   6575:     }
1.800     albertel 6576:     close(OUT);
1.574     banghart 6577:     return (@return_files);
1.572     banghart 6578: }
                   6579: 
1.745     raeburn  6580: #----------------------------------------------Get portfolio file permissions
1.629     banghart 6581: 
1.745     raeburn  6582: sub get_portfile_permissions {
                   6583:     my ($domain,$user) = @_;
1.613     albertel 6584:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6585:     my ($tmp)=keys(%current_permissions);
                   6586:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6587:     return \%current_permissions;
                   6588: }
                   6589: 
                   6590: #---------------------------------------------Get portfolio file access controls
                   6591: 
1.749     raeburn  6592: sub get_access_controls {
1.745     raeburn  6593:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 6594:     my %access;
                   6595:     my $real_file = $file;
                   6596:     $file =~ s/\.meta$//;
1.745     raeburn  6597:     if (defined($file)) {
1.749     raeburn  6598:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   6599:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 6600:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  6601:             }
                   6602:         }
1.745     raeburn  6603:     } else {
1.749     raeburn  6604:         foreach my $key (keys(%{$current_permissions})) {
                   6605:             if ($key =~ /\0accesscontrol$/) {
                   6606:                 if (defined($group)) {
                   6607:                     if ($key !~ m-^\Q$group\E/-) {
                   6608:                         next;
                   6609:                     }
                   6610:                 }
                   6611:                 my ($fullpath) = split(/\0/,$key);
                   6612:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   6613:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   6614:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   6615:                     }
                   6616:                 }
                   6617:             }
                   6618:         }
                   6619:     }
                   6620:     return %access;
                   6621: }
                   6622: 
                   6623: sub modify_access_controls {
                   6624:     my ($file_name,$changes,$domain,$user)=@_;
                   6625:     my ($outcome,$deloutcome);
                   6626:     my %store_permissions;
                   6627:     my %new_values;
                   6628:     my %new_control;
                   6629:     my %translation;
                   6630:     my @deletions = ();
                   6631:     my $now = time;
                   6632:     if (exists($$changes{'activate'})) {
                   6633:         if (ref($$changes{'activate'}) eq 'HASH') {
                   6634:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   6635:             my $numnew = scalar(@newitems);
                   6636:             for (my $i=0; $i<$numnew; $i++) {
                   6637:                 my $newkey = $newitems[$i];
                   6638:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  6639:                 if ($newkey =~ /^\d+:/) { 
                   6640:                     $newkey =~ s/^(\d+)/$newid/;
                   6641:                     $translation{$1} = $newid;
                   6642:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   6643:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   6644:                     $translation{$1} = $newid;
                   6645:                 }
1.749     raeburn  6646:                 $new_values{$file_name."\0".$newkey} = 
                   6647:                                           $$changes{'activate'}{$newitems[$i]};
                   6648:                 $new_control{$newkey} = $now;
                   6649:             }
                   6650:         }
                   6651:     }
                   6652:     my %todelete;
                   6653:     my %changed_items;
                   6654:     foreach my $action ('delete','update') {
                   6655:         if (exists($$changes{$action})) {
                   6656:             if (ref($$changes{$action}) eq 'HASH') {
                   6657:                 foreach my $key (keys(%{$$changes{$action}})) {
                   6658:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   6659:                     if ($action eq 'delete') { 
                   6660:                         $todelete{$itemnum} = 1;
                   6661:                     } else {
                   6662:                         $changed_items{$itemnum} = $key;
                   6663:                     }
                   6664:                 }
1.745     raeburn  6665:             }
                   6666:         }
1.749     raeburn  6667:     }
                   6668:     # get lock on access controls for file.
                   6669:     my $lockhash = {
                   6670:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   6671:                                                        ':'.$env{'user.domain'},
                   6672:                    }; 
                   6673:     my $tries = 0;
                   6674:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6675:    
                   6676:     while (($gotlock ne 'ok') && $tries <3) {
                   6677:         $tries ++;
                   6678:         sleep 1;
                   6679:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6680:     }
                   6681:     if ($gotlock eq 'ok') {
                   6682:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6683:         my ($tmp)=keys(%curr_permissions);
                   6684:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6685:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6686:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6687:             if (ref($curr_controls) eq 'HASH') {
                   6688:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6689:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6690:                     if (defined($todelete{$itemnum})) {
                   6691:                         push(@deletions,$file_name."\0".$control_item);
                   6692:                     } else {
                   6693:                         if (defined($changed_items{$itemnum})) {
                   6694:                             $new_control{$changed_items{$itemnum}} = $now;
                   6695:                             push(@deletions,$file_name."\0".$control_item);
                   6696:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6697:                         } else {
                   6698:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6699:                         }
                   6700:                     }
1.745     raeburn  6701:                 }
                   6702:             }
                   6703:         }
1.970     raeburn  6704:         my ($group);
                   6705:         if (&is_course($domain,$user)) {
                   6706:             ($group,my $file) = split(/\//,$file_name,2);
                   6707:         }
1.749     raeburn  6708:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6709:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6710:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6711:         #  remove lock
                   6712:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6713:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6714:         my $sqlresult =
1.970     raeburn  6715:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  6716:                                     $group);
1.749     raeburn  6717:     } else {
                   6718:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6719:     }
1.749     raeburn  6720:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6721: }
                   6722: 
1.827     raeburn  6723: sub make_public_indefinitely {
                   6724:     my ($requrl) = @_;
                   6725:     my $now = time;
                   6726:     my $action = 'activate';
                   6727:     my $aclnum = 0;
                   6728:     if (&is_portfolio_url($requrl)) {
                   6729:         my (undef,$udom,$unum,$file_name,$group) =
                   6730:             &parse_portfolio_url($requrl);
                   6731:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6732:         my %access_controls = &get_access_controls($current_perms,
                   6733:                                                    $group,$file_name);
                   6734:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6735:             my ($num,$scope,$end,$start) = 
                   6736:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6737:             if ($scope eq 'public') {
                   6738:                 if ($start <= $now && $end == 0) {
                   6739:                     $action = 'none';
                   6740:                 } else {
                   6741:                     $action = 'update';
                   6742:                     $aclnum = $num;
                   6743:                 }
                   6744:                 last;
                   6745:             }
                   6746:         }
                   6747:         if ($action eq 'none') {
                   6748:              return 'ok';
                   6749:         } else {
                   6750:             my %changes;
                   6751:             my $newend = 0;
                   6752:             my $newstart = $now;
                   6753:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6754:             $changes{$action}{$newkey} = {
                   6755:                 type => 'public',
                   6756:                 time => {
                   6757:                     start => $newstart,
                   6758:                     end   => $newend,
                   6759:                 },
                   6760:             };
                   6761:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6762:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6763:             return $outcome;
                   6764:         }
                   6765:     } else {
                   6766:         return 'invalid';
                   6767:     }
                   6768: }
                   6769: 
1.745     raeburn  6770: #------------------------------------------------------Get Marked as Read Only
                   6771: 
                   6772: sub get_marked_as_readonly {
                   6773:     my ($domain,$user,$what,$group) = @_;
                   6774:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6775:     my @readonly_files;
1.629     banghart 6776:     my $cmp1=$what;
                   6777:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6778:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6779:         if (defined($group)) {
                   6780:             if ($file_name !~ m-^\Q$group\E/-) {
                   6781:                 next;
                   6782:             }
                   6783:         }
1.561     banghart 6784:         if (ref($value) eq "ARRAY"){
                   6785:             foreach my $stored_what (@{$value}) {
1.629     banghart 6786:                 my $cmp2=$stored_what;
1.759     albertel 6787:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6788:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6789:                 }
1.629     banghart 6790:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6791:                     push(@readonly_files, $file_name);
1.745     raeburn  6792:                     last;
1.563     banghart 6793:                 } elsif (!defined($what)) {
                   6794:                     push(@readonly_files, $file_name);
1.745     raeburn  6795:                     last;
1.561     banghart 6796:                 }
                   6797:             }
1.745     raeburn  6798:         }
1.561     banghart 6799:     }
                   6800:     return @readonly_files;
                   6801: }
1.577     banghart 6802: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6803: 
1.577     banghart 6804: sub get_marked_as_readonly_hash {
1.745     raeburn  6805:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6806:     my %readonly_files;
1.745     raeburn  6807:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6808:         if (defined($group)) {
                   6809:             if ($file_name !~ m-^\Q$group\E/-) {
                   6810:                 next;
                   6811:             }
                   6812:         }
1.577     banghart 6813:         if (ref($value) eq "ARRAY"){
                   6814:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6815:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6816:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6817:                         if ($lock_descriptor eq 'graded') {
                   6818:                             $readonly_files{$file_name} = 'graded';
                   6819:                         } elsif ($lock_descriptor eq 'handback') {
                   6820:                             $readonly_files{$file_name} = 'handback';
                   6821:                         } else {
                   6822:                             if (!exists($readonly_files{$file_name})) {
                   6823:                                 $readonly_files{$file_name} = 'locked';
                   6824:                             }
                   6825:                         }
1.745     raeburn  6826:                     }
1.750     banghart 6827:                 } 
1.577     banghart 6828:             }
                   6829:         } 
                   6830:     }
                   6831:     return %readonly_files;
                   6832: }
1.559     banghart 6833: # ------------------------------------------------------------ Unmark as Read Only
                   6834: 
                   6835: sub unmark_as_readonly {
1.629     banghart 6836:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6837:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6838:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6839:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6840:     my $symb_crs = $what;
                   6841:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6842:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6843:     my ($tmp)=keys(%current_permissions);
                   6844:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6845:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6846:     foreach my $file (@readonly_files) {
1.759     albertel 6847: 	my $clean_file = &declutter_portfile($file);
                   6848: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6849: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6850:         my @new_locks;
                   6851:         my @del_keys;
                   6852:         if (ref($current_locks) eq "ARRAY"){
                   6853:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6854:                 my $compare=$locker;
1.749     raeburn  6855:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6856:                     $compare=join('',@{$locker});
1.746     raeburn  6857:                     if ($compare ne $symb_crs) {
                   6858:                         push(@new_locks, $locker);
                   6859:                     }
1.563     banghart 6860:                 }
                   6861:             }
1.650     albertel 6862:             if (scalar(@new_locks) > 0) {
1.563     banghart 6863:                 $current_permissions{$file} = \@new_locks;
                   6864:             } else {
                   6865:                 push(@del_keys, $file);
1.613     albertel 6866:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6867:                 delete($current_permissions{$file});
1.563     banghart 6868:             }
                   6869:         }
1.561     banghart 6870:     }
1.613     albertel 6871:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6872:     return;
                   6873: }
1.512     banghart 6874: 
1.17      www      6875: # ------------------------------------------------------------ Directory lister
                   6876: 
                   6877: sub dirlist {
1.955     raeburn  6878:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      6879:     $uri=~s/^\///;
                   6880:     $uri=~s/\/$//;
1.253     stredwic 6881:     my ($udom, $uname);
1.955     raeburn  6882:     if ($getuserdir) {
1.253     stredwic 6883:         $udom = $userdomain;
                   6884:         $uname = $username;
1.955     raeburn  6885:     } else {
                   6886:         (undef,$udom,$uname)=split(/\//,$uri);
                   6887:         if(defined($userdomain)) {
                   6888:             $udom = $userdomain;
                   6889:         }
                   6890:         if(defined($username)) {
                   6891:             $uname = $username;
                   6892:         }
1.253     stredwic 6893:     }
1.955     raeburn  6894:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 6895: 
1.955     raeburn  6896:     $dirRoot = $perlvar{'lonDocRoot'};
                   6897:     if (defined($getpropath)) {
                   6898:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 6899:         $dirRoot =~ s/\/$//;
1.955     raeburn  6900:     } elsif (defined($getuserdir)) {
                   6901:         my $subdir=$uname.'__';
                   6902:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6903:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   6904:                    ."/$udom/$subdir/$uname";
                   6905:     } elsif (defined($alternateRoot)) {
                   6906:         $dirRoot = $alternateRoot;
1.751     banghart 6907:     }
1.253     stredwic 6908: 
                   6909:     if($udom) {
                   6910:         if($uname) {
1.955     raeburn  6911:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  6912:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  6913:                               .':'.&escape($uname).':'.&escape($udom),
                   6914:                               &homeserver($uname,$udom));
                   6915:             if ($listing eq 'unknown_cmd') {
                   6916:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6917:                                   &homeserver($uname,$udom));
                   6918:             } else {
                   6919:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6920:             }
1.605     matthew  6921:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6922:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6923: 				  &homeserver($uname,$udom));
1.605     matthew  6924:                 @listing_results = split(/:/,$listing);
                   6925:             } else {
                   6926:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6927:             }
                   6928:             return @listing_results;
1.955     raeburn  6929:         } elsif(!$alternateRoot) {
1.800     albertel 6930:             my %allusers;
1.841     albertel 6931: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  6932:  	    foreach my $tryserver (keys(%servers)) {
                   6933:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   6934:                                   &escape($udom),$tryserver);
                   6935:                 if ($listing eq 'unknown_cmd') {
                   6936: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6937: 				      $udom, $tryserver);
                   6938:                 } else {
                   6939:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6940:                 }
1.841     albertel 6941: 		if ($listing eq 'unknown_cmd') {
                   6942: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6943: 				      $udom, $tryserver);
                   6944: 		    @listing_results = split(/:/,$listing);
                   6945: 		} else {
                   6946: 		    @listing_results =
                   6947: 			map { &unescape($_); } split(/:/,$listing);
                   6948: 		}
                   6949: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6950: 		    $listing_results[0] ne 'empty'       &&
                   6951: 		    $listing_results[0] ne 'con_lost') {
                   6952: 		    foreach my $line (@listing_results) {
                   6953: 			my ($entry) = split(/&/,$line,2);
                   6954: 			$allusers{$entry} = 1;
                   6955: 		    }
                   6956: 		}
1.253     stredwic 6957:             }
                   6958:             my $alluserstr='';
1.800     albertel 6959:             foreach my $user (sort(keys(%allusers))) {
                   6960:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6961:             }
                   6962:             $alluserstr=~s/:$//;
                   6963:             return split(/:/,$alluserstr);
                   6964:         } else {
1.800     albertel 6965:             return ('missing user name');
1.253     stredwic 6966:         }
1.955     raeburn  6967:     } elsif(!defined($getpropath)) {
1.841     albertel 6968:         my @all_domains = sort(&all_domains());
1.955     raeburn  6969:         foreach my $domain (@all_domains) {
                   6970:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6971:         }
                   6972:         return @all_domains;
                   6973:     } else {
1.800     albertel 6974:         return ('missing domain');
1.275     stredwic 6975:     }
                   6976: }
                   6977: 
                   6978: # --------------------------------------------- GetFileTimestamp
                   6979: # This function utilizes dirlist and returns the date stamp for
                   6980: # when it was last modified.  It will also return an error of -1
                   6981: # if an error occurs
                   6982: 
                   6983: sub GetFileTimestamp {
1.955     raeburn  6984:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 6985:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6986:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  6987:     my ($fileStat) = 
                   6988:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   6989:                                  undef,$getuserdir);
1.275     stredwic 6990:     my @stats = split('&', $fileStat);
                   6991:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6992:         # @stats contains first the filename, then the stat output
                   6993:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6994:     } else {
                   6995:         return -1;
1.253     stredwic 6996:     }
1.26      www      6997: }
                   6998: 
1.712     albertel 6999: sub stat_file {
                   7000:     my ($uri) = @_;
1.787     albertel 7001:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 7002: 
1.955     raeburn  7003:     my ($udom,$uname,$file);
1.712     albertel 7004:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   7005: 	($udom,$uname,$file) =
1.811     albertel 7006: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 7007: 	$file = 'userfiles/'.$file;
                   7008:     }
                   7009:     if ($uri =~ m-^/res/-) {
                   7010: 	($udom,$uname) = 
1.807     albertel 7011: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 7012: 	$file = $uri;
                   7013:     }
                   7014: 
                   7015:     if (!$udom || !$uname || !$file) {
                   7016: 	# unable to handle the uri
                   7017: 	return ();
                   7018:     }
1.956     raeburn  7019:     my $getpropath;
                   7020:     if ($file =~ /^userfiles\//) {
                   7021:         $getpropath = 1;
                   7022:     }
1.955     raeburn  7023:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 7024:     my @stats = split('&', $result);
1.721     banghart 7025:     
1.712     albertel 7026:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   7027: 	shift(@stats); #filename is first
                   7028: 	return @stats;
                   7029:     }
                   7030:     return ();
                   7031: }
                   7032: 
1.26      www      7033: # -------------------------------------------------------- Value of a Condition
                   7034: 
1.713     albertel 7035: # gets the value of a specific preevaluated condition
                   7036: #    stored in the string  $env{user.state.<cid>}
                   7037: # or looks up a condition reference in the bighash and if if hasn't
                   7038: # already been evaluated recurses into docondval to get the value of
                   7039: # the condition, then memoizing it to 
                   7040: #   $env{user.state.<cid>.<condition>}
1.40      www      7041: sub directcondval {
                   7042:     my $number=shift;
1.620     albertel 7043:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 7044: 	&Apache::lonuserstate::evalstate();
                   7045:     }
1.713     albertel 7046:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   7047: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   7048:     } elsif ($number =~ /^_/) {
                   7049: 	my $sub_condition;
                   7050: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7051: 		&GDBM_READER(),0640)) {
                   7052: 	    $sub_condition=$bighash{'conditions'.$number};
                   7053: 	    untie(%bighash);
                   7054: 	}
                   7055: 	my $value = &docondval($sub_condition);
1.949     raeburn  7056: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 7057: 	return $value;
                   7058:     }
1.620     albertel 7059:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   7060:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      7061:     } else {
                   7062:        return 2;
                   7063:     }
                   7064: }
                   7065: 
1.713     albertel 7066: # get the collection of conditions for this resource
1.26      www      7067: sub condval {
                   7068:     my $condidx=shift;
1.54      www      7069:     my $allpathcond='';
1.713     albertel 7070:     foreach my $cond (split(/\|/,$condidx)) {
                   7071: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   7072: 	    $allpathcond.=
                   7073: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   7074: 	}
1.191     harris41 7075:     }
1.54      www      7076:     $allpathcond=~s/\|$//;
1.713     albertel 7077:     return &docondval($allpathcond);
                   7078: }
                   7079: 
                   7080: #evaluates an expression of conditions
                   7081: sub docondval {
                   7082:     my ($allpathcond) = @_;
                   7083:     my $result=0;
                   7084:     if ($env{'request.course.id'}
                   7085: 	&& defined($allpathcond)) {
                   7086: 	my $operand='|';
                   7087: 	my @stack;
                   7088: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   7089: 	    if ($chunk eq '(') {
                   7090: 		push @stack,($operand,$result);
                   7091: 	    } elsif ($chunk eq ')') {
                   7092: 		my $before=pop @stack;
                   7093: 		if (pop @stack eq '&') {
                   7094: 		    $result=$result>$before?$before:$result;
                   7095: 		} else {
                   7096: 		    $result=$result>$before?$result:$before;
                   7097: 		}
                   7098: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   7099: 		$operand=$chunk;
                   7100: 	    } else {
                   7101: 		my $new=directcondval($chunk);
                   7102: 		if ($operand eq '&') {
                   7103: 		    $result=$result>$new?$new:$result;
                   7104: 		} else {
                   7105: 		    $result=$result>$new?$result:$new;
                   7106: 		}
                   7107: 	    }
                   7108: 	}
1.26      www      7109:     }
                   7110:     return $result;
1.421     albertel 7111: }
                   7112: 
                   7113: # ---------------------------------------------------- Devalidate courseresdata
                   7114: 
                   7115: sub devalidatecourseresdata {
                   7116:     my ($coursenum,$coursedomain)=@_;
                   7117:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7118:     &devalidate_cache_new('courseres',$hashid);
1.28      www      7119: }
                   7120: 
1.763     www      7121: 
1.200     www      7122: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     7123: #
                   7124: #  Parameters:
                   7125: #      $coursenum    - Number of the course.
                   7126: #      $coursedomain - Domain at which the course was created.
                   7127: #  Returns:
                   7128: #     A hash of the course parameters along (I think) with timestamps
                   7129: #     and version info.
1.877     foxr     7130: 
1.624     albertel 7131: sub get_courseresdata {
                   7132:     my ($coursenum,$coursedomain)=@_;
1.200     www      7133:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   7134:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7135:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 7136:     my %dumpreply;
1.417     albertel 7137:     unless (defined($cached)) {
1.624     albertel 7138: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 7139: 	$result=\%dumpreply;
1.251     albertel 7140: 	my ($tmp) = keys(%dumpreply);
                   7141: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 7142: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 7143: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   7144: 	    return $tmp;
1.416     albertel 7145: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 7146: 	    $result=undef;
1.599     albertel 7147: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 7148: 	}
                   7149:     }
1.624     albertel 7150:     return $result;
                   7151: }
                   7152: 
1.633     albertel 7153: sub devalidateuserresdata {
                   7154:     my ($uname,$udom)=@_;
                   7155:     my $hashid="$udom:$uname";
                   7156:     &devalidate_cache_new('userres',$hashid);
                   7157: }
                   7158: 
1.624     albertel 7159: sub get_userresdata {
                   7160:     my ($uname,$udom)=@_;
                   7161:     #most student don\'t have any data set, check if there is some data
                   7162:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   7163: 
                   7164:     my $hashid="$udom:$uname";
                   7165:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   7166:     if (!defined($cached)) {
                   7167: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   7168: 	$result=\%resourcedata;
                   7169: 	&do_cache_new('userres',$hashid,$result,600);
                   7170:     }
                   7171:     my ($tmp)=keys(%$result);
                   7172:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   7173: 	return $result;
                   7174:     }
                   7175:     #error 2 occurs when the .db doesn't exist
                   7176:     if ($tmp!~/error: 2 /) {
1.672     albertel 7177: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 7178: 		 " Trying to get resource data for ".
                   7179: 		 $uname." at ".$udom.": ".
                   7180: 		 $tmp."</font>");
                   7181:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 7182: 	#&EXT_cache_set($udom,$uname);
                   7183: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 7184: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 7185:     }
                   7186:     return $tmp;
                   7187: }
1.879     foxr     7188: #----------------------------------------------- resdata - return resource data
                   7189: #  Purpose:
                   7190: #    Return resource data for either users or for a course.
                   7191: #  Parameters:
                   7192: #     $name      - Course/user name.
                   7193: #     $domain    - Name of the domain the user/course is registered on.
                   7194: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   7195: #     @which     - Array of names of resources desired.
                   7196: #  Returns:
                   7197: #     The value of the first reasource in @which that is found in the
                   7198: #     resource hash.
                   7199: #  Exceptional Conditions:
                   7200: #     If the $type passed in is not valid (not the string 'course' or 
                   7201: #     'user', an undefined  reference is returned.
                   7202: #     If none of the resources are found, an undef is returned
1.624     albertel 7203: sub resdata {
                   7204:     my ($name,$domain,$type,@which)=@_;
                   7205:     my $result;
                   7206:     if ($type eq 'course') {
                   7207: 	$result=&get_courseresdata($name,$domain);
                   7208:     } elsif ($type eq 'user') {
                   7209: 	$result=&get_userresdata($name,$domain);
                   7210:     }
                   7211:     if (!ref($result)) { return $result; }    
1.251     albertel 7212:     foreach my $item (@which) {
1.927     albertel 7213: 	if (defined($result->{$item->[0]})) {
                   7214: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 7215: 	}
1.250     albertel 7216:     }
1.291     albertel 7217:     return undef;
1.200     www      7218: }
                   7219: 
1.379     matthew  7220: #
                   7221: # EXT resource caching routines
                   7222: #
                   7223: 
                   7224: sub clear_EXT_cache_status {
1.383     albertel 7225:     &delenv('cache.EXT.');
1.379     matthew  7226: }
                   7227: 
                   7228: sub EXT_cache_status {
                   7229:     my ($target_domain,$target_user) = @_;
1.383     albertel 7230:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 7231:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  7232:         # We know already the user has no data
                   7233:         return 1;
                   7234:     } else {
                   7235:         return 0;
                   7236:     }
                   7237: }
                   7238: 
                   7239: sub EXT_cache_set {
                   7240:     my ($target_domain,$target_user) = @_;
1.383     albertel 7241:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  7242:     #&appenv({$cachename => time});
1.379     matthew  7243: }
                   7244: 
1.28      www      7245: # --------------------------------------------------------- Value of a Variable
1.58      www      7246: sub EXT {
1.715     albertel 7247: 
1.395     albertel 7248:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      7249:     unless ($varname) { return ''; }
1.218     albertel 7250:     #get real user name/domain, courseid and symb
                   7251:     my $courseid;
1.359     albertel 7252:     my $publicuser;
1.427     www      7253:     if ($symbparm) {
                   7254: 	$symbparm=&get_symb_from_alias($symbparm);
                   7255:     }
1.218     albertel 7256:     if (!($uname && $udom)) {
1.790     albertel 7257:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 7258:       if (!$symbparm) {	$symbparm=$cursymb; }
                   7259:     } else {
1.620     albertel 7260: 	$courseid=$env{'request.course.id'};
1.218     albertel 7261:     }
1.48      www      7262:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   7263:     my $rest;
1.320     albertel 7264:     if (defined($therest[0])) {
1.48      www      7265:        $rest=join('.',@therest);
                   7266:     } else {
                   7267:        $rest='';
                   7268:     }
1.320     albertel 7269: 
1.57      www      7270:     my $qualifierrest=$qualifier;
                   7271:     if ($rest) { $qualifierrest.='.'.$rest; }
                   7272:     my $spacequalifierrest=$space;
                   7273:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      7274:     if ($realm eq 'user') {
1.48      www      7275: # --------------------------------------------------------------- user.resource
                   7276: 	if ($space eq 'resource') {
1.651     albertel 7277: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   7278: 		  || defined($Apache::lonhomework::parsing_a_task))
                   7279: 		 &&
1.744     albertel 7280: 		 ($symbparm eq &symbread()) ) {	
                   7281: 		# if we are in the middle of processing the resource the
                   7282: 		# get the value we are planning on committing
                   7283:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   7284:                     return $Apache::lonhomework::results{$qualifierrest};
                   7285:                 } else {
                   7286:                     return $Apache::lonhomework::history{$qualifierrest};
                   7287:                 }
1.335     albertel 7288: 	    } else {
1.359     albertel 7289: 		my %restored;
1.620     albertel 7290: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 7291: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   7292: 		} else {
                   7293: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   7294: 		}
1.335     albertel 7295: 		return $restored{$qualifierrest};
                   7296: 	    }
1.48      www      7297: # ----------------------------------------------------------------- user.access
                   7298:         } elsif ($space eq 'access') {
1.218     albertel 7299: 	    # FIXME - not supporting calls for a specific user
1.48      www      7300:             return &allowed($qualifier,$rest);
                   7301: # ------------------------------------------ user.preferences, user.environment
                   7302:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 7303: 	    if (($uname eq $env{'user.name'}) &&
                   7304: 		($udom eq $env{'user.domain'})) {
                   7305: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 7306: 	    } else {
1.359     albertel 7307: 		my %returnhash;
                   7308: 		if (!$publicuser) {
                   7309: 		    %returnhash=&userenvironment($udom,$uname,
                   7310: 						 $qualifierrest);
                   7311: 		}
1.218     albertel 7312: 		return $returnhash{$qualifierrest};
                   7313: 	    }
1.48      www      7314: # ----------------------------------------------------------------- user.course
                   7315:         } elsif ($space eq 'course') {
1.218     albertel 7316: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 7317:             return $env{join('.',('request.course',$qualifier))};
1.48      www      7318: # ------------------------------------------------------------------- user.role
                   7319:         } elsif ($space eq 'role') {
1.218     albertel 7320: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 7321:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      7322:             if ($qualifier eq 'value') {
                   7323: 		return $role;
                   7324:             } elsif ($qualifier eq 'extent') {
                   7325:                 return $where;
                   7326:             }
                   7327: # ----------------------------------------------------------------- user.domain
                   7328:         } elsif ($space eq 'domain') {
1.218     albertel 7329:             return $udom;
1.48      www      7330: # ------------------------------------------------------------------- user.name
                   7331:         } elsif ($space eq 'name') {
1.218     albertel 7332:             return $uname;
1.48      www      7333: # ---------------------------------------------------- Any other user namespace
1.29      www      7334:         } else {
1.359     albertel 7335: 	    my %reply;
                   7336: 	    if (!$publicuser) {
                   7337: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   7338: 	    }
                   7339: 	    return $reply{$qualifierrest};
1.48      www      7340:         }
1.236     www      7341:     } elsif ($realm eq 'query') {
                   7342: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 7343:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   7344: 						[$spacequalifierrest]);
1.620     albertel 7345: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      7346:    } elsif ($realm eq 'request') {
1.48      www      7347: # ------------------------------------------------------------- request.browser
                   7348:         if ($space eq 'browser') {
1.430     www      7349: 	    if ($qualifier eq 'textremote') {
1.676     albertel 7350: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      7351: 		    return 1;
                   7352: 		} else {
                   7353: 		    return 0;
                   7354: 		}
                   7355: 	    } else {
1.620     albertel 7356: 		return $env{'browser.'.$qualifier};
1.430     www      7357: 	    }
1.57      www      7358: # ------------------------------------------------------------ request.filename
                   7359:         } else {
1.620     albertel 7360:             return $env{'request.'.$spacequalifierrest};
1.29      www      7361:         }
1.28      www      7362:     } elsif ($realm eq 'course') {
1.48      www      7363: # ---------------------------------------------------------- course.description
1.620     albertel 7364:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      7365:     } elsif ($realm eq 'resource') {
1.165     www      7366: 
1.620     albertel 7367: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 7368: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   7369: 	}
1.693     albertel 7370: 
                   7371: 	if ($space eq 'title') {
                   7372: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   7373: 	    return &gettitle($symbparm);
                   7374: 	}
                   7375: 	
                   7376: 	if ($space eq 'map') {
                   7377: 	    my ($map) = &decode_symb($symbparm);
                   7378: 	    return &symbread($map);
                   7379: 	}
1.905     albertel 7380: 	if ($space eq 'filename') {
                   7381: 	    if ($symbparm) {
                   7382: 		return &clutter((&decode_symb($symbparm))[2]);
                   7383: 	    }
                   7384: 	    return &hreflocation('',$env{'request.filename'});
                   7385: 	}
1.693     albertel 7386: 
                   7387: 	my ($section, $group, @groups);
1.593     albertel 7388: 	my ($courselevelm,$courselevel);
1.539     albertel 7389: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7390: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      7391: 
1.218     albertel 7392: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      7393: 
1.60      www      7394: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 7395: 	    my $symbp=$symbparm;
1.735     albertel 7396: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 7397: 
                   7398: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   7399: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   7400: 
1.620     albertel 7401: 	    if (($env{'user.name'} eq $uname) &&
                   7402: 		($env{'user.domain'} eq $udom)) {
                   7403: 		$section=$env{'request.course.sec'};
1.733     raeburn  7404:                 @groups = split(/:/,$env{'request.course.groups'});  
                   7405:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 7406: 	    } else {
1.539     albertel 7407: 		if (! defined($usection)) {
1.551     albertel 7408: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 7409: 		} else {
                   7410: 		    $section = $usection;
                   7411: 		}
1.733     raeburn  7412:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 7413: 	    }
                   7414: 
                   7415: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   7416: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   7417: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   7418: 
1.593     albertel 7419: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 7420: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 7421: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      7422: 
1.60      www      7423: # ----------------------------------------------------------- first, check user
1.624     albertel 7424: 
                   7425: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 7426: 				       ([$courselevelr,'resource'],
                   7427: 					[$courselevelm,'map'     ],
                   7428: 					[$courselevel, 'course'  ]));
1.931     albertel 7429: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      7430: 
1.594     albertel 7431: # ------------------------------------------------ second, check some of course
1.684     raeburn  7432:             my $coursereply;
1.691     raeburn  7433:             if (@groups > 0) {
                   7434:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   7435:                                        $mapparm,$spacequalifierrest);
1.927     albertel 7436:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  7437:             }
1.96      www      7438: 
1.684     raeburn  7439: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 7440: 				  $env{'course.'.$courseid.'.domain'},
                   7441: 				  'course',
                   7442: 				  ([$seclevelr,   'resource'],
                   7443: 				   [$seclevelm,   'map'     ],
                   7444: 				   [$seclevel,    'course'  ],
                   7445: 				   [$courselevelr,'resource']));
                   7446: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      7447: 
1.60      www      7448: # ------------------------------------------------------ third, check map parms
1.218     albertel 7449: 	    my %parmhash=();
                   7450: 	    my $thisparm='';
                   7451: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 7452: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 7453: 		    &GDBM_READER(),0640)) {
1.218     albertel 7454: 		$thisparm=$parmhash{$symbparm};
                   7455: 		untie(%parmhash);
                   7456: 	    }
1.927     albertel 7457: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 7458: 	}
1.594     albertel 7459: # ------------------------------------------ fourth, look in resource metadata
1.71      www      7460: 
1.218     albertel 7461: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 7462: 	my $filename;
                   7463: 	if (!$symbparm) { $symbparm=&symbread(); }
                   7464: 	if ($symbparm) {
1.409     www      7465: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 7466: 	} else {
1.620     albertel 7467: 	    $filename=$env{'request.filename'};
1.282     albertel 7468: 	}
                   7469: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 7470: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 7471: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 7472: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      7473: 
1.927     albertel 7474: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 7475: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7476: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 7477: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   7478: 				     $env{'course.'.$courseid.'.domain'},
                   7479: 				     'course',
1.927     albertel 7480: 				     ([$courselevelm,'map'   ],
                   7481: 				      [$courselevel, 'course']));
                   7482: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 7483: 	}
1.145     www      7484: # ------------------------------------------------------------------ Cascade up
1.218     albertel 7485: 	unless ($space eq '0') {
1.336     albertel 7486: 	    my @parts=split(/_/,$space);
                   7487: 	    my $id=pop(@parts);
                   7488: 	    my $part=join('_',@parts);
                   7489: 	    if ($part eq '') { $part='0'; }
1.927     albertel 7490: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 7491: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  7492: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 7493: 	}
1.395     albertel 7494: 	if ($recurse) { return undef; }
                   7495: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 7496: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      7497: # ---------------------------------------------------- Any other user namespace
                   7498:     } elsif ($realm eq 'environment') {
                   7499: # ----------------------------------------------------------------- environment
1.620     albertel 7500: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   7501: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 7502: 	} else {
1.770     albertel 7503: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   7504: 		return '';
                   7505: 	    }
1.219     albertel 7506: 	    my %returnhash=&userenvironment($udom,$uname,
                   7507: 					    $spacequalifierrest);
                   7508: 	    return $returnhash{$spacequalifierrest};
                   7509: 	}
1.28      www      7510:     } elsif ($realm eq 'system') {
1.48      www      7511: # ----------------------------------------------------------------- system.time
                   7512: 	if ($space eq 'time') {
                   7513: 	    return time;
                   7514:         }
1.696     albertel 7515:     } elsif ($realm eq 'server') {
                   7516: # ----------------------------------------------------------------- system.time
                   7517: 	if ($space eq 'name') {
                   7518: 	    return $ENV{'SERVER_NAME'};
                   7519:         }
1.28      www      7520:     }
1.48      www      7521:     return '';
1.61      www      7522: }
                   7523: 
1.927     albertel 7524: sub get_reply {
                   7525:     my ($reply_value) = @_;
1.940     raeburn  7526:     if (ref($reply_value) eq 'ARRAY') {
                   7527:         if (wantarray) {
                   7528: 	    return @$reply_value;
                   7529:         }
                   7530:         return $reply_value->[0];
                   7531:     } else {
                   7532:         return $reply_value;
1.927     albertel 7533:     }
                   7534: }
                   7535: 
1.691     raeburn  7536: sub check_group_parms {
                   7537:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   7538:     my @groupitems = ();
                   7539:     my $resultitem;
1.927     albertel 7540:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  7541:     foreach my $group (@{$groups}) {
                   7542:         foreach my $level (@levels) {
1.927     albertel 7543:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   7544:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  7545:         }
                   7546:     }
                   7547:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   7548:                             $env{'course.'.$courseid.'.domain'},
                   7549:                                      'course',@groupitems);
                   7550:     return $coursereply;
                   7551: }
                   7552: 
                   7553: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  7554:     my ($courseid,@groups) = @_;
                   7555:     @groups = sort(@groups);
1.691     raeburn  7556:     return @groups;
                   7557: }
                   7558: 
1.395     albertel 7559: sub packages_tab_default {
                   7560:     my ($uri,$varname)=@_;
                   7561:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 7562: 
                   7563:     my (@extension,@specifics,$do_default);
                   7564:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 7565: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 7566: 	if ($pack_type eq 'default') {
                   7567: 	    $do_default=1;
                   7568: 	} elsif ($pack_type eq 'extension') {
                   7569: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 7570: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 7571: 	    # only look at packages defaults for packages that this id is
1.738     albertel 7572: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   7573: 	}
                   7574:     }
                   7575:     # first look for a package that matches the requested part id
                   7576:     foreach my $package (@specifics) {
                   7577: 	my (undef,$pack_type,$pack_part)=@{$package};
                   7578: 	next if ($pack_part ne $part);
                   7579: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7580: 	    return $packagetab{"$pack_type&$name&default"};
                   7581: 	}
                   7582:     }
                   7583:     # look for any possible matching non extension_ package
                   7584:     foreach my $package (@specifics) {
                   7585: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 7586: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7587: 	    return $packagetab{"$pack_type&$name&default"};
                   7588: 	}
1.585     albertel 7589: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 7590: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   7591: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 7592: 	}
                   7593:     }
1.738     albertel 7594:     # look for any posible extension_ match
                   7595:     foreach my $package (@extension) {
                   7596: 	my ($package,$pack_type)=@{$package};
                   7597: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7598: 	    return $packagetab{"$pack_type&$name&default"};
                   7599: 	}
                   7600: 	if (defined($packagetab{$package."&$name&default"})) {
                   7601: 	    return $packagetab{$package."&$name&default"};
                   7602: 	}
                   7603:     }
                   7604:     # look for a global default setting
                   7605:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   7606: 	return $packagetab{"default&$name&default"};
                   7607:     }
1.395     albertel 7608:     return undef;
                   7609: }
                   7610: 
1.334     albertel 7611: sub add_prefix_and_part {
                   7612:     my ($prefix,$part)=@_;
                   7613:     my $keyroot;
                   7614:     if (defined($prefix) && $prefix !~ /^__/) {
                   7615: 	# prefix that has a part already
                   7616: 	$keyroot=$prefix;
                   7617:     } elsif (defined($prefix)) {
                   7618: 	# prefix that is missing a part
                   7619: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   7620:     } else {
                   7621: 	# no prefix at all
                   7622: 	if (defined($part)) { $keyroot='_'.$part; }
                   7623:     }
                   7624:     return $keyroot;
                   7625: }
                   7626: 
1.71      www      7627: # ---------------------------------------------------------------- Get metadata
                   7628: 
1.599     albertel 7629: my %metaentry;
1.71      www      7630: sub metadata {
1.176     www      7631:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      7632:     $uri=&declutter($uri);
1.288     albertel 7633:     # if it is a non metadata possible uri return quickly
1.529     albertel 7634:     if (($uri eq '') || 
                   7635: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 7636: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 7637:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   7638: 	return undef;
                   7639:     }
                   7640:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   7641: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 7642: 	return undef;
1.288     albertel 7643:     }
1.73      www      7644:     my $filename=$uri;
                   7645:     $uri=~s/\.meta$//;
1.172     www      7646: #
                   7647: # Is the metadata already cached?
1.177     www      7648: # Look at timestamp of caching
1.172     www      7649: # Everything is cached by the main uri, libraries are never directly cached
                   7650: #
1.428     albertel 7651:     if (!defined($liburi)) {
1.599     albertel 7652: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 7653: 	if (defined($cached)) { return $result->{':'.$what}; }
                   7654:     }
                   7655:     {
1.172     www      7656: #
                   7657: # Is this a recursive call for a library?
                   7658: #
1.599     albertel 7659: #	if (! exists($metacache{$uri})) {
                   7660: #	    $metacache{$uri}={};
                   7661: #	}
1.924     albertel 7662: 	my $cachetime = 60*60;
1.171     www      7663:         if ($liburi) {
                   7664: 	    $liburi=&declutter($liburi);
                   7665:             $filename=$liburi;
1.401     bowersj2 7666:         } else {
1.599     albertel 7667: 	    &devalidate_cache_new('meta',$uri);
                   7668: 	    undef(%metaentry);
1.401     bowersj2 7669: 	}
1.140     www      7670:         my %metathesekeys=();
1.73      www      7671:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 7672: 	my $metastring;
1.924     albertel 7673: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 7674: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 7675: 	    $metastring = 
1.929     albertel 7676: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 7677: 					  ('grade_target' => 'meta'));
                   7678: 	    $cachetime = 1; # only want this cached in the child not long term
                   7679: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 7680: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 7681: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 7682: 	    $metastring=&getfile($file);
1.489     albertel 7683: 	}
1.208     albertel 7684:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      7685:         my $token;
1.140     www      7686:         undef %metathesekeys;
1.71      www      7687:         while ($token=$parser->get_token) {
1.339     albertel 7688: 	    if ($token->[0] eq 'S') {
                   7689: 		if (defined($token->[2]->{'package'})) {
1.172     www      7690: #
                   7691: # This is a package - get package info
                   7692: #
1.339     albertel 7693: 		    my $package=$token->[2]->{'package'};
                   7694: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7695: 		    if (defined($token->[2]->{'id'})) { 
                   7696: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7697: 		    }
1.599     albertel 7698: 		    if ($metaentry{':packages'}) {
                   7699: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7700: 		    } else {
1.599     albertel 7701: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7702: 		    }
1.736     albertel 7703: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7704: 			my $part=$keyroot;
                   7705: 			$part=~s/^\_//;
1.736     albertel 7706: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7707: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7708: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7709: 			    # ignore package.tab specified default values
                   7710:                             # here &package_tab_default() will fetch those
                   7711: 			    if ($subp eq 'default') { next; }
1.736     albertel 7712: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7713: 			    my $unikey;
                   7714: 			    if ($pack =~ /_0$/) {
                   7715: 				$unikey='parameter_0_'.$name;
                   7716: 				$part=0;
                   7717: 			    } else {
                   7718: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7719: 			    }
1.339     albertel 7720: 			    if ($subp eq 'display') {
                   7721: 				$value.=' [Part: '.$part.']';
                   7722: 			    }
1.599     albertel 7723: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7724: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7725: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7726: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7727: 			    }
1.599     albertel 7728: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7729: 				$metaentry{':'.$unikey}=
                   7730: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7731: 			    }
1.339     albertel 7732: 			}
                   7733: 		    }
                   7734: 		} else {
1.172     www      7735: #
                   7736: # This is not a package - some other kind of start tag
1.339     albertel 7737: #
                   7738: 		    my $entry=$token->[1];
                   7739: 		    my $unikey;
                   7740: 		    if ($entry eq 'import') {
                   7741: 			$unikey='';
                   7742: 		    } else {
                   7743: 			$unikey=$entry;
                   7744: 		    }
                   7745: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7746: 
                   7747: 		    if (defined($token->[2]->{'id'})) { 
                   7748: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7749: 		    }
1.175     www      7750: 
1.339     albertel 7751: 		    if ($entry eq 'import') {
1.175     www      7752: #
                   7753: # Importing a library here
1.339     albertel 7754: #
                   7755: 			if ($depthcount<20) {
                   7756: 			    my $location=$parser->get_text('/import');
                   7757: 			    my $dir=$filename;
                   7758: 			    $dir=~s|[^/]*$||;
                   7759: 			    $location=&filelocation($dir,$location);
1.736     albertel 7760: 			    my $metadata = 
                   7761: 				&metadata($uri,'keys', $location,$unikey,
                   7762: 					  $depthcount+1);
                   7763: 			    foreach my $meta (split(',',$metadata)) {
                   7764: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7765: 				$metathesekeys{$meta}=1;
1.339     albertel 7766: 			    }
                   7767: 			}
                   7768: 		    } else { 
                   7769: 			
                   7770: 			if (defined($token->[2]->{'name'})) { 
                   7771: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7772: 			}
                   7773: 			$metathesekeys{$unikey}=1;
1.736     albertel 7774: 			foreach my $param (@{$token->[3]}) {
                   7775: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7776: 				$token->[2]->{$param};
1.339     albertel 7777: 			}
                   7778: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7779: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7780: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7781: 		 # only ws inside the tag, and not in default, so use default
                   7782: 		 # as value
1.599     albertel 7783: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7784: 			} elsif ( $internaltext =~ /\S/ ) {
                   7785: 		  # something interesting inside the tag
                   7786: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7787: 			} else {
1.908     albertel 7788: 		  # no interesting values, don't set a default
1.339     albertel 7789: 			}
1.172     www      7790: # end of not-a-package not-a-library import
1.339     albertel 7791: 		    }
1.172     www      7792: # end of not-a-package start tag
1.339     albertel 7793: 		}
1.172     www      7794: # the next is the end of "start tag"
1.339     albertel 7795: 	    }
                   7796: 	}
1.483     albertel 7797: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7798: 	$extension = lc($extension);
                   7799: 	if ($extension eq 'htm') { $extension='html'; }
                   7800: 
1.737     albertel 7801: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7802: 	    #no specific packages #how's our extension
                   7803: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7804: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7805: 					 \%metathesekeys);
                   7806: 	}
1.883     albertel 7807: 
                   7808: 	if (!exists($metaentry{':packages'})
                   7809: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7810: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7811: 		#no specific packages well let's get default then
                   7812: 		if ($key!~/^default&/) { next; }
1.488     albertel 7813: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7814: 					     \%metathesekeys);
                   7815: 	    }
                   7816: 	}
1.338     www      7817: # are there custom rights to evaluate
1.599     albertel 7818: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7819: 
1.338     www      7820:     #
                   7821:     # Importing a rights file here
1.339     albertel 7822:     #
                   7823: 	    unless ($depthcount) {
1.599     albertel 7824: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7825: 		my $dir=$filename;
                   7826: 		$dir=~s|[^/]*$||;
                   7827: 		$location=&filelocation($dir,$location);
1.736     albertel 7828: 		my $rights_metadata =
                   7829: 		    &metadata($uri,'keys',$location,'_rights',
                   7830: 			      $depthcount+1);
                   7831: 		foreach my $rights (split(',',$rights_metadata)) {
                   7832: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7833: 		    $metathesekeys{$rights}=1;
1.339     albertel 7834: 		}
                   7835: 	    }
                   7836: 	}
1.737     albertel 7837: 	# uniqifiy package listing
                   7838: 	my %seen;
                   7839: 	my @uniq_packages =
                   7840: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7841: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7842: 
                   7843: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7844: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7845: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7846: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7847: # this is the end of "was not already recently cached
1.71      www      7848:     }
1.599     albertel 7849:     return $metaentry{':'.$what};
1.261     albertel 7850: }
                   7851: 
1.488     albertel 7852: sub metadata_create_package_def {
1.483     albertel 7853:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7854:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7855:     if ($subp eq 'default') { next; }
                   7856:     
1.599     albertel 7857:     if (defined($metaentry{':packages'})) {
                   7858: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7859:     } else {
1.599     albertel 7860: 	$metaentry{':packages'}=$package;
1.483     albertel 7861:     }
                   7862:     my $value=$packagetab{$key};
                   7863:     my $unikey;
                   7864:     $unikey='parameter_0_'.$name;
1.599     albertel 7865:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7866:     $$metathesekeys{$unikey}=1;
1.599     albertel 7867:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7868: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7869:     }
1.599     albertel 7870:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7871: 	$metaentry{':'.$unikey}=
                   7872: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7873:     }
                   7874: }
                   7875: 
1.261     albertel 7876: sub metadata_generate_part0 {
                   7877:     my ($metadata,$metacache,$uri) = @_;
                   7878:     my %allnames;
1.737     albertel 7879:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7880: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7881: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7882: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7883: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7884: 	    $allnames{$name}=$part;
                   7885: 	  }
                   7886: 	}
                   7887:     }
                   7888:     foreach my $name (keys(%allnames)) {
                   7889:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7890:       my $key=":parameter_0_$name";
1.261     albertel 7891:       $$metacache{"$key.part"}='0';
                   7892:       $$metacache{"$key.name"}=$name;
1.428     albertel 7893:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7894: 					   $allnames{$name}.'_'.$name.
                   7895: 					   '.type'};
1.428     albertel 7896:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7897: 			     '.display'};
1.644     www      7898:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7899:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7900:       $$metacache{"$key.display"}=$olddis;
                   7901:     }
1.71      www      7902: }
                   7903: 
1.764     albertel 7904: # ------------------------------------------------------ Devalidate title cache
                   7905: 
                   7906: sub devalidate_title_cache {
                   7907:     my ($url)=@_;
                   7908:     if (!$env{'request.course.id'}) { return; }
                   7909:     my $symb=&symbread($url);
                   7910:     if (!$symb) { return; }
                   7911:     my $key=$env{'request.course.id'}."\0".$symb;
                   7912:     &devalidate_cache_new('title',$key);
                   7913: }
                   7914: 
1.301     www      7915: # ------------------------------------------------- Get the title of a resource
                   7916: 
                   7917: sub gettitle {
                   7918:     my $urlsymb=shift;
                   7919:     my $symb=&symbread($urlsymb);
1.534     albertel 7920:     if ($symb) {
1.620     albertel 7921: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7922: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7923: 	if (defined($cached)) { 
                   7924: 	    return $result;
                   7925: 	}
1.534     albertel 7926: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7927: 	my $title='';
1.907     albertel 7928: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7929: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7930: 	} else {
                   7931: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7932: 		    &GDBM_READER(),0640)) {
                   7933: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7934: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7935: 		untie(%bighash);
                   7936: 	    }
1.534     albertel 7937: 	}
                   7938: 	$title=~s/\&colon\;/\:/gs;
                   7939: 	if ($title) {
1.599     albertel 7940: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7941: 	}
                   7942: 	$urlsymb=$url;
                   7943:     }
                   7944:     my $title=&metadata($urlsymb,'title');
                   7945:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7946:     return $title;
1.301     www      7947: }
1.613     albertel 7948: 
1.614     albertel 7949: sub get_slot {
                   7950:     my ($which,$cnum,$cdom)=@_;
                   7951:     if (!$cnum || !$cdom) {
1.790     albertel 7952: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7953: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7954: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7955:     }
1.703     albertel 7956:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7957:     my %slotinfo;
                   7958:     if (exists($remembered{$key})) {
                   7959: 	$slotinfo{$which} = $remembered{$key};
                   7960:     } else {
                   7961: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7962: 	&Apache::lonhomework::showhash(%slotinfo);
                   7963: 	my ($tmp)=keys(%slotinfo);
                   7964: 	if ($tmp=~/^error:/) { return (); }
                   7965: 	$remembered{$key} = $slotinfo{$which};
                   7966:     }
1.616     albertel 7967:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7968: 	return %{$slotinfo{$which}};
                   7969:     }
                   7970:     return $slotinfo{$which};
1.614     albertel 7971: }
1.31      www      7972: # ------------------------------------------------- Update symbolic store links
                   7973: 
                   7974: sub symblist {
                   7975:     my ($mapname,%newhash)=@_;
1.438     www      7976:     $mapname=&deversion(&declutter($mapname));
1.31      www      7977:     my %hash;
1.620     albertel 7978:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7979:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7980:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  7981: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 7982: 		next if ($url eq 'last_known'
                   7983: 			 && $env{'form.no_update_last_known'});
                   7984: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7985: 						    $newhash{$url}->[1],
                   7986: 						    $newhash{$url}->[0]);
1.191     harris41 7987:             }
1.31      www      7988:             if (untie(%hash)) {
                   7989: 		return 'ok';
                   7990:             }
                   7991:         }
                   7992:     }
                   7993:     return 'error';
1.212     www      7994: }
                   7995: 
                   7996: # --------------------------------------------------------------- Verify a symb
                   7997: 
                   7998: sub symbverify {
1.510     www      7999:     my ($symb,$thisurl)=@_;
                   8000:     my $thisfn=$thisurl;
1.439     www      8001:     $thisfn=&declutter($thisfn);
1.215     www      8002: # direct jump to resource in page or to a sequence - will construct own symbs
                   8003:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   8004: # check URL part
1.409     www      8005:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      8006: 
1.431     www      8007:     unless ($url eq $thisfn) { return 0; }
1.213     www      8008: 
1.216     www      8009:     $symb=&symbclean($symb);
1.510     www      8010:     $thisurl=&deversion($thisurl);
1.439     www      8011:     $thisfn=&deversion($thisfn);
1.213     www      8012: 
                   8013:     my %bighash;
                   8014:     my $okay=0;
1.431     www      8015: 
1.620     albertel 8016:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8017:                             &GDBM_READER(),0640)) {
1.510     www      8018:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      8019:         unless ($ids) { 
1.510     www      8020:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      8021:         }
                   8022:         if ($ids) {
                   8023: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 8024: 	    foreach my $id (split(/\,/,$ids)) {
                   8025: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      8026:                if (
                   8027:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   8028:    eq $symb) { 
1.620     albertel 8029: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 8030: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 8031: 		       $okay=1; 
                   8032: 		   }
                   8033: 	       }
1.216     www      8034: 	   }
                   8035:         }
1.213     www      8036: 	untie(%bighash);
                   8037:     }
                   8038:     return $okay;
1.31      www      8039: }
                   8040: 
1.210     www      8041: # --------------------------------------------------------------- Clean-up symb
                   8042: 
                   8043: sub symbclean {
                   8044:     my $symb=shift;
1.568     albertel 8045:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      8046: # remove version from map
                   8047:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      8048: 
1.210     www      8049: # remove version from URL
                   8050:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      8051: 
1.507     www      8052: # remove wrapper
                   8053: 
1.510     www      8054:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 8055:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      8056:     return $symb;
1.409     www      8057: }
                   8058: 
                   8059: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 8060: 
                   8061: sub encode_symb {
                   8062:     my ($map,$resid,$url)=@_;
                   8063:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   8064: }
1.409     www      8065: 
                   8066: sub decode_symb {
1.568     albertel 8067:     my $symb=shift;
                   8068:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   8069:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      8070:     return (&fixversion($map),$resid,&fixversion($url));
                   8071: }
                   8072: 
                   8073: sub fixversion {
                   8074:     my $fn=shift;
1.609     banghart 8075:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      8076:     my %bighash;
                   8077:     my $uri=&clutter($fn);
1.620     albertel 8078:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      8079: # is this cached?
1.599     albertel 8080:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      8081:     if (defined($cached)) { return $result; }
                   8082: # unfortunately not cached, or expired
1.620     albertel 8083:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      8084: 	    &GDBM_READER(),0640)) {
                   8085:  	if ($bighash{'version_'.$uri}) {
                   8086:  	    my $version=$bighash{'version_'.$uri};
1.444     www      8087:  	    unless (($version eq 'mostrecent') || 
                   8088: 		    ($version==&getversion($uri))) {
1.440     www      8089:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   8090:  	    }
                   8091:  	}
                   8092:  	untie %bighash;
1.413     www      8093:     }
1.599     albertel 8094:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      8095: }
                   8096: 
                   8097: sub deversion {
                   8098:     my $url=shift;
                   8099:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   8100:     return $url;
1.210     www      8101: }
                   8102: 
1.31      www      8103: # ------------------------------------------------------ Return symb list entry
                   8104: 
                   8105: sub symbread {
1.249     www      8106:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 8107:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 8108:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      8109: # no filename provided? try from environment
1.44      www      8110:     unless ($thisfn) {
1.620     albertel 8111:         if ($env{'request.symb'}) {
                   8112: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 8113: 	}
1.620     albertel 8114: 	$thisfn=$env{'request.filename'};
1.44      www      8115:     }
1.569     albertel 8116:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      8117: # is that filename actually a symb? Verify, clean, and return
                   8118:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 8119: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 8120: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 8121: 	}
1.242     www      8122:     }
1.44      www      8123:     $thisfn=declutter($thisfn);
1.31      www      8124:     my %hash;
1.37      www      8125:     my %bighash;
                   8126:     my $syval='';
1.620     albertel 8127:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  8128:         my $targetfn = $thisfn;
1.609     banghart 8129:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  8130:             $targetfn = 'adm/wrapper/'.$thisfn;
                   8131:         }
1.687     albertel 8132: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   8133: 	    $targetfn=$1;
                   8134: 	}
1.620     albertel 8135:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8136:                       &GDBM_READER(),0640)) {
1.481     raeburn  8137: 	    $syval=$hash{$targetfn};
1.37      www      8138:             untie(%hash);
                   8139:         }
                   8140: # ---------------------------------------------------------- There was an entry
                   8141:         if ($syval) {
1.601     albertel 8142: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 8143: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  8144: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 8145: 		    #return $env{$cache_str}='';
1.601     albertel 8146: 		#}    
                   8147: 		#$syval.=$1;
                   8148: 	    #}
1.37      www      8149:         } else {
                   8150: # ------------------------------------------------------- Was not in symb table
1.620     albertel 8151:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8152:                             &GDBM_READER(),0640)) {
1.37      www      8153: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      8154:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      8155:               unless ($ids) { 
                   8156:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      8157:               }
                   8158:               unless ($ids) {
                   8159: # alias?
                   8160: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      8161:               }
1.37      www      8162:               if ($ids) {
                   8163: # ------------------------------------------------------------------- Has ID(s)
                   8164:                  my @possibilities=split(/\,/,$ids);
1.39      www      8165:                  if ($#possibilities==0) {
                   8166: # ----------------------------------------------- There is only one possibility
1.37      www      8167: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 8168: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   8169: 						    $resid,$thisfn);
1.249     www      8170:                  } elsif (!$donotrecurse) {
1.39      www      8171: # ------------------------------------------ There is more than one possibility
                   8172:                      my $realpossible=0;
1.800     albertel 8173:                      foreach my $id (@possibilities) {
                   8174: 			 my $file=$bighash{'src_'.$id};
1.39      www      8175:                          if (&allowed('bre',$file)) {
1.800     albertel 8176:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      8177:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   8178: 				$realpossible++;
1.626     albertel 8179:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   8180: 						    $resid,$thisfn);
1.39      www      8181:                             }
                   8182: 			 }
1.191     harris41 8183:                      }
1.39      www      8184: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      8185:                  } else {
                   8186:                      $syval='';
1.37      www      8187:                  }
                   8188: 	      }
                   8189:               untie(%bighash)
1.481     raeburn  8190:            }
1.31      www      8191:         }
1.62      www      8192:         if ($syval) {
1.620     albertel 8193: 	    return $env{$cache_str}=$syval;
1.62      www      8194:         }
1.31      www      8195:     }
1.949     raeburn  8196:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 8197:     return $env{$cache_str}='';
1.31      www      8198: }
                   8199: 
                   8200: # ---------------------------------------------------------- Return random seed
                   8201: 
1.32      www      8202: sub numval {
                   8203:     my $txt=shift;
                   8204:     $txt=~tr/A-J/0-9/;
                   8205:     $txt=~tr/a-j/0-9/;
                   8206:     $txt=~tr/K-T/0-9/;
                   8207:     $txt=~tr/k-t/0-9/;
                   8208:     $txt=~tr/U-Z/0-5/;
                   8209:     $txt=~tr/u-z/0-5/;
                   8210:     $txt=~s/\D//g;
1.564     albertel 8211:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      8212:     return int($txt);
1.368     albertel 8213: }
                   8214: 
1.484     albertel 8215: sub numval2 {
                   8216:     my $txt=shift;
                   8217:     $txt=~tr/A-J/0-9/;
                   8218:     $txt=~tr/a-j/0-9/;
                   8219:     $txt=~tr/K-T/0-9/;
                   8220:     $txt=~tr/k-t/0-9/;
                   8221:     $txt=~tr/U-Z/0-5/;
                   8222:     $txt=~tr/u-z/0-5/;
                   8223:     $txt=~s/\D//g;
                   8224:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   8225:     my $total;
                   8226:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 8227:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 8228:     return int($total);
                   8229: }
                   8230: 
1.575     albertel 8231: sub numval3 {
                   8232:     use integer;
                   8233:     my $txt=shift;
                   8234:     $txt=~tr/A-J/0-9/;
                   8235:     $txt=~tr/a-j/0-9/;
                   8236:     $txt=~tr/K-T/0-9/;
                   8237:     $txt=~tr/k-t/0-9/;
                   8238:     $txt=~tr/U-Z/0-5/;
                   8239:     $txt=~tr/u-z/0-5/;
                   8240:     $txt=~s/\D//g;
                   8241:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   8242:     my $total;
                   8243:     foreach my $val (@txts) { $total+=$val; }
                   8244:     if ($_64bit) { $total=(($total<<32)>>32); }
                   8245:     return $total;
                   8246: }
                   8247: 
1.675     albertel 8248: sub digest {
                   8249:     my ($data)=@_;
                   8250:     my $digest=&Digest::MD5::md5($data);
                   8251:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   8252:     my ($e,$f);
                   8253:     {
                   8254:         use integer;
                   8255:         $e=($a+$b);
                   8256:         $f=($c+$d);
                   8257:         if ($_64bit) {
                   8258:             $e=(($e<<32)>>32);
                   8259:             $f=(($f<<32)>>32);
                   8260:         }
                   8261:     }
                   8262:     if (wantarray) {
                   8263: 	return ($e,$f);
                   8264:     } else {
                   8265: 	my $g;
                   8266: 	{
                   8267: 	    use integer;
                   8268: 	    $g=($e+$f);
                   8269: 	    if ($_64bit) {
                   8270: 		$g=(($g<<32)>>32);
                   8271: 	    }
                   8272: 	}
                   8273: 	return $g;
                   8274:     }
                   8275: }
                   8276: 
1.368     albertel 8277: sub latest_rnd_algorithm_id {
1.675     albertel 8278:     return '64bit5';
1.366     albertel 8279: }
1.32      www      8280: 
1.503     albertel 8281: sub get_rand_alg {
                   8282:     my ($courseid)=@_;
1.790     albertel 8283:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 8284:     if ($courseid) {
1.620     albertel 8285: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 8286:     }
                   8287:     return &latest_rnd_algorithm_id();
                   8288: }
                   8289: 
1.562     albertel 8290: sub validCODE {
                   8291:     my ($CODE)=@_;
                   8292:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   8293:     return 0;
                   8294: }
                   8295: 
1.491     albertel 8296: sub getCODE {
1.620     albertel 8297:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 8298:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   8299: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   8300: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 8301: 	return $Apache::lonhomework::history{'resource.CODE'};
                   8302:     }
                   8303:     return undef;
                   8304: }
                   8305: 
1.31      www      8306: sub rndseed {
1.155     albertel 8307:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 8308:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 8309:     if (!defined($symb)) {
1.366     albertel 8310: 	unless ($symb=$wsymb) { return time; }
                   8311:     }
                   8312:     if (!$courseid) { $courseid=$wcourseid; }
                   8313:     if (!$domain) { $domain=$wdomain; }
                   8314:     if (!$username) { $username=$wusername }
1.503     albertel 8315:     my $which=&get_rand_alg();
1.803     albertel 8316: 
1.491     albertel 8317:     if (defined(&getCODE())) {
1.675     albertel 8318: 	if ($which eq '64bit5') {
                   8319: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   8320: 	} elsif ($which eq '64bit4') {
1.575     albertel 8321: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   8322: 	} else {
                   8323: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   8324: 	}
1.675     albertel 8325:     } elsif ($which eq '64bit5') {
                   8326: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 8327:     } elsif ($which eq '64bit4') {
                   8328: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 8329:     } elsif ($which eq '64bit3') {
                   8330: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 8331:     } elsif ($which eq '64bit2') {
                   8332: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 8333:     } elsif ($which eq '64bit') {
                   8334: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   8335:     }
                   8336:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   8337: }
                   8338: 
                   8339: sub rndseed_32bit {
                   8340:     my ($symb,$courseid,$domain,$username)=@_;
                   8341:     {
                   8342: 	use integer;
                   8343: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   8344: 	my $symbseed=numval($symb) << 22;
                   8345: 	my $namechck=unpack("%32C*",$username) << 17;
                   8346: 	my $nameseed=numval($username) << 12;
                   8347: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   8348: 	my $courseseed=unpack("%32C*",$courseid);
                   8349: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 8350: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8351: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8352: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 8353: 	return $num;
                   8354:     }
                   8355: }
                   8356: 
                   8357: sub rndseed_64bit {
                   8358:     my ($symb,$courseid,$domain,$username)=@_;
                   8359:     {
                   8360: 	use integer;
                   8361: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   8362: 	my $symbseed=numval($symb) << 10;
                   8363: 	my $namechck=unpack("%32S*",$username);
                   8364: 	
                   8365: 	my $nameseed=numval($username) << 21;
                   8366: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   8367: 	my $courseseed=unpack("%32S*",$courseid);
                   8368: 	
                   8369: 	my $num1=$symbchck+$symbseed+$namechck;
                   8370: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8371: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8372: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8373: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 8374: 	return "$num1,$num2";
1.155     albertel 8375:     }
1.366     albertel 8376: }
                   8377: 
1.443     albertel 8378: sub rndseed_64bit2 {
                   8379:     my ($symb,$courseid,$domain,$username)=@_;
                   8380:     {
                   8381: 	use integer;
                   8382: 	# strings need to be an even # of cahracters long, it it is odd the
                   8383:         # last characters gets thrown away
                   8384: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8385: 	my $symbseed=numval($symb) << 10;
                   8386: 	my $namechck=unpack("%32S*",$username.' ');
                   8387: 	
                   8388: 	my $nameseed=numval($username) << 21;
1.501     albertel 8389: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8390: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8391: 	
                   8392: 	my $num1=$symbchck+$symbseed+$namechck;
                   8393: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8394: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8395: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 8396: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 8397: 	return "$num1,$num2";
                   8398:     }
                   8399: }
                   8400: 
                   8401: sub rndseed_64bit3 {
                   8402:     my ($symb,$courseid,$domain,$username)=@_;
                   8403:     {
                   8404: 	use integer;
                   8405: 	# strings need to be an even # of cahracters long, it it is odd the
                   8406:         # last characters gets thrown away
                   8407: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8408: 	my $symbseed=numval2($symb) << 10;
                   8409: 	my $namechck=unpack("%32S*",$username.' ');
                   8410: 	
                   8411: 	my $nameseed=numval2($username) << 21;
1.443     albertel 8412: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8413: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8414: 	
                   8415: 	my $num1=$symbchck+$symbseed+$namechck;
                   8416: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8417: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8418: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 8419: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8420: 	
1.503     albertel 8421: 	return "$num1:$num2";
1.443     albertel 8422:     }
                   8423: }
                   8424: 
1.575     albertel 8425: sub rndseed_64bit4 {
                   8426:     my ($symb,$courseid,$domain,$username)=@_;
                   8427:     {
                   8428: 	use integer;
                   8429: 	# strings need to be an even # of cahracters long, it it is odd the
                   8430:         # last characters gets thrown away
                   8431: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8432: 	my $symbseed=numval3($symb) << 10;
                   8433: 	my $namechck=unpack("%32S*",$username.' ');
                   8434: 	
                   8435: 	my $nameseed=numval3($username) << 21;
                   8436: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8437: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8438: 	
                   8439: 	my $num1=$symbchck+$symbseed+$namechck;
                   8440: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8441: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8442: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 8443: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8444: 	
                   8445: 	return "$num1:$num2";
                   8446:     }
                   8447: }
                   8448: 
1.675     albertel 8449: sub rndseed_64bit5 {
                   8450:     my ($symb,$courseid,$domain,$username)=@_;
                   8451:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   8452:     return "$num1:$num2";
                   8453: }
                   8454: 
1.366     albertel 8455: sub rndseed_CODE_64bit {
                   8456:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 8457:     {
1.366     albertel 8458: 	use integer;
1.443     albertel 8459: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 8460: 	my $symbseed=numval2($symb);
1.491     albertel 8461: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8462: 	my $CODEseed=numval(&getCODE());
1.443     albertel 8463: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 8464: 	my $num1=$symbseed+$CODEchck;
                   8465: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8466: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8467: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 8468: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8469: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 8470: 	return "$num1:$num2";
1.366     albertel 8471:     }
                   8472: }
                   8473: 
1.575     albertel 8474: sub rndseed_CODE_64bit4 {
                   8475:     my ($symb,$courseid,$domain,$username)=@_;
                   8476:     {
                   8477: 	use integer;
                   8478: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   8479: 	my $symbseed=numval3($symb);
                   8480: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8481: 	my $CODEseed=numval3(&getCODE());
                   8482: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8483: 	my $num1=$symbseed+$CODEchck;
                   8484: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8485: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8486: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 8487: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8488: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   8489: 	return "$num1:$num2";
                   8490:     }
                   8491: }
                   8492: 
1.675     albertel 8493: sub rndseed_CODE_64bit5 {
                   8494:     my ($symb,$courseid,$domain,$username)=@_;
                   8495:     my $code = &getCODE();
                   8496:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   8497:     return "$num1:$num2";
                   8498: }
                   8499: 
1.366     albertel 8500: sub setup_random_from_rndseed {
                   8501:     my ($rndseed)=@_;
1.503     albertel 8502:     if ($rndseed =~/([,:])/) {
                   8503: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 8504: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   8505:     } else {
                   8506: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 8507:     }
1.36      albertel 8508: }
                   8509: 
1.474     albertel 8510: sub latest_receipt_algorithm_id {
1.835     albertel 8511:     return 'receipt3';
1.474     albertel 8512: }
                   8513: 
1.480     www      8514: sub recunique {
                   8515:     my $fucourseid=shift;
                   8516:     my $unique;
1.835     albertel 8517:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   8518: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8519: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      8520:     } else {
                   8521: 	$unique=$perlvar{'lonReceipt'};
                   8522:     }
                   8523:     return unpack("%32C*",$unique);
                   8524: }
                   8525: 
                   8526: sub recprefix {
                   8527:     my $fucourseid=shift;
                   8528:     my $prefix;
1.835     albertel 8529:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   8530: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8531: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      8532:     } else {
                   8533: 	$prefix=$perlvar{'lonHostID'};
                   8534:     }
                   8535:     return unpack("%32C*",$prefix);
                   8536: }
                   8537: 
1.76      www      8538: sub ireceipt {
1.474     albertel 8539:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 8540: 
                   8541:     my $return =&recprefix($fucourseid).'-';
                   8542: 
                   8543:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   8544: 	$env{'request.state'} eq 'construct') {
                   8545: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   8546: 	return $return;
                   8547:     }
                   8548: 
1.76      www      8549:     my $cuname=unpack("%32C*",$funame);
                   8550:     my $cudom=unpack("%32C*",$fudom);
                   8551:     my $cucourseid=unpack("%32C*",$fucourseid);
                   8552:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      8553:     my $cunique=&recunique($fucourseid);
1.474     albertel 8554:     my $cpart=unpack("%32S*",$part);
1.835     albertel 8555:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   8556: 
1.790     albertel 8557: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 8558: 			       
                   8559: 	$return.= ($cunique%$cuname+
                   8560: 		   $cunique%$cudom+
                   8561: 		   $cusymb%$cuname+
                   8562: 		   $cusymb%$cudom+
                   8563: 		   $cucourseid%$cuname+
                   8564: 		   $cucourseid%$cudom+
                   8565: 		   $cpart%$cuname+
                   8566: 		   $cpart%$cudom);
                   8567:     } else {
                   8568: 	$return.= ($cunique%$cuname+
                   8569: 		   $cunique%$cudom+
                   8570: 		   $cusymb%$cuname+
                   8571: 		   $cusymb%$cudom+
                   8572: 		   $cucourseid%$cuname+
                   8573: 		   $cucourseid%$cudom);
                   8574:     }
                   8575:     return $return;
1.76      www      8576: }
                   8577: 
                   8578: sub receipt {
1.474     albertel 8579:     my ($part)=@_;
1.790     albertel 8580:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 8581:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      8582: }
1.260     ng       8583: 
1.790     albertel 8584: sub whichuser {
                   8585:     my ($passedsymb)=@_;
                   8586:     my ($symb,$courseid,$domain,$name,$publicuser);
                   8587:     if (defined($env{'form.grade_symb'})) {
                   8588: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   8589: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   8590: 	if (!$allowed &&
                   8591: 	    exists($env{'request.course.sec'}) &&
                   8592: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   8593: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   8594: 			      '/'.$env{'request.course.sec'});
                   8595: 	}
                   8596: 	if ($allowed) {
                   8597: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   8598: 	    $courseid=$tmp_courseid;
                   8599: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   8600: 	    ($name)=&get_env_multiple('form.grade_username');
                   8601: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   8602: 	}
                   8603:     }
                   8604:     if (!$passedsymb) {
                   8605: 	$symb=&symbread();
                   8606:     } else {
                   8607: 	$symb=$passedsymb;
                   8608:     }
                   8609:     $courseid=$env{'request.course.id'};
                   8610:     $domain=$env{'user.domain'};
                   8611:     $name=$env{'user.name'};
                   8612:     if ($name eq 'public' && $domain eq 'public') {
                   8613: 	if (!defined($env{'form.username'})) {
                   8614: 	    $env{'form.username'}.=time.rand(10000000);
                   8615: 	}
                   8616: 	$name.=$env{'form.username'};
                   8617:     }
                   8618:     return ($symb,$courseid,$domain,$name,$publicuser);
                   8619: 
                   8620: }
                   8621: 
1.36      albertel 8622: # ------------------------------------------------------------ Serves up a file
1.472     albertel 8623: # returns either the contents of the file or 
                   8624: # -1 if the file doesn't exist
1.481     raeburn  8625: #
                   8626: # if the target is a file that was uploaded via DOCS, 
                   8627: # a check will be made to see if a current copy exists on the local server,
                   8628: # if it does this will be served, otherwise a copy will be retrieved from
                   8629: # the home server for the course and stored in /home/httpd/html/userfiles on
                   8630: # the local server.   
1.472     albertel 8631: 
1.36      albertel 8632: sub getfile {
1.538     albertel 8633:     my ($file) = @_;
1.609     banghart 8634:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 8635:     &repcopy($file);
                   8636:     return &readfile($file);
                   8637: }
                   8638: 
                   8639: sub repcopy_userfile {
                   8640:     my ($file)=@_;
1.609     banghart 8641:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 8642:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 8643:     my ($cdom,$cnum,$filename) = 
1.811     albertel 8644: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 8645:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   8646:     if (-e "$file") {
1.828     www      8647: # we already have a local copy, check it out
1.538     albertel 8648: 	my @fileinfo = stat($file);
1.828     www      8649: 	my $rtncode;
                   8650: 	my $info;
1.538     albertel 8651: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 8652: 	if ($lwpresp ne 'ok') {
1.828     www      8653: # there is no such file anymore, even though we had a local copy
1.482     albertel 8654: 	    if ($rtncode eq '404') {
1.538     albertel 8655: 		unlink($file);
1.482     albertel 8656: 	    }
                   8657: 	    return -1;
                   8658: 	}
                   8659: 	if ($info < $fileinfo[9]) {
1.828     www      8660: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  8661: 	    return 'ok';
1.828     www      8662: 	} else {
                   8663: # the file is outdated, get rid of it
                   8664: 	    unlink($file);
1.482     albertel 8665: 	}
1.828     www      8666:     }
                   8667: # one way or the other, at this point, we don't have the file
                   8668: # construct the correct path for the file
                   8669:     my @parts = ($cdom,$cnum); 
                   8670:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   8671: 	push @parts, split(/\//,$1);
                   8672:     }
                   8673:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   8674:     foreach my $part (@parts) {
                   8675: 	$path .= '/'.$part;
                   8676: 	if (!-e $path) {
                   8677: 	    mkdir($path,0770);
1.482     albertel 8678: 	}
                   8679:     }
1.828     www      8680: # now the path exists for sure
                   8681: # get a user agent
                   8682:     my $ua=new LWP::UserAgent;
                   8683:     my $transferfile=$file.'.in.transfer';
                   8684: # FIXME: this should flock
                   8685:     if (-e $transferfile) { return 'ok'; }
                   8686:     my $request;
                   8687:     $uri=~s/^\///;
1.980     raeburn  8688:     my $homeserver = &homeserver($cnum,$cdom);
                   8689:     my $protocol = $protocol{$homeserver};
                   8690:     $protocol = 'http' if ($protocol ne 'https');
                   8691:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      8692:     my $response=$ua->request($request,$transferfile);
                   8693: # did it work?
                   8694:     if ($response->is_error()) {
                   8695: 	unlink($transferfile);
                   8696: 	&logthis("Userfile repcopy failed for $uri");
                   8697: 	return -1;
                   8698:     }
                   8699: # worked, rename the transfer file
                   8700:     rename($transferfile,$file);
1.607     raeburn  8701:     return 'ok';
1.481     raeburn  8702: }
                   8703: 
1.517     albertel 8704: sub tokenwrapper {
                   8705:     my $uri=shift;
1.980     raeburn  8706:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 8707:     $uri=~s|^/||;
1.620     albertel 8708:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8709:     my $token=$1;
1.552     albertel 8710:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8711:     if ($udom && $uname && $file) {
                   8712: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8713:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  8714:         my $homeserver = &homeserver($uname,$udom);
                   8715:         my $protocol = $protocol{$homeserver};
                   8716:         $protocol = 'http' if ($protocol ne 'https');
                   8717:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 8718:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8719:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8720:     } else {
                   8721:         return '/adm/notfound.html';
                   8722:     }
                   8723: }
                   8724: 
1.828     www      8725: # call with reqtype HEAD: get last modification time
                   8726: # call with reqtype GET: get the file contents
                   8727: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8728: #
1.481     raeburn  8729: sub getuploaded {
                   8730:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8731:     $uri=~s/^\///;
1.980     raeburn  8732:     my $homeserver = &homeserver($cnum,$cdom);
                   8733:     my $protocol = $protocol{$homeserver};
                   8734:     $protocol = 'http' if ($protocol ne 'https');
                   8735:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  8736:     my $ua=new LWP::UserAgent;
                   8737:     my $request=new HTTP::Request($reqtype,$uri);
                   8738:     my $response=$ua->request($request);
                   8739:     $$rtncode = $response->code;
1.482     albertel 8740:     if (! $response->is_success()) {
                   8741: 	return 'failed';
                   8742:     }      
                   8743:     if ($reqtype eq 'HEAD') {
1.486     www      8744: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8745:     } elsif ($reqtype eq 'GET') {
                   8746: 	$$info = $response->content;
1.472     albertel 8747:     }
1.482     albertel 8748:     return 'ok';
1.36      albertel 8749: }
                   8750: 
1.481     raeburn  8751: sub readfile {
                   8752:     my $file = shift;
                   8753:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8754:     my $fh;
                   8755:     open($fh,"<$file");
                   8756:     my $a='';
1.800     albertel 8757:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8758:     return $a;
                   8759: }
                   8760: 
1.36      albertel 8761: sub filelocation {
1.590     banghart 8762:     my ($dir,$file) = @_;
                   8763:     my $location;
                   8764:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8765: 
                   8766:     if ($file =~ m-^/adm/-) {
                   8767: 	$file=~s-^/adm/wrapper/-/-;
                   8768: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8769:     }
1.882     albertel 8770: 
1.590     banghart 8771:     if ($file=~m:^/~:) { # is a contruction space reference
                   8772:         $location = $file;
                   8773:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8774:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8775: 	# is a correct contruction space reference
                   8776:         $location = $file;
1.956     raeburn  8777:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   8778:         $location = $file;
1.609     banghart 8779:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8780:         my ($udom,$uname,$filename)=
1.811     albertel 8781:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8782:         my $home=&homeserver($uname,$udom);
                   8783:         my $is_me=0;
                   8784:         my @ids=&current_machine_ids();
                   8785:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8786:         if ($is_me) {
1.955     raeburn  8787:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 8788:         } else {
                   8789:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8790:   	      $udom.'/'.$uname.'/'.$filename;
                   8791:         }
1.882     albertel 8792:     } elsif ($file =~ m-^/adm/-) {
                   8793: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8794:     } else {
                   8795:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8796:         $file=~s:^/res/:/:;
                   8797:         if ( !( $file =~ m:^/:) ) {
                   8798:             $location = $dir. '/'.$file;
                   8799:         } else {
                   8800:             $location = '/home/httpd/html/res'.$file;
                   8801:         }
1.59      albertel 8802:     }
1.590     banghart 8803:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8804:     while ($location=~m{/\.\./}) {
                   8805: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8806: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8807: 	} else {
                   8808: 	    $location=~ s{/\.\./}{/}g;
                   8809: 	}
                   8810:     } #remove dir/..
1.590     banghart 8811:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8812:     return $location;
1.46      www      8813: }
1.36      albertel 8814: 
1.46      www      8815: sub hreflocation {
                   8816:     my ($dir,$file)=@_;
1.980     raeburn  8817:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 8818: 	$file=filelocation($dir,$file);
1.700     albertel 8819:     } elsif ($file=~m-^/adm/-) {
                   8820: 	$file=~s-^/adm/wrapper/-/-;
                   8821: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8822:     }
                   8823:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8824: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8825:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8826: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8827:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8828: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8829: 	    -/uploaded/$1/$2/-x;
1.46      www      8830:     }
1.913     albertel 8831:     if ($file=~ m{^/userfiles/}) {
                   8832: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8833:     }
1.462     albertel 8834:     return $file;
1.465     albertel 8835: }
                   8836: 
                   8837: sub current_machine_domains {
1.853     albertel 8838:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8839: }
                   8840: 
                   8841: sub machine_domains {
                   8842:     my ($hostname) = @_;
1.465     albertel 8843:     my @domains;
1.838     albertel 8844:     my %hostname = &all_hostnames();
1.465     albertel 8845:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8846: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8847: 	if ($hostname eq $name) {
1.844     albertel 8848: 	    push(@domains,&host_domain($id));
1.465     albertel 8849: 	}
                   8850:     }
                   8851:     return @domains;
                   8852: }
                   8853: 
                   8854: sub current_machine_ids {
1.853     albertel 8855:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8856: }
                   8857: 
                   8858: sub machine_ids {
                   8859:     my ($hostname) = @_;
                   8860:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8861:     my @ids;
1.888     albertel 8862:     my %name_to_host = &all_names();
1.889     albertel 8863:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8864: 	return @{ $name_to_host{$hostname} };
                   8865:     }
                   8866:     return;
1.31      www      8867: }
                   8868: 
1.824     raeburn  8869: sub additional_machine_domains {
                   8870:     my @domains;
                   8871:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8872:     while( my $line = <$fh>) {
                   8873:         $line =~ s/\s//g;
                   8874:         push(@domains,$line);
                   8875:     }
                   8876:     return @domains;
                   8877: }
                   8878: 
                   8879: sub default_login_domain {
                   8880:     my $domain = $perlvar{'lonDefDomain'};
                   8881:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8882:     foreach my $posdom (&current_machine_domains(),
                   8883:                         &additional_machine_domains()) {
                   8884:         if (lc($posdom) eq lc($testdomain)) {
                   8885:             $domain=$posdom;
                   8886:             last;
                   8887:         }
                   8888:     }
                   8889:     return $domain;
                   8890: }
                   8891: 
1.31      www      8892: # ------------------------------------------------------------- Declutters URLs
                   8893: 
                   8894: sub declutter {
                   8895:     my $thisfn=shift;
1.569     albertel 8896:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8897:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8898:     $thisfn=~s/^\///;
1.697     albertel 8899:     $thisfn=~s|^adm/wrapper/||;
                   8900:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8901:     $thisfn=~s/^res\///;
1.235     www      8902:     $thisfn=~s/\?.+$//;
1.268     www      8903:     return $thisfn;
                   8904: }
                   8905: 
                   8906: # ------------------------------------------------------------- Clutter up URLs
                   8907: 
                   8908: sub clutter {
                   8909:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8910:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8911: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8912:        $thisfn='/res'.$thisfn; 
                   8913:     }
1.694     albertel 8914:     if ($thisfn !~m|/adm|) {
1.695     albertel 8915: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8916: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8917: 	} else {
                   8918: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8919: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8920: 	    if ($embstyle eq 'ssi'
                   8921: 		|| ($embstyle eq 'hdn')
                   8922: 		|| ($embstyle eq 'rat')
                   8923: 		|| ($embstyle eq 'prv')
                   8924: 		|| ($embstyle eq 'ign')) {
                   8925: 		#do nothing with these
                   8926: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8927: 		|| ($embstyle eq 'emb')
                   8928: 		|| ($embstyle eq 'wrp')) {
                   8929: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8930: 	    } elsif ($embstyle eq 'unk'
                   8931: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8932: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8933: 	    } else {
1.718     www      8934: #		&logthis("Got a blank emb style");
1.695     albertel 8935: 	    }
1.694     albertel 8936: 	}
                   8937:     }
1.31      www      8938:     return $thisfn;
1.12      www      8939: }
                   8940: 
1.787     albertel 8941: sub clutter_with_no_wrapper {
                   8942:     my $uri = &clutter(shift);
                   8943:     if ($uri =~ m-^/adm/-) {
                   8944: 	$uri =~ s-^/adm/wrapper/-/-;
                   8945: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8946:     }
                   8947:     return $uri;
                   8948: }
                   8949: 
1.557     albertel 8950: sub freeze_escape {
                   8951:     my ($value)=@_;
                   8952:     if (ref($value)) {
                   8953: 	$value=&nfreeze($value);
                   8954: 	return '__FROZEN__'.&escape($value);
                   8955:     }
                   8956:     return &escape($value);
                   8957: }
                   8958: 
1.11      www      8959: 
1.557     albertel 8960: sub thaw_unescape {
                   8961:     my ($value)=@_;
                   8962:     if ($value =~ /^__FROZEN__/) {
                   8963: 	substr($value,0,10,undef);
                   8964: 	$value=&unescape($value);
                   8965: 	return &thaw($value);
                   8966:     }
                   8967:     return &unescape($value);
                   8968: }
                   8969: 
1.436     albertel 8970: sub correct_line_ends {
                   8971:     my ($result)=@_;
                   8972:     $$result =~s/\r\n/\n/mg;
                   8973:     $$result =~s/\r/\n/mg;
1.415     albertel 8974: }
1.1       albertel 8975: # ================================================================ Main Program
                   8976: 
1.184     www      8977: sub goodbye {
1.204     albertel 8978:    &logthis("Starting Shut down");
1.443     albertel 8979: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8980:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8981: #converted
1.599     albertel 8982: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8983:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8984: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8985: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8986: #1.1 only
1.870     albertel 8987: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8988: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8989: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8990: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8991:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8992:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8993:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8994:    &flushcourselogs();
                   8995:    &logthis("Shutting down");
                   8996: }
                   8997: 
1.852     albertel 8998: sub get_dns {
1.869     albertel 8999:     my ($url,$func,$ignore_cache) = @_;
                   9000:     if (!$ignore_cache) {
                   9001: 	my ($content,$cached)=
                   9002: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   9003: 	if ($cached) {
                   9004: 	    &$func($content);
                   9005: 	    return;
                   9006: 	}
                   9007:     }
                   9008: 
                   9009:     my %alldns;
1.852     albertel 9010:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9011:     foreach my $dns (<$config>) {
                   9012: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  9013:         my $line = $1;
                   9014:         my ($host,$protocol) = split(/:/,$line);
                   9015:         if ($protocol ne 'https') {
                   9016:             $protocol = 'http';
                   9017:         }
                   9018: 	$alldns{$host} = $protocol;
1.869     albertel 9019:     }
                   9020:     while (%alldns) {
                   9021: 	my ($dns) = keys(%alldns);
1.852     albertel 9022: 	my $ua=new LWP::UserAgent;
1.979     raeburn  9023: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 9024: 	my $response=$ua->request($request);
1.979     raeburn  9025:         delete($alldns{$dns});
1.852     albertel 9026: 	next if ($response->is_error());
                   9027: 	my @content = split("\n",$response->content);
1.869     albertel 9028: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 9029: 	&$func(\@content);
1.869     albertel 9030: 	return;
1.852     albertel 9031:     }
                   9032:     close($config);
1.871     albertel 9033:     my $which = (split('/',$url))[3];
                   9034:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   9035:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 9036:     my @content = <$config>;
                   9037:     &$func(\@content);
                   9038:     return;
1.852     albertel 9039: }
1.327     albertel 9040: # ------------------------------------------------------------ Read domain file
                   9041: {
1.852     albertel 9042:     my $loaded;
1.846     albertel 9043:     my %domain;
                   9044: 
1.852     albertel 9045:     sub parse_domain_tab {
                   9046: 	my ($lines) = @_;
                   9047: 	foreach my $line (@$lines) {
                   9048: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      9049: 
1.846     albertel 9050: 	    chomp($line);
1.852     albertel 9051: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 9052: 	    my %this_domain;
                   9053: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   9054: 			       'lang_def', 'city', 'longi', 'lati',
                   9055: 			       'primary') {
                   9056: 		$this_domain{$field} = shift(@elements);
                   9057: 	    }
                   9058: 	    $domain{$name} = \%this_domain;
1.852     albertel 9059: 	}
                   9060:     }
1.864     albertel 9061: 
                   9062:     sub reset_domain_info {
                   9063: 	undef($loaded);
                   9064: 	undef(%domain);
                   9065:     }
                   9066: 
1.852     albertel 9067:     sub load_domain_tab {
1.869     albertel 9068: 	my ($ignore_cache) = @_;
                   9069: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 9070: 	my $fh;
                   9071: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   9072: 	    my @lines = <$fh>;
                   9073: 	    &parse_domain_tab(\@lines);
1.448     albertel 9074: 	}
1.852     albertel 9075: 	close($fh);
                   9076: 	$loaded = 1;
1.327     albertel 9077:     }
1.846     albertel 9078: 
                   9079:     sub domain {
1.852     albertel 9080: 	&load_domain_tab() if (!$loaded);
                   9081: 
1.846     albertel 9082: 	my ($name,$what) = @_;
                   9083: 	return if ( !exists($domain{$name}) );
                   9084: 
                   9085: 	if (!$what) {
                   9086: 	    return $domain{$name}{'description'};
                   9087: 	}
                   9088: 	return $domain{$name}{$what};
                   9089:     }
1.974     raeburn  9090: 
                   9091:     sub domain_info {
                   9092:         &load_domain_tab() if (!$loaded);
                   9093:         return %domain;
                   9094:     }
                   9095: 
1.327     albertel 9096: }
                   9097: 
                   9098: 
1.1       albertel 9099: # ------------------------------------------------------------- Read hosts file
                   9100: {
1.838     albertel 9101:     my %hostname;
1.844     albertel 9102:     my %hostdom;
1.845     albertel 9103:     my %libserv;
1.852     albertel 9104:     my $loaded;
1.888     albertel 9105:     my %name_to_host;
1.852     albertel 9106: 
                   9107:     sub parse_hosts_tab {
                   9108: 	my ($file) = @_;
                   9109: 	foreach my $configline (@$file) {
                   9110: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   9111: 	    next if ($configline =~ /^\^/);
                   9112: 	    chomp($configline);
1.968     raeburn  9113: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852     albertel 9114: 	    $name=~s/\s//g;
                   9115: 	    if ($id && $domain && $role && $name) {
                   9116: 		$hostname{$id}=$name;
1.888     albertel 9117: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 9118: 		$hostdom{$id}=$domain;
                   9119: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  9120:                 if (defined($protocol)) {
                   9121:                     if ($protocol eq 'https') {
                   9122:                         $protocol{$id} = $protocol;
                   9123:                     } else {
                   9124:                         $protocol{$id} = 'http'; 
                   9125:                     }
1.968     raeburn  9126:                 } else {
1.969     raeburn  9127:                     $protocol{$id} = 'http';
1.968     raeburn  9128:                 }
1.852     albertel 9129: 	    }
                   9130: 	}
                   9131:     }
1.864     albertel 9132:     
                   9133:     sub reset_hosts_info {
1.897     albertel 9134: 	&purge_remembered();
1.864     albertel 9135: 	&reset_domain_info();
                   9136: 	&reset_hosts_ip_info();
1.892     albertel 9137: 	undef(%name_to_host);
1.864     albertel 9138: 	undef(%hostname);
                   9139: 	undef(%hostdom);
                   9140: 	undef(%libserv);
                   9141: 	undef($loaded);
                   9142:     }
1.1       albertel 9143: 
1.852     albertel 9144:     sub load_hosts_tab {
1.869     albertel 9145: 	my ($ignore_cache) = @_;
                   9146: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 9147: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9148: 	my @config = <$config>;
                   9149: 	&parse_hosts_tab(\@config);
                   9150: 	close($config);
                   9151: 	$loaded=1;
1.1       albertel 9152:     }
1.852     albertel 9153: 
1.838     albertel 9154:     sub hostname {
1.852     albertel 9155: 	&load_hosts_tab() if (!$loaded);
                   9156: 
1.838     albertel 9157: 	my ($lonid) = @_;
                   9158: 	return $hostname{$lonid};
                   9159:     }
1.845     albertel 9160: 
1.838     albertel 9161:     sub all_hostnames {
1.852     albertel 9162: 	&load_hosts_tab() if (!$loaded);
                   9163: 
1.838     albertel 9164: 	return %hostname;
                   9165:     }
1.845     albertel 9166: 
1.888     albertel 9167:     sub all_names {
                   9168: 	&load_hosts_tab() if (!$loaded);
                   9169: 
                   9170: 	return %name_to_host;
                   9171:     }
                   9172: 
1.974     raeburn  9173:     sub all_host_domain {
                   9174:         &load_hosts_tab() if (!$loaded);
                   9175:         return %hostdom;
                   9176:     }
                   9177: 
1.845     albertel 9178:     sub is_library {
1.852     albertel 9179: 	&load_hosts_tab() if (!$loaded);
                   9180: 
1.845     albertel 9181: 	return exists($libserv{$_[0]});
                   9182:     }
                   9183: 
                   9184:     sub all_library {
1.852     albertel 9185: 	&load_hosts_tab() if (!$loaded);
                   9186: 
1.845     albertel 9187: 	return %libserv;
                   9188:     }
                   9189: 
1.841     albertel 9190:     sub get_servers {
1.852     albertel 9191: 	&load_hosts_tab() if (!$loaded);
                   9192: 
1.841     albertel 9193: 	my ($domain,$type) = @_;
                   9194: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   9195: 	                                          : %hostname;
                   9196: 	my %result;
1.842     albertel 9197: 	if (ref($domain) eq 'ARRAY') {
                   9198: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 9199: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 9200: 		    $result{$host} = $hostname;
                   9201: 		}
                   9202: 	    }
                   9203: 	} else {
                   9204: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   9205: 		if ($hostdom{$host} eq $domain) {
                   9206: 		    $result{$host} = $hostname;
                   9207: 		}
1.841     albertel 9208: 	    }
                   9209: 	}
                   9210: 	return %result;
                   9211:     }
1.845     albertel 9212: 
1.844     albertel 9213:     sub host_domain {
1.852     albertel 9214: 	&load_hosts_tab() if (!$loaded);
                   9215: 
1.844     albertel 9216: 	my ($lonid) = @_;
                   9217: 	return $hostdom{$lonid};
                   9218:     }
                   9219: 
1.841     albertel 9220:     sub all_domains {
1.852     albertel 9221: 	&load_hosts_tab() if (!$loaded);
                   9222: 
1.841     albertel 9223: 	my %seen;
                   9224: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   9225: 	return @uniq;
                   9226:     }
1.1       albertel 9227: }
                   9228: 
1.847     albertel 9229: { 
                   9230:     my %iphost;
1.856     albertel 9231:     my %name_to_ip;
                   9232:     my %lonid_to_ip;
1.869     albertel 9233: 
1.847     albertel 9234:     sub get_hosts_from_ip {
                   9235: 	my ($ip) = @_;
                   9236: 	my %iphosts = &get_iphost();
                   9237: 	if (ref($iphosts{$ip})) {
                   9238: 	    return @{$iphosts{$ip}};
                   9239: 	}
                   9240: 	return;
1.839     albertel 9241:     }
1.864     albertel 9242:     
                   9243:     sub reset_hosts_ip_info {
                   9244: 	undef(%iphost);
                   9245: 	undef(%name_to_ip);
                   9246: 	undef(%lonid_to_ip);
                   9247:     }
1.856     albertel 9248: 
                   9249:     sub get_host_ip {
                   9250: 	my ($lonid) = @_;
                   9251: 	if (exists($lonid_to_ip{$lonid})) {
                   9252: 	    return $lonid_to_ip{$lonid};
                   9253: 	}
                   9254: 	my $name=&hostname($lonid);
                   9255:    	my $ip = gethostbyname($name);
                   9256: 	return if (!$ip || length($ip) ne 4);
                   9257: 	$ip=inet_ntoa($ip);
                   9258: 	$name_to_ip{$name}   = $ip;
                   9259: 	$lonid_to_ip{$lonid} = $ip;
                   9260: 	return $ip;
                   9261:     }
1.847     albertel 9262:     
                   9263:     sub get_iphost {
1.869     albertel 9264: 	my ($ignore_cache) = @_;
1.894     albertel 9265: 
1.869     albertel 9266: 	if (!$ignore_cache) {
                   9267: 	    if (%iphost) {
                   9268: 		return %iphost;
                   9269: 	    }
                   9270: 	    my ($ip_info,$cached)=
                   9271: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   9272: 	    if ($cached) {
                   9273: 		%iphost      = %{$ip_info->[0]};
                   9274: 		%name_to_ip  = %{$ip_info->[1]};
                   9275: 		%lonid_to_ip = %{$ip_info->[2]};
                   9276: 		return %iphost;
                   9277: 	    }
                   9278: 	}
1.894     albertel 9279: 
                   9280: 	# get yesterday's info for fallback
                   9281: 	my %old_name_to_ip;
                   9282: 	my ($ip_info,$cached)=
                   9283: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   9284: 	if ($cached) {
                   9285: 	    %old_name_to_ip = %{$ip_info->[1]};
                   9286: 	}
                   9287: 
1.888     albertel 9288: 	my %name_to_host = &all_names();
                   9289: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 9290: 	    my $ip;
                   9291: 	    if (!exists($name_to_ip{$name})) {
                   9292: 		$ip = gethostbyname($name);
                   9293: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 9294: 		    if (defined($old_name_to_ip{$name})) {
                   9295: 			$ip = $old_name_to_ip{$name};
                   9296: 			&logthis("Can't find $name defaulting to old $ip");
                   9297: 		    } else {
                   9298: 			&logthis("Name $name no IP found");
                   9299: 			next;
                   9300: 		    }
                   9301: 		} else {
                   9302: 		    $ip=inet_ntoa($ip);
1.847     albertel 9303: 		}
                   9304: 		$name_to_ip{$name} = $ip;
                   9305: 	    } else {
                   9306: 		$ip = $name_to_ip{$name};
1.653     albertel 9307: 	    }
1.888     albertel 9308: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   9309: 		$lonid_to_ip{$id} = $ip;
                   9310: 	    }
                   9311: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 9312: 	}
1.869     albertel 9313: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   9314: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 9315: 				      48*60*60);
1.869     albertel 9316: 
1.847     albertel 9317: 	return %iphost;
1.598     albertel 9318:     }
                   9319: 
1.992     raeburn  9320:     #
                   9321:     #  Given a DNS returns the loncapa host name for that DNS 
                   9322:     # 
                   9323:     sub host_from_dns {
                   9324:         my ($dns) = @_;
                   9325:         my @hosts;
                   9326:         my $ip;
                   9327: 
1.993     raeburn  9328:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  9329:             $ip = $name_to_ip{$dns};
                   9330:         }
                   9331:         if (!$ip) {
                   9332:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   9333:             if (length($ip) == 4) { 
                   9334: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   9335:             }
                   9336:         }
                   9337:         if ($ip) {
                   9338: 	    @hosts = get_hosts_from_ip($ip);
                   9339: 	    return $hosts[0];
                   9340:         }
                   9341:         return undef;
1.986     foxr     9342:     }
1.992     raeburn  9343: 
1.986     foxr     9344: }
                   9345: 
1.862     albertel 9346: BEGIN {
                   9347: 
                   9348: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   9349:     unless ($readit) {
                   9350: {
                   9351:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   9352:     %perlvar = (%perlvar,%{$configvars});
                   9353: }
                   9354: 
                   9355: 
1.1       albertel 9356: # ------------------------------------------------------ Read spare server file
                   9357: {
1.448     albertel 9358:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 9359: 
                   9360:     while (my $configline=<$config>) {
                   9361:        chomp($configline);
1.284     matthew  9362:        if ($configline) {
1.784     albertel 9363: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 9364: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 9365: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 9366:        }
                   9367:     }
1.448     albertel 9368:     close($config);
1.1       albertel 9369: }
1.11      www      9370: # ------------------------------------------------------------ Read permissions
                   9371: {
1.448     albertel 9372:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      9373: 
                   9374:     while (my $configline=<$config>) {
1.448     albertel 9375: 	chomp($configline);
                   9376: 	if ($configline) {
                   9377: 	    my ($role,$perm)=split(/ /,$configline);
                   9378: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   9379: 	}
1.11      www      9380:     }
1.448     albertel 9381:     close($config);
1.11      www      9382: }
                   9383: 
                   9384: # -------------------------------------------- Read plain texts for permissions
                   9385: {
1.448     albertel 9386:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      9387: 
                   9388:     while (my $configline=<$config>) {
1.448     albertel 9389: 	chomp($configline);
                   9390: 	if ($configline) {
1.742     raeburn  9391: 	    my ($short,@plain)=split(/:/,$configline);
                   9392:             %{$prp{$short}} = ();
                   9393: 	    if (@plain > 0) {
                   9394:                 $prp{$short}{'std'} = $plain[0];
                   9395:                 for (my $i=1; $i<@plain; $i++) {
                   9396:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   9397:                 }
                   9398:             }
1.448     albertel 9399: 	}
1.135     www      9400:     }
1.448     albertel 9401:     close($config);
1.135     www      9402: }
                   9403: 
                   9404: # ---------------------------------------------------------- Read package table
                   9405: {
1.448     albertel 9406:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      9407: 
                   9408:     while (my $configline=<$config>) {
1.483     albertel 9409: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 9410: 	chomp($configline);
                   9411: 	my ($short,$plain)=split(/:/,$configline);
                   9412: 	my ($pack,$name)=split(/\&/,$short);
                   9413: 	if ($plain ne '') {
                   9414: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   9415: 	    $packagetab{$short}=$plain; 
                   9416: 	}
1.11      www      9417:     }
1.448     albertel 9418:     close($config);
1.329     matthew  9419: }
                   9420: 
                   9421: # ------------- set up temporary directory
                   9422: {
                   9423:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   9424: 
1.11      www      9425: }
                   9426: 
1.794     albertel 9427: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   9428: 				'compress_threshold'=> 20_000,
                   9429:  			        });
1.185     www      9430: 
1.281     www      9431: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      9432: $dumpcount=0;
1.958     www      9433: $locknum=0;
1.22      www      9434: 
1.163     harris41 9435: &logtouch();
1.672     albertel 9436: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      9437: $readit=1;
1.564     albertel 9438:     {
                   9439: 	use integer;
                   9440: 	my $test=(2**32)+1;
1.568     albertel 9441: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 9442: 	&logthis(" Detected 64bit platform ($_64bit)");
                   9443:     }
1.195     www      9444: }
1.1       albertel 9445: }
1.179     www      9446: 
1.1       albertel 9447: 1;
1.191     harris41 9448: __END__
                   9449: 
1.243     albertel 9450: =pod
                   9451: 
1.191     harris41 9452: =head1 NAME
                   9453: 
1.243     albertel 9454: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 9455: 
                   9456: =head1 SYNOPSIS
                   9457: 
1.243     albertel 9458: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 9459: 
                   9460:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   9461: 
1.243     albertel 9462: Common parameters:
                   9463: 
                   9464: =over 4
                   9465: 
                   9466: =item *
                   9467: 
                   9468: $uname : an internal username (if $cname expecting a course Id specifically)
                   9469: 
                   9470: =item *
                   9471: 
                   9472: $udom : a domain (if $cdom expecting a course's domain specifically)
                   9473: 
                   9474: =item *
                   9475: 
                   9476: $symb : a resource instance identifier
                   9477: 
                   9478: =item *
                   9479: 
                   9480: $namespace : the name of a .db file that contains the data needed or
                   9481: being set.
                   9482: 
                   9483: =back
                   9484: 
1.394     bowersj2 9485: =head1 OVERVIEW
1.191     harris41 9486: 
1.394     bowersj2 9487: lonnet provides subroutines which interact with the
                   9488: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   9489: about classes, users, and resources.
1.243     albertel 9490: 
                   9491: For many of these objects you can also use this to store data about
                   9492: them or modify them in various ways.
1.191     harris41 9493: 
1.394     bowersj2 9494: =head2 Symbs
1.191     harris41 9495: 
1.394     bowersj2 9496: To identify a specific instance of a resource, LON-CAPA uses symbols
                   9497: or "symbs"X<symb>. These identifiers are built from the URL of the
                   9498: map, the resource number of the resource in the map, and the URL of
                   9499: the resource itself. The latter is somewhat redundant, but might help
                   9500: if maps change.
                   9501: 
                   9502: An example is
                   9503: 
                   9504:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   9505: 
                   9506: The respective map entry is
                   9507: 
                   9508:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   9509:   title="Problem 2">
                   9510:  </resource>
                   9511: 
                   9512: Symbs are used by the random number generator, as well as to store and
                   9513: restore data specific to a certain instance of for example a problem.
                   9514: 
                   9515: =head2 Storing And Retrieving Data
                   9516: 
                   9517: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   9518: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   9519: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   9520: is is the non-critical message twin of cstore. These functions are for
                   9521: handlers to store a perl hash to a user's permanent data space in an
                   9522: easy manner, and to retrieve it again on another call. It is expected
                   9523: that a handler would use this once at the beginning to retrieve data,
                   9524: and then again once at the end to send only the new data back.
                   9525: 
                   9526: The data is stored in the user's data directory on the user's
                   9527: homeserver under the ID of the course.
                   9528: 
                   9529: The hash that is returned by restore will have all of the previous
                   9530: value for all of the elements of the hash.
                   9531: 
                   9532: Example:
                   9533: 
                   9534:  #creating a hash
                   9535:  my %hash;
                   9536:  $hash{'foo'}='bar';
                   9537: 
                   9538:  #storing it
                   9539:  &Apache::lonnet::cstore(\%hash);
                   9540: 
                   9541:  #changing a value
                   9542:  $hash{'foo'}='notbar';
                   9543: 
                   9544:  #adding a new value
                   9545:  $hash{'bar'}='foo';
                   9546:  &Apache::lonnet::cstore(\%hash);
                   9547: 
                   9548:  #retrieving the hash
                   9549:  my %history=&Apache::lonnet::restore();
                   9550: 
                   9551:  #print the hash
                   9552:  foreach my $key (sort(keys(%history))) {
                   9553:    print("\%history{$key} = $history{$key}");
                   9554:  }
                   9555: 
                   9556: Will print out:
1.191     harris41 9557: 
1.394     bowersj2 9558:  %history{1:foo} = bar
                   9559:  %history{1:keys} = foo:timestamp
                   9560:  %history{1:timestamp} = 990455579
                   9561:  %history{2:bar} = foo
                   9562:  %history{2:foo} = notbar
                   9563:  %history{2:keys} = foo:bar:timestamp
                   9564:  %history{2:timestamp} = 990455580
                   9565:  %history{bar} = foo
                   9566:  %history{foo} = notbar
                   9567:  %history{timestamp} = 990455580
                   9568:  %history{version} = 2
                   9569: 
                   9570: Note that the special hash entries C<keys>, C<version> and
                   9571: C<timestamp> were added to the hash. C<version> will be equal to the
                   9572: total number of versions of the data that have been stored. The
                   9573: C<timestamp> attribute will be the UNIX time the hash was
                   9574: stored. C<keys> is available in every historical section to list which
                   9575: keys were added or changed at a specific historical revision of a
                   9576: hash.
                   9577: 
                   9578: B<Warning>: do not store the hash that restore returns directly. This
                   9579: will cause a mess since it will restore the historical keys as if the
                   9580: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 9581: 
1.394     bowersj2 9582: Calling convention:
1.191     harris41 9583: 
1.394     bowersj2 9584:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   9585:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 9586: 
1.394     bowersj2 9587: For more detailed information, see lonnet specific documentation.
1.191     harris41 9588: 
1.394     bowersj2 9589: =head1 RETURN MESSAGES
1.191     harris41 9590: 
1.394     bowersj2 9591: =over 4
1.191     harris41 9592: 
1.394     bowersj2 9593: =item * B<con_lost>: unable to contact remote host
1.191     harris41 9594: 
1.394     bowersj2 9595: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   9596: when the connection is brought back up
1.191     harris41 9597: 
1.394     bowersj2 9598: =item * B<con_failed>: unable to contact remote host and unable to save message
                   9599: for later delivery
1.191     harris41 9600: 
1.967     bisitz   9601: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 9602: 
1.394     bowersj2 9603: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 9604: that was requested
1.191     harris41 9605: 
1.243     albertel 9606: =back
1.191     harris41 9607: 
1.243     albertel 9608: =head1 PUBLIC SUBROUTINES
1.191     harris41 9609: 
1.243     albertel 9610: =head2 Session Environment Functions
1.191     harris41 9611: 
1.243     albertel 9612: =over 4
1.191     harris41 9613: 
1.394     bowersj2 9614: =item * 
                   9615: X<appenv()>
1.949     raeburn  9616: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 9617: the user envirnoment file, and will be restored for each access this
1.620     albertel 9618: user makes during this session, also modifies the %env for the current
1.949     raeburn  9619: process. Optional rolesarrayref - if defined contains a reference to an array
                   9620: of roles which are exempt from the restriction on modifying user.role entries 
                   9621: in the user's environment.db and in %env.    
1.191     harris41 9622: 
                   9623: =item *
1.394     bowersj2 9624: X<delenv()>
1.987     raeburn  9625: B<delenv($delthis,$regexp)>: removes all items from the session
                   9626: environment file that begin with $delthis. If the 
                   9627: optional second arg - $regexp - is true, $delthis is treated as a 
                   9628: regular expression, otherwise \Q$delthis\E is used. 
                   9629: The values are also deleted from the current processes %env.
1.191     harris41 9630: 
1.795     albertel 9631: =item * get_env_multiple($name) 
                   9632: 
                   9633: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   9634: values may be defined and end up as an array ref.
                   9635: 
                   9636: returns an array of values
                   9637: 
1.243     albertel 9638: =back
                   9639: 
                   9640: =head2 User Information
1.191     harris41 9641: 
1.243     albertel 9642: =over 4
1.191     harris41 9643: 
                   9644: =item *
1.394     bowersj2 9645: X<queryauthenticate()>
                   9646: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 9647: authentication scheme
                   9648: 
                   9649: =item *
1.394     bowersj2 9650: X<authenticate()>
                   9651: B<authenticate($uname,$upass,$udom)>: try to
                   9652: authenticate user from domain's lib servers (first use the current
                   9653: one). C<$upass> should be the users password.
1.191     harris41 9654: 
                   9655: =item *
1.394     bowersj2 9656: X<homeserver()>
                   9657: B<homeserver($uname,$udom)>: find the server which has
                   9658: the user's directory and files (there must be only one), this caches
                   9659: the answer, and also caches if there is a borken connection.
1.191     harris41 9660: 
                   9661: =item *
1.394     bowersj2 9662: X<idget()>
                   9663: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   9664: (IDs are a unique resource in a domain, there must be only 1 ID per
                   9665: username, and only 1 username per ID in a specific domain) (returns
                   9666: hash: id=>name,id=>name)
1.191     harris41 9667: 
                   9668: =item *
1.394     bowersj2 9669: X<idrget()>
                   9670: B<idrget($udom,@unames)>: find the IDs behind a list of
                   9671: usernames (returns hash: name=>id,name=>id)
1.191     harris41 9672: 
                   9673: =item *
1.394     bowersj2 9674: X<idput()>
                   9675: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 9676: 
                   9677: =item *
1.394     bowersj2 9678: X<rolesinit()>
                   9679: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 9680: 
                   9681: =item *
1.551     albertel 9682: X<getsection()>
                   9683: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 9684: course $cname, return section name/number or '' for "not in course"
                   9685: and '-1' for "no section"
                   9686: 
                   9687: =item *
1.394     bowersj2 9688: X<userenvironment()>
                   9689: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 9690: passed in @what from the requested user's environment, returns a hash
                   9691: 
1.858     raeburn  9692: =item * 
                   9693: X<userlog_query()>
1.859     albertel 9694: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   9695: activity.log file. %filters defines filters applied when parsing the
                   9696: log file. These can be start or end timestamps, or the type of action
                   9697: - log to look for Login or Logout events, check for Checkin or
                   9698: Checkout, role for role selection. The response is in the form
                   9699: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   9700: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  9701: 
1.243     albertel 9702: =back
                   9703: 
                   9704: =head2 User Roles
                   9705: 
                   9706: =over 4
                   9707: 
                   9708: =item *
                   9709: 
1.810     raeburn  9710: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 9711:  F: full access
                   9712:  U,I,K: authentication modes (cxx only)
                   9713:  '': forbidden
                   9714:  1: user needs to choose course
                   9715:  2: browse allowed
1.766     albertel 9716:  A: passphrase authentication needed
1.243     albertel 9717: 
                   9718: =item *
                   9719: 
                   9720: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   9721: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   9722: and course level
                   9723: 
                   9724: =item *
                   9725: 
1.988     raeburn  9726: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   9727: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  9728: $type is Course (default) or Community.
1.988     raeburn  9729: If $forcedefault evaluates to true, text returned will be default 
                   9730: text for $type. Otherwise, if this is a course, the text returned 
                   9731: will be a custom name for the role (if defined in the course's 
                   9732: environment).  If no custom name is defined the default is returned.
                   9733:    
1.832     raeburn  9734: =item *
                   9735: 
1.935     raeburn  9736: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  9737: All arguments are optional. Returns a hash of a roles, either for
                   9738: co-author/assistant author roles for a user's Construction Space
1.906     albertel 9739: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  9740: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   9741: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   9742: For each key, value is set to colon-separated start and end times for
                   9743: the role.  If no username and domain are specified, will default to
1.934     raeburn  9744: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  9745: of role statuses (active, future or previous), roles 
                   9746: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   9747: to restrict the list of roles reported. If no array ref is 
                   9748: provided for types, will default to return only active roles.
1.834     albertel 9749: 
1.243     albertel 9750: =back
                   9751: 
                   9752: =head2 User Modification
                   9753: 
                   9754: =over 4
                   9755: 
                   9756: =item *
                   9757: 
1.957     raeburn  9758: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 9759: user for the level given by URL.  Optional start and end dates (leave empty
                   9760: string or zero for "no date")
1.191     harris41 9761: 
                   9762: =item *
                   9763: 
1.243     albertel 9764: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   9765: change a users, password, possible return values are: ok,
                   9766: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   9767: refused
1.191     harris41 9768: 
                   9769: =item *
                   9770: 
1.243     albertel 9771: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9772: 
                   9773: =item *
                   9774: 
1.963     raeburn  9775: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
                   9776:            $forceid,$desiredhome,$email,$inststatus) : 
1.243     albertel 9777: modify user
1.191     harris41 9778: 
                   9779: =item *
                   9780: 
1.286     matthew  9781: modifystudent
                   9782: 
1.957     raeburn  9783: modify a student's enrollment and identification information.
1.286     matthew  9784: The course id is resolved based on the current users environment.  
                   9785: This means the envoking user must be a course coordinator or otherwise
                   9786: associated with a course.
                   9787: 
1.297     matthew  9788: This call is essentially a wrapper for lonnet::modifyuser and
                   9789: lonnet::modify_student_enrollment
1.286     matthew  9790: 
                   9791: Inputs: 
                   9792: 
                   9793: =over 4
                   9794: 
1.957     raeburn  9795: =item B<$udom> Student's loncapa domain
1.286     matthew  9796: 
1.957     raeburn  9797: =item B<$uname> Student's loncapa login name
1.286     matthew  9798: 
1.964     bisitz   9799: =item B<$uid> Student/Employee ID
1.286     matthew  9800: 
1.957     raeburn  9801: =item B<$umode> Student's authentication mode
1.286     matthew  9802: 
1.957     raeburn  9803: =item B<$upass> Student's password
1.286     matthew  9804: 
1.957     raeburn  9805: =item B<$first> Student's first name
1.286     matthew  9806: 
1.957     raeburn  9807: =item B<$middle> Student's middle name
1.286     matthew  9808: 
1.957     raeburn  9809: =item B<$last> Student's last name
1.286     matthew  9810: 
1.957     raeburn  9811: =item B<$gene> Student's generation
1.286     matthew  9812: 
1.957     raeburn  9813: =item B<$usec> Student's section in course
1.286     matthew  9814: 
                   9815: =item B<$end> Unix time of the roles expiration
                   9816: 
                   9817: =item B<$start> Unix time of the roles start date
                   9818: 
                   9819: =item B<$forceid> If defined, allow $uid to be changed
                   9820: 
                   9821: =item B<$desiredhome> server to use as home server for student
                   9822: 
1.957     raeburn  9823: =item B<$email> Student's permanent e-mail address
                   9824: 
                   9825: =item B<$type> Type of enrollment (auto or manual)
                   9826: 
1.963     raeburn  9827: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   9828: 
                   9829: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  9830: 
1.963     raeburn  9831: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  9832: 
1.963     raeburn  9833: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  9834: 
1.963     raeburn  9835: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  9836: 
1.286     matthew  9837: =back
1.297     matthew  9838: 
                   9839: =item *
                   9840: 
                   9841: modify_student_enrollment
                   9842: 
                   9843: Change a students enrollment status in a class.  The environment variable
                   9844: 'role.request.course' must be defined for this function to proceed.
                   9845: 
                   9846: Inputs:
                   9847: 
                   9848: =over 4
                   9849: 
                   9850: =item $udom, students domain
                   9851: 
                   9852: =item $uname, students name
                   9853: 
                   9854: =item $uid, students user id
                   9855: 
                   9856: =item $first, students first name
                   9857: 
                   9858: =item $middle
                   9859: 
                   9860: =item $last
                   9861: 
                   9862: =item $gene
                   9863: 
                   9864: =item $usec
                   9865: 
                   9866: =item $end
                   9867: 
                   9868: =item $start
                   9869: 
1.957     raeburn  9870: =item $type
                   9871: 
                   9872: =item $locktype
                   9873: 
                   9874: =item $cid
                   9875: 
                   9876: =item $selfenroll
                   9877: 
                   9878: =item $context
                   9879: 
1.297     matthew  9880: =back
                   9881: 
1.191     harris41 9882: 
                   9883: =item *
                   9884: 
1.243     albertel 9885: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9886: custom role; give a custom role to a user for the level given by URL.  Specify
                   9887: name and domain of role author, and role name
1.191     harris41 9888: 
                   9889: =item *
                   9890: 
1.243     albertel 9891: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9892: 
                   9893: =item *
                   9894: 
1.243     albertel 9895: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9896: 
                   9897: =back
                   9898: 
                   9899: =head2 Course Infomation
                   9900: 
                   9901: =over 4
1.191     harris41 9902: 
                   9903: =item *
                   9904: 
1.631     albertel 9905: coursedescription($courseid) : returns a hash of information about the
                   9906: specified course id, including all environment settings for the
                   9907: course, the description of the course will be in the hash under the
                   9908: key 'description'
1.191     harris41 9909: 
                   9910: =item *
                   9911: 
1.624     albertel 9912: resdata($name,$domain,$type,@which) : request for current parameter
                   9913: setting for a specific $type, where $type is either 'course' or 'user',
                   9914: @what should be a list of parameters to ask about. This routine caches
                   9915: answers for 5 minutes.
1.243     albertel 9916: 
1.877     foxr     9917: =item *
                   9918: 
                   9919: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9920: data base, returning a hash that is keyed by the resource name and has
                   9921: values that are the resource value.  I believe that the timestamps and
                   9922: versions are also returned.
                   9923: 
                   9924: 
1.243     albertel 9925: =back
                   9926: 
                   9927: =head2 Course Modification
                   9928: 
                   9929: =over 4
1.191     harris41 9930: 
                   9931: =item *
                   9932: 
1.243     albertel 9933: writecoursepref($courseid,%prefs) : write preferences (environment
                   9934: database) for a course
1.191     harris41 9935: 
                   9936: =item *
                   9937: 
1.1011  ! raeburn  9938: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
        !          9939: 
        !          9940: =item *
        !          9941: 
        !          9942: generate_coursenum($udom) : get a unique (unused) course number in domain $udom
1.243     albertel 9943: 
                   9944: =back
                   9945: 
                   9946: =head2 Resource Subroutines
                   9947: 
                   9948: =over 4
1.191     harris41 9949: 
                   9950: =item *
                   9951: 
1.243     albertel 9952: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9953: 
                   9954: =item *
                   9955: 
1.243     albertel 9956: repcopy($filename) : subscribes to the requested file, and attempts to
                   9957: replicate from the owning library server, Might return
1.607     raeburn  9958: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9959: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9960: resource. Expects the local filesystem pathname
                   9961: (/home/httpd/html/res/....)
                   9962: 
                   9963: =back
                   9964: 
                   9965: =head2 Resource Information
                   9966: 
                   9967: =over 4
1.191     harris41 9968: 
                   9969: =item *
                   9970: 
1.243     albertel 9971: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9972: a vairety of different possible values, $varname should be a request
                   9973: string, and the other parameters can be used to specify who and what
                   9974: one is asking about.
                   9975: 
                   9976: Possible values for $varname are environment.lastname (or other item
                   9977: from the envirnment hash), user.name (or someother aspect about the
                   9978: user), resource.0.maxtries (or some other part and parameter of a
                   9979: resource)
1.204     albertel 9980: 
                   9981: =item *
                   9982: 
1.243     albertel 9983: directcondval($number) : get current value of a condition; reads from a state
                   9984: string
1.204     albertel 9985: 
                   9986: =item *
                   9987: 
1.243     albertel 9988: condval($condidx) : value of condition index based on state
1.204     albertel 9989: 
                   9990: =item *
                   9991: 
1.243     albertel 9992: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9993: resource's metadata, $what should be either a specific key, or either
                   9994: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9995: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9996: 
                   9997: this function automatically caches all requests
1.191     harris41 9998: 
                   9999: =item *
                   10000: 
1.243     albertel 10001: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   10002: network of library servers; returns file handle of where SQL and regex results
                   10003: will be stored for query
1.191     harris41 10004: 
                   10005: =item *
                   10006: 
1.243     albertel 10007: symbread($filename) : return symbolic list entry (filename argument optional);
                   10008: returns the data handle
1.191     harris41 10009: 
                   10010: =item *
                   10011: 
1.243     albertel 10012: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 10013: a possible symb for the URL in $thisfn, and if is an encryypted
                   10014: resource that the user accessed using /enc/ returns a 1 on success, 0
                   10015: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 10016: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 10017: 
1.191     harris41 10018: 
                   10019: =item *
                   10020: 
1.243     albertel 10021: symbclean($symb) : removes versions numbers from a symb, returns the
                   10022: cleaned symb
1.191     harris41 10023: 
                   10024: =item *
                   10025: 
1.243     albertel 10026: is_on_map($uri) : checks if the $uri is somewhere on the current
                   10027: course map, user must be in a course for it to work.
1.191     harris41 10028: 
                   10029: =item *
                   10030: 
1.243     albertel 10031: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 10032: 
                   10033: =item *
                   10034: 
1.243     albertel 10035: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   10036: a random seed, all arguments are optional, if they aren't sent it uses the
                   10037: environment to derive them. Note: if symb isn't sent and it can't get one
                   10038: from &symbread it will use the current time as its return value
1.191     harris41 10039: 
                   10040: =item *
                   10041: 
1.243     albertel 10042: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   10043: unfakeable, receipt
1.191     harris41 10044: 
                   10045: =item *
                   10046: 
1.620     albertel 10047: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 10048: 
                   10049: =item *
                   10050: 
1.243     albertel 10051: countacc($url) : count the number of accesses to a given URL
1.191     harris41 10052: 
                   10053: =item *
                   10054: 
1.243     albertel 10055: 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 10056: 
                   10057: =item *
                   10058: 
1.243     albertel 10059: 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 10060: 
                   10061: =item *
                   10062: 
1.243     albertel 10063: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 10064: 
                   10065: =item *
                   10066: 
1.243     albertel 10067: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   10068: forcing spreadsheet to reevaluate the resource scores next time.
                   10069: 
                   10070: =back
                   10071: 
                   10072: =head2 Storing/Retreiving Data
                   10073: 
                   10074: =over 4
1.191     harris41 10075: 
                   10076: =item *
                   10077: 
1.243     albertel 10078: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   10079: for this url; hashref needs to be given and should be a \%hashname; the
                   10080: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 10081: be derived from the env
1.191     harris41 10082: 
                   10083: =item *
                   10084: 
1.243     albertel 10085: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   10086: uses critical subroutine
1.191     harris41 10087: 
                   10088: =item *
                   10089: 
1.243     albertel 10090: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   10091: all args are optional
1.191     harris41 10092: 
                   10093: =item *
                   10094: 
1.717     albertel 10095: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   10096: dumps the complete (or key matching regexp) namespace into a hash
                   10097: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   10098: normally &store()ed into
                   10099: 
                   10100: $range should be either an integer '100' (give me the first 100
                   10101:                                            matching records)
                   10102:               or be  two integers sperated by a - with no spaces
                   10103:                  '30-50' (give me the 30th through the 50th matching
                   10104:                           records)
                   10105: 
                   10106: 
                   10107: =item *
                   10108: 
                   10109: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   10110: replaces a &store() version of data with a replacement set of data
                   10111: for a particular resource in a namespace passed in the $storehash hash 
                   10112: reference
                   10113: 
                   10114: =item *
                   10115: 
1.243     albertel 10116: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   10117: works very similar to store/cstore, but all data is stored in a
                   10118: temporary location and can be reset using tmpreset, $storehash should
                   10119: be a hash reference, returns nothing on success
1.191     harris41 10120: 
                   10121: =item *
                   10122: 
1.243     albertel 10123: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   10124: similar to restore, but all data is stored in a temporary location and
                   10125: can be reset using tmpreset. Returns a hash of values on success,
                   10126: error string otherwise.
1.191     harris41 10127: 
                   10128: =item *
                   10129: 
1.243     albertel 10130: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   10131: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 10132: 
                   10133: =item *
                   10134: 
1.243     albertel 10135: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   10136: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 10137: 
                   10138: =item *
                   10139: 
1.243     albertel 10140: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   10141: namesp ($udom and $uname are optional)
1.191     harris41 10142: 
                   10143: =item *
                   10144: 
1.702     albertel 10145: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 10146: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 10147: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  10148: 
1.702     albertel 10149: $range should be either an integer '100' (give me the first 100
                   10150:                                            matching records)
                   10151:               or be  two integers sperated by a - with no spaces
                   10152:                  '30-50' (give me the 30th through the 50th matching
                   10153:                           records)
1.449     matthew  10154: =item *
                   10155: 
                   10156: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   10157: $store can be a scalar, an array reference, or if the amount to be 
                   10158: incremented is > 1, a hash reference.
                   10159: 
                   10160: ($udom and $uname are optional)
1.191     harris41 10161: 
                   10162: =item *
                   10163: 
1.243     albertel 10164: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   10165: ($udom and $uname are optional)
1.191     harris41 10166: 
                   10167: =item *
                   10168: 
1.243     albertel 10169: cput($namespace,$storehash,$udom,$uname) : critical put
                   10170: ($udom and $uname are optional)
1.191     harris41 10171: 
                   10172: =item *
                   10173: 
1.748     albertel 10174: newput($namespace,$storehash,$udom,$uname) :
                   10175: 
                   10176: Attempts to store the items in the $storehash, but only if they don't
                   10177: currently exist, if this succeeds you can be certain that you have 
                   10178: successfully created a new key value pair in the $namespace db.
                   10179: 
                   10180: 
                   10181: Args:
                   10182:  $namespace: name of database to store values to
                   10183:  $storehash: hashref to store to the db
                   10184:  $udom: (optional) domain of user containing the db
                   10185:  $uname: (optional) name of user caontaining the db
                   10186: 
                   10187: Returns:
                   10188:  'ok' -> succeeded in storing all keys of $storehash
                   10189:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   10190:                         least <key> already existed in the db (other
                   10191:                         requested keys may also already exist)
1.967     bisitz   10192:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 10193:  'con_lost' -> unable to contact request server
                   10194:  'refused' -> action was not allowed by remote machine
                   10195: 
                   10196: 
                   10197: =item *
                   10198: 
1.243     albertel 10199: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   10200: reference filled in from namesp (encrypts the return communication)
                   10201: ($udom and $uname are optional)
1.191     harris41 10202: 
                   10203: =item *
                   10204: 
1.243     albertel 10205: log($udom,$name,$home,$message) : write to permanent log for user; use
                   10206: critical subroutine
                   10207: 
1.806     raeburn  10208: =item *
                   10209: 
1.860     raeburn  10210: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   10211: array reference filled in from namespace found in domain level on either
                   10212: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  10213: 
                   10214: =item *
                   10215: 
1.860     raeburn  10216: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   10217: domain level either on specified domain server ($uhome) or primary domain 
                   10218: server ($udom and $uhome are optional)
1.806     raeburn  10219: 
1.943     raeburn  10220: =item * 
                   10221: 
                   10222: get_domain_defaults($target_domain) : returns hash with defaults for
                   10223: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   10224: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   10225: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   10226: Values are retrieved from cache (if current), or from domain's configuration.db
                   10227: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   10228: or lonTabs/domain.tab. 
                   10229: 
                   10230: %domdefaults = &get_auth_defaults($target_domain);
                   10231: 
1.243     albertel 10232: =back
                   10233: 
                   10234: =head2 Network Status Functions
                   10235: 
                   10236: =over 4
1.191     harris41 10237: 
                   10238: =item *
                   10239: 
                   10240: dirlist($uri) : return directory list based on URI
                   10241: 
                   10242: =item *
                   10243: 
1.243     albertel 10244: spareserver() : find server with least workload from spare.tab
                   10245: 
1.986     foxr     10246: 
                   10247: =item *
                   10248: 
                   10249: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   10250: if there is no corresponding loncapa host.
                   10251: 
1.243     albertel 10252: =back
                   10253: 
1.986     foxr     10254: 
1.243     albertel 10255: =head2 Apache Request
                   10256: 
                   10257: =over 4
1.191     harris41 10258: 
                   10259: =item *
                   10260: 
1.243     albertel 10261: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   10262: localhost, posts hash
                   10263: 
                   10264: =back
                   10265: 
                   10266: =head2 Data to String to Data
                   10267: 
                   10268: =over 4
1.191     harris41 10269: 
                   10270: =item *
                   10271: 
1.243     albertel 10272: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   10273: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 10274: 
                   10275: =item *
                   10276: 
1.243     albertel 10277: hashref2str($hashref) : convert a hashref into a string complete with
                   10278: escaping and '=' and '&' separators, supports elements that are
                   10279: arrayrefs and hashrefs
1.191     harris41 10280: 
                   10281: =item *
                   10282: 
1.243     albertel 10283: arrayref2str($arrayref) : convert an arrayref into a string complete
                   10284: with escaping and '&' separators, supports elements that are arrayrefs
                   10285: and hashrefs
1.191     harris41 10286: 
                   10287: =item *
                   10288: 
1.243     albertel 10289: str2hash($string) : convert string to hash using unescaping and
                   10290: splitting on '=' and '&', supports elements that are arrayrefs and
                   10291: hashrefs
1.191     harris41 10292: 
                   10293: =item *
                   10294: 
1.243     albertel 10295: str2array($string) : convert string to hash using unescaping and
                   10296: splitting on '&', supports elements that are arrayrefs and hashrefs
                   10297: 
                   10298: =back
                   10299: 
                   10300: =head2 Logging Routines
                   10301: 
                   10302: =over 4
                   10303: 
                   10304: These routines allow one to make log messages in the lonnet.log and
                   10305: lonnet.perm logfiles.
1.191     harris41 10306: 
                   10307: =item *
                   10308: 
1.243     albertel 10309: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 10310: 
                   10311: =item *
                   10312: 
1.243     albertel 10313: logthis() : append message to the normal lonnet.log file, it gets
                   10314: preiodically rolled over and deleted.
1.191     harris41 10315: 
                   10316: =item *
                   10317: 
1.243     albertel 10318: logperm() : append a permanent message to lonnet.perm.log, this log
                   10319: file never gets deleted by any automated portion of the system, only
                   10320: messages of critical importance should go in here.
                   10321: 
                   10322: =back
                   10323: 
                   10324: =head2 General File Helper Routines
                   10325: 
                   10326: =over 4
1.191     harris41 10327: 
                   10328: =item *
                   10329: 
1.481     raeburn  10330: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   10331: (a) files in /uploaded
                   10332:   (i) If a local copy of the file exists - 
                   10333:       compares modification date of local copy with last-modified date for 
                   10334:       definitive version stored on home server for course. If local copy is 
                   10335:       stale, requests a new version from the home server and stores it. 
                   10336:       If the original has been removed from the home server, then local copy 
                   10337:       is unlinked.
                   10338:   (ii) If local copy does not exist -
                   10339:       requests the file from the home server and stores it. 
                   10340:   
                   10341:   If $caller is 'uploadrep':  
                   10342:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   10343:     for request for files originally uploaded via DOCS. 
                   10344:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   10345:   
                   10346:   Otherwise:
                   10347:      This indicates a call from the content generation phase of the request.
                   10348:      -  returns the entire contents of the file or -1.
                   10349:      
                   10350: (b) files in /res
                   10351:    - returns the entire contents of a file or -1; 
                   10352:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 10353: 
1.712     albertel 10354: 
                   10355: =item *
                   10356: 
                   10357: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   10358:                   reference
                   10359: 
                   10360: returns either a stat() list of data about the file or an empty list
                   10361: if the file doesn't exist or couldn't find out about it (connection
                   10362: problems or user unknown)
                   10363: 
1.191     harris41 10364: =item *
                   10365: 
1.243     albertel 10366: filelocation($dir,$file) : returns file system location of a file
                   10367: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   10368: directory that relative $file lookups are to looked in ($dir of /a/dir
                   10369: and a file of ../bob will become /a/bob)
1.191     harris41 10370: 
                   10371: =item *
                   10372: 
                   10373: hreflocation($dir,$file) : returns file system location or a URL; same as
                   10374: filelocation except for hrefs
                   10375: 
                   10376: =item *
                   10377: 
                   10378: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   10379: 
1.243     albertel 10380: =back
                   10381: 
1.608     albertel 10382: =head2 Usererfile file routines (/uploaded*)
                   10383: 
                   10384: =over 4
                   10385: 
                   10386: =item *
                   10387: 
                   10388: userfileupload(): main rotine for putting a file in a user or course's
                   10389:                   filespace, arguments are,
                   10390: 
1.620     albertel 10391:  formname - required - this is the name of the element in $env where the
1.608     albertel 10392:            filename, and the contents of the file to create/modifed exist
1.620     albertel 10393:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   10394:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 10395:  coursedoc - if true, store the file in the course of the active role
                   10396:              of the current user
                   10397:  subdir - required - subdirectory to put the file in under ../userfiles/
                   10398:          if undefined, it will be placed in "unknown"
                   10399: 
                   10400:  (This routine calls clean_filename() to remove any dangerous
                   10401:  characters from the filename, and then calls finuserfileupload() to
                   10402:  complete the transaction)
                   10403: 
                   10404:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10405:  and /adm/notfound.html if unsuccessful
                   10406: 
                   10407: =item *
                   10408: 
                   10409: clean_filename(): routine for cleaing a filename up for storage in
                   10410:                  userfile space, argument is:
                   10411: 
                   10412:  filename - proposed filename
                   10413: 
                   10414: returns: the new clean filename
                   10415: 
                   10416: =item *
                   10417: 
                   10418: finishuserfileupload(): routine that creaes and sends the file to
                   10419: userspace, probably shouldn't be called directly
                   10420: 
                   10421:   docuname: username or courseid of destination for the file
                   10422:   docudom: domain of user/course of destination for the file
                   10423:   formname: same as for userfileupload()
                   10424:   fname: filename (inculding subdirectories) for the file
                   10425: 
                   10426:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10427:  and /adm/notfound.html if unsuccessful
                   10428: 
                   10429: =item *
                   10430: 
                   10431: renameuserfile(): renames an existing userfile to a new name
                   10432: 
                   10433:   Args:
                   10434:    docuname: username or courseid of destination for the file
                   10435:    docudom: domain of user/course of destination for the file
                   10436:    old: current file name (including any subdirs under userfiles)
                   10437:    new: desired file name (including any subdirs under userfiles)
                   10438: 
                   10439: =item *
                   10440: 
                   10441: mkdiruserfile(): creates a directory is a userfiles dir
                   10442: 
                   10443:   Args:
                   10444:    docuname: username or courseid of destination for the file
                   10445:    docudom: domain of user/course of destination for the file
                   10446:    dir: dir to create (including any subdirs under userfiles)
                   10447: 
                   10448: =item *
                   10449: 
                   10450: removeuserfile(): removes a file that exists in userfiles
                   10451: 
                   10452:   Args:
                   10453:    docuname: username or courseid of destination for the file
                   10454:    docudom: domain of user/course of destination for the file
                   10455:    fname: filname to delete (including any subdirs under userfiles)
                   10456: 
                   10457: =item *
                   10458: 
                   10459: removeuploadedurl(): convience function for removeuserfile()
                   10460: 
                   10461:   Args:
                   10462:    url:  a full /uploaded/... url to delete
                   10463: 
1.747     albertel 10464: =item * 
                   10465: 
                   10466: get_portfile_permissions():
                   10467:   Args:
                   10468:     domain: domain of user or course contain the portfolio files
                   10469:     user: name of user or num of course contain the portfolio files
                   10470:   Returns:
                   10471:     hashref of a dump of the proper file_permissions.db
                   10472:    
                   10473: 
                   10474: =item * 
                   10475: 
                   10476: get_access_controls():
                   10477: 
                   10478: Args:
                   10479:   current_permissions: the hash ref returned from get_portfile_permissions()
                   10480:   group: (optional) the group you want the files associated with
                   10481:   file: (optional) the file you want access info on
                   10482: 
                   10483: Returns:
1.749     raeburn  10484:     a hash (keys are file names) of hashes containing
                   10485:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   10486:         values are XML containing access control settings (see below) 
1.747     albertel 10487: 
                   10488: Internal notes:
                   10489: 
1.749     raeburn  10490:  access controls are stored in file_permissions.db as key=value pairs.
                   10491:     key -> path to file/file_name\0uniqueID:scope_end_start
                   10492:         where scope -> public,guest,course,group,domains or users.
                   10493:               end -> UNIX time for end of access (0 -> no end date)
                   10494:               start -> UNIX time for start of access
                   10495: 
                   10496:     value -> XML description of access control
                   10497:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   10498:             <start></start>
                   10499:             <end></end>
                   10500: 
                   10501:             <password></password>  for scope type = guest
                   10502: 
                   10503:             <domain></domain>     for scope type = course or group
                   10504:             <number></number>
                   10505:             <roles id="">
                   10506:              <role></role>
                   10507:              <access></access>
                   10508:              <section></section>
                   10509:              <group></group>
                   10510:             </roles>
                   10511: 
                   10512:             <dom></dom>         for scope type = domains
                   10513: 
                   10514:             <users>             for scope type = users
                   10515:              <user>
                   10516:               <uname></uname>
                   10517:               <udom></udom>
                   10518:              </user>
                   10519:             </users>
                   10520:            </scope> 
                   10521:               
                   10522:  Access data is also aggregated for each file in an additional key=value pair:
                   10523:  key -> path to file/file_name\0accesscontrol 
                   10524:  value -> reference to hash
                   10525:           hash contains key = value pairs
                   10526:           where key = uniqueID:scope_end_start
                   10527:                 value = UNIX time record was last updated
                   10528: 
                   10529:           Used to improve speed of look-ups of access controls for each file.  
                   10530:  
                   10531:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   10532: 
                   10533: modify_access_controls():
                   10534: 
                   10535: Modifies access controls for a portfolio file
                   10536: Args
                   10537: 1. file name
                   10538: 2. reference to hash of required changes,
                   10539: 3. domain
                   10540: 4. username
                   10541:   where domain,username are the domain of the portfolio owner 
                   10542:   (either a user or a course) 
                   10543: 
                   10544: Returns:
                   10545: 1. result of additions or updates ('ok' or 'error', with error message). 
                   10546: 2. result of deletions ('ok' or 'error', with error message).
                   10547: 3. reference to hash of any new or updated access controls.
                   10548: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   10549:    key = integer (inbound ID)
                   10550:    value = uniqueID  
1.747     albertel 10551: 
1.608     albertel 10552: =back
                   10553: 
1.243     albertel 10554: =head2 HTTP Helper Routines
                   10555: 
                   10556: =over 4
                   10557: 
1.191     harris41 10558: =item *
                   10559: 
                   10560: escape() : unpack non-word characters into CGI-compatible hex codes
                   10561: 
                   10562: =item *
                   10563: 
                   10564: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   10565: 
1.243     albertel 10566: =back
                   10567: 
                   10568: =head1 PRIVATE SUBROUTINES
                   10569: 
                   10570: =head2 Underlying communication routines (Shouldn't call)
                   10571: 
                   10572: =over 4
                   10573: 
                   10574: =item *
                   10575: 
                   10576: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   10577: 
                   10578: =item *
                   10579: 
                   10580: reply() : uses subreply to send a message to remote machine, logs all failures
                   10581: 
                   10582: =item *
                   10583: 
                   10584: critical() : passes a critical message to another server; if cannot
                   10585: get through then place message in connection buffer directory and
                   10586: returns con_delayed, if incapable of saving message, returns
                   10587: con_failed
                   10588: 
                   10589: =item *
                   10590: 
                   10591: reconlonc() : tries to reconnect lonc client processes.
                   10592: 
                   10593: =back
                   10594: 
                   10595: =head2 Resource Access Logging
                   10596: 
                   10597: =over 4
                   10598: 
                   10599: =item *
                   10600: 
                   10601: flushcourselogs() : flush (save) buffer logs and access logs
                   10602: 
                   10603: =item *
                   10604: 
                   10605: courselog($what) : save message for course in hash
                   10606: 
                   10607: =item *
                   10608: 
                   10609: courseacclog($what) : save message for course using &courselog().  Perform
                   10610: special processing for specific resource types (problems, exams, quizzes, etc).
                   10611: 
1.191     harris41 10612: =item *
                   10613: 
                   10614: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   10615: as a PerlChildExitHandler
1.243     albertel 10616: 
                   10617: =back
                   10618: 
                   10619: =head2 Other
                   10620: 
                   10621: =over 4
                   10622: 
                   10623: =item *
                   10624: 
                   10625: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 10626: 
                   10627: =back
                   10628: 
                   10629: =cut
1.877     foxr     10630: 

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