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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1001  ! raeburn     4: # $Id: lonnet.pm,v 1.1000 2009/05/13 01:30:49 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') {
                   1329:         foreach my $item ('official','unofficial') {
                   1330:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1331:         }
                   1332:     }
1.989     raeburn  1333:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1334:         foreach my $item ('inststatustypes','inststatusorder') {
                   1335:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1336:         }
                   1337:     }
1.943     raeburn  1338:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1339:                                   $cachetime);
                   1340:     return %domdefaults;
                   1341: }
                   1342: 
1.344     www      1343: # --------------------------------------------------- Assign a key to a student
                   1344: 
                   1345: sub assign_access_key {
1.364     www      1346: #
                   1347: # a valid key looks like uname:udom#comments
                   1348: # comments are being appended
                   1349: #
1.498     www      1350:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1351:     $kdom=
1.620     albertel 1352:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1353:     $knum=
1.620     albertel 1354:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1355:     $cdom=
1.620     albertel 1356:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1357:     $cnum=
1.620     albertel 1358:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1359:     $udom=$env{'user.name'} unless (defined($udom));
                   1360:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1361:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1362:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1363:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1364:                                                   # assigned to this person
                   1365:                                                   # - this should not happen,
1.345     www      1366:                                                   # unless something went wrong
                   1367:                                                   # the first time around
                   1368: # ready to assign
1.364     www      1369:         $logentry=$1.'; '.$logentry;
1.496     www      1370:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1371:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1372: # key now belongs to user
1.346     www      1373: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1374:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1375:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1376:                 return 'ok';
                   1377:             } else {
                   1378:                 return 
                   1379:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1380: 	    }
                   1381:         } else {
                   1382:             return 'error: Could not assign key, try again later.';
                   1383:         }
1.364     www      1384:     } elsif (!$existing{$ckey}) {
1.345     www      1385: # the key does not exist
                   1386: 	return 'error: The key does not exist';
                   1387:     } else {
                   1388: # the key is somebody else's
                   1389: 	return 'error: The key is already in use';
                   1390:     }
1.344     www      1391: }
                   1392: 
1.364     www      1393: # ------------------------------------------ put an additional comment on a key
                   1394: 
                   1395: sub comment_access_key {
                   1396: #
                   1397: # a valid key looks like uname:udom#comments
                   1398: # comments are being appended
                   1399: #
                   1400:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1401:     $cdom=
1.620     albertel 1402:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1403:     $cnum=
1.620     albertel 1404:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1405:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1406:     if ($existing{$ckey}) {
                   1407:         $existing{$ckey}.='; '.$logentry;
                   1408: # ready to assign
1.367     www      1409:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1410:                                                  $cdom,$cnum) eq 'ok') {
                   1411: 	    return 'ok';
                   1412:         } else {
                   1413: 	    return 'error: Count not store comment.';
                   1414:         }
                   1415:     } else {
                   1416: # the key does not exist
                   1417: 	return 'error: The key does not exist';
                   1418:     }
                   1419: }
                   1420: 
1.344     www      1421: # ------------------------------------------------------ Generate a set of keys
                   1422: 
                   1423: sub generate_access_keys {
1.364     www      1424:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1425:     $cdom=
1.620     albertel 1426:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1427:     $cnum=
1.620     albertel 1428:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1429:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1430:     unless (($cdom) && ($cnum)) { return 0; }
                   1431:     if ($number>10000) { return 0; }
                   1432:     sleep(2); # make sure don't get same seed twice
                   1433:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1434:     my $total=0;
                   1435:     for (my $i=1;$i<=$number;$i++) {
                   1436:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1437:                   sprintf("%lx",int(100000*rand)).'-'.
                   1438:                   sprintf("%lx",int(100000*rand));
                   1439:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1440:        $newkey=~s/0/h/g; # and also 0 and O
                   1441:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1442:        if ($existing{$newkey}) {
                   1443:            $i--;
                   1444:        } else {
1.364     www      1445: 	  if (&put('accesskeys',
                   1446:               { $newkey => '# generated '.localtime().
1.620     albertel 1447:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1448:                            '; '.$logentry },
                   1449: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1450:               $total++;
                   1451: 	  }
                   1452:        }
                   1453:     }
1.620     albertel 1454:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1455:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1456:     return $total;
                   1457: }
                   1458: 
                   1459: # ------------------------------------------------------- Validate an accesskey
                   1460: 
                   1461: sub validate_access_key {
                   1462:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1463:     $cdom=
1.620     albertel 1464:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1465:     $cnum=
1.620     albertel 1466:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1467:     $udom=$env{'user.domain'} unless (defined($udom));
                   1468:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1469:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1470:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1471: }
                   1472: 
                   1473: # ------------------------------------- Find the section of student in a course
1.652     albertel 1474: sub devalidate_getsection_cache {
                   1475:     my ($udom,$unam,$courseid)=@_;
                   1476:     my $hashid="$udom:$unam:$courseid";
                   1477:     &devalidate_cache_new('getsection',$hashid);
                   1478: }
1.298     matthew  1479: 
1.815     albertel 1480: sub courseid_to_courseurl {
                   1481:     my ($courseid) = @_;
                   1482:     #already url style courseid
                   1483:     return $courseid if ($courseid =~ m{^/});
                   1484: 
                   1485:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1486: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1487: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1488: 	return "/$cdom/$cnum";
                   1489:     }
                   1490: 
                   1491:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1492:     if (exists($courseinfo{'num'})) {
                   1493: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1494:     }
                   1495: 
                   1496:     return undef;
                   1497: }
                   1498: 
1.298     matthew  1499: sub getsection {
                   1500:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1501:     my $cachetime=1800;
1.551     albertel 1502: 
                   1503:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1504:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1505:     if (defined($cached)) { return $result; }
                   1506: 
1.298     matthew  1507:     my %Pending; 
                   1508:     my %Expired;
                   1509:     #
                   1510:     # Each role can either have not started yet (pending), be active, 
                   1511:     #    or have expired.
                   1512:     #
                   1513:     # If there is an active role, we are done.
                   1514:     #
                   1515:     # If there is more than one role which has not started yet, 
                   1516:     #     choose the one which will start sooner
                   1517:     # If there is one role which has not started yet, return it.
                   1518:     #
                   1519:     # If there is more than one expired role, choose the one which ended last.
                   1520:     # If there is a role which has expired, return it.
                   1521:     #
1.815     albertel 1522:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1523:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1524:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1525:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1526:         my $section=$1;
                   1527:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1528:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1529:         my $now=time;
1.548     albertel 1530:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1531:             $Expired{$end}=$section;
                   1532:             next;
                   1533:         }
1.548     albertel 1534:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1535:             $Pending{$start}=$section;
                   1536:             next;
                   1537:         }
1.599     albertel 1538:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1539:     }
                   1540:     #
                   1541:     # Presumedly there will be few matching roles from the above
                   1542:     # loop and the sorting time will be negligible.
                   1543:     if (scalar(keys(%Pending))) {
                   1544:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1545:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1546:     } 
                   1547:     if (scalar(keys(%Expired))) {
                   1548:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1549:         my $time = pop(@sorted);
1.599     albertel 1550:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1551:     }
1.599     albertel 1552:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1553: }
1.70      www      1554: 
1.599     albertel 1555: sub save_cache {
                   1556:     &purge_remembered();
1.722     albertel 1557:     #&Apache::loncommon::validate_page();
1.620     albertel 1558:     undef(%env);
1.780     albertel 1559:     undef($env_loaded);
1.599     albertel 1560: }
1.452     albertel 1561: 
1.599     albertel 1562: my $to_remember=-1;
                   1563: my %remembered;
                   1564: my %accessed;
                   1565: my $kicks=0;
                   1566: my $hits=0;
1.849     albertel 1567: sub make_key {
                   1568:     my ($name,$id) = @_;
1.872     albertel 1569:     if (length($id) > 65 
                   1570: 	&& length(&escape($id)) > 200) {
                   1571: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1572:     }
1.849     albertel 1573:     return &escape($name.':'.$id);
                   1574: }
                   1575: 
1.599     albertel 1576: sub devalidate_cache_new {
                   1577:     my ($name,$id,$debug) = @_;
                   1578:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1579:     $id=&make_key($name,$id);
1.599     albertel 1580:     $memcache->delete($id);
                   1581:     delete($remembered{$id});
                   1582:     delete($accessed{$id});
                   1583: }
                   1584: 
                   1585: sub is_cached_new {
                   1586:     my ($name,$id,$debug) = @_;
1.849     albertel 1587:     $id=&make_key($name,$id);
1.599     albertel 1588:     if (exists($remembered{$id})) {
                   1589: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1590: 	$accessed{$id}=[&gettimeofday()];
                   1591: 	$hits++;
                   1592: 	return ($remembered{$id},1);
                   1593:     }
                   1594:     my $value = $memcache->get($id);
                   1595:     if (!(defined($value))) {
                   1596: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1597: 	return (undef,undef);
1.416     albertel 1598:     }
1.599     albertel 1599:     if ($value eq '__undef__') {
                   1600: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1601: 	$value=undef;
                   1602:     }
                   1603:     &make_room($id,$value,$debug);
                   1604:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1605:     return ($value,1);
                   1606: }
                   1607: 
                   1608: sub do_cache_new {
                   1609:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1610:     $id=&make_key($name,$id);
1.599     albertel 1611:     my $setvalue=$value;
                   1612:     if (!defined($setvalue)) {
                   1613: 	$setvalue='__undef__';
                   1614:     }
1.623     albertel 1615:     if (!defined($time) ) {
                   1616: 	$time=600;
                   1617:     }
1.599     albertel 1618:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1619:     my $result = $memcache->set($id,$setvalue,$time);
                   1620:     if (! $result) {
1.872     albertel 1621: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1622: 	$memcache->disconnect_all();
1.872     albertel 1623:     }
1.600     albertel 1624:     # need to make a copy of $value
1.919     albertel 1625:     &make_room($id,$value,$debug);
1.599     albertel 1626:     return $value;
                   1627: }
                   1628: 
                   1629: sub make_room {
                   1630:     my ($id,$value,$debug)=@_;
1.919     albertel 1631: 
                   1632:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1633:                                     : $value;
1.599     albertel 1634:     if ($to_remember<0) { return; }
                   1635:     $accessed{$id}=[&gettimeofday()];
                   1636:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1637:     my $to_kick;
                   1638:     my $max_time=0;
                   1639:     foreach my $other (keys(%accessed)) {
                   1640: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1641: 	    $to_kick=$other;
                   1642: 	    $max_time=&tv_interval($accessed{$other});
                   1643: 	}
                   1644:     }
                   1645:     delete($remembered{$to_kick});
                   1646:     delete($accessed{$to_kick});
                   1647:     $kicks++;
                   1648:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1649:     return;
                   1650: }
                   1651: 
1.599     albertel 1652: sub purge_remembered {
1.604     albertel 1653:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1654:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1655:     undef(%remembered);
                   1656:     undef(%accessed);
1.428     albertel 1657: }
1.70      www      1658: # ------------------------------------- Read an entry from a user's environment
                   1659: 
                   1660: sub userenvironment {
                   1661:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1662:     my $items;
                   1663:     foreach my $item (@what) {
                   1664:         $items.=&escape($item).'&';
                   1665:     }
                   1666:     $items=~s/\&$//;
1.70      www      1667:     my %returnhash=();
                   1668:     my @answer=split(/\&/,
1.976     raeburn  1669:                 &reply('get:'.$udom.':'.$unam.':environment:'.$items,
1.70      www      1670:                       &homeserver($unam,$udom)));
                   1671:     my $i;
                   1672:     for ($i=0;$i<=$#what;$i++) {
                   1673: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1674:     }
                   1675:     return %returnhash;
1.1       albertel 1676: }
                   1677: 
1.617     albertel 1678: # ---------------------------------------------------------- Get a studentphoto
                   1679: sub studentphoto {
                   1680:     my ($udom,$unam,$ext) = @_;
                   1681:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1682:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1683:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1684:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1685:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1686:             } else {
                   1687:                 my ($result,$perm_reqd)=
1.707     albertel 1688: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1689:                 if ($result eq 'ok') {
                   1690:                     if (!($perm_reqd eq 'yes')) {
                   1691:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1692:                     }
                   1693:                 }
                   1694:             }
                   1695:         }
                   1696:     } else {
                   1697:         my ($result,$perm_reqd) = 
1.707     albertel 1698: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1699:         if ($result eq 'ok') {
                   1700:             if (!($perm_reqd eq 'yes')) {
                   1701:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1702:             }
                   1703:         }
                   1704:     }
                   1705:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1706: }
                   1707: 
                   1708: sub retrievestudentphoto {
                   1709:     my ($udom,$unam,$ext,$type) = @_;
                   1710:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1711:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1712:     if ($ret eq 'ok') {
                   1713:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1714:         if ($type eq 'thumbnail') {
                   1715:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1716:         }
                   1717:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1718:         return $tokenurl;
                   1719:     } else {
                   1720:         if ($type eq 'thumbnail') {
                   1721:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1722:         } else { 
                   1723:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1724:         }
1.617     albertel 1725:     }
                   1726: }
                   1727: 
1.263     www      1728: # -------------------------------------------------------------------- New chat
                   1729: 
                   1730: sub chatsend {
1.724     raeburn  1731:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1732:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1733:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1734:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1735:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1736: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1737: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1738: }
                   1739: 
                   1740: # ------------------------------------------ Find current version of a resource
                   1741: 
                   1742: sub getversion {
                   1743:     my $fname=&clutter(shift);
                   1744:     unless ($fname=~/^\/res\//) { return -1; }
                   1745:     return &currentversion(&filelocation('',$fname));
                   1746: }
                   1747: 
                   1748: sub currentversion {
                   1749:     my $fname=shift;
1.599     albertel 1750:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1751:     if (defined($cached)) { return $result; }
1.292     www      1752:     my $author=$fname;
                   1753:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1754:     my ($udom,$uname)=split(/\//,$author);
                   1755:     my $home=homeserver($uname,$udom);
                   1756:     if ($home eq 'no_host') { 
                   1757:         return -1; 
                   1758:     }
                   1759:     my $answer=reply("currentversion:$fname",$home);
                   1760:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1761: 	return -1;
                   1762:     }
1.599     albertel 1763:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1764: }
                   1765: 
1.1       albertel 1766: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1767: 
1.1       albertel 1768: sub subscribe {
                   1769:     my $fname=shift;
1.761     raeburn  1770:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1771:     $fname=~s/[\n\r]//g;
1.1       albertel 1772:     my $author=$fname;
                   1773:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1774:     my ($udom,$uname)=split(/\//,$author);
                   1775:     my $home=homeserver($uname,$udom);
1.335     albertel 1776:     if ($home eq 'no_host') {
                   1777:         return 'not_found';
1.1       albertel 1778:     }
                   1779:     my $answer=reply("sub:$fname",$home);
1.64      www      1780:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1781: 	$answer.=' by '.$home;
                   1782:     }
1.1       albertel 1783:     return $answer;
                   1784: }
                   1785:     
1.8       www      1786: # -------------------------------------------------------------- Replicate file
                   1787: 
                   1788: sub repcopy {
                   1789:     my $filename=shift;
1.23      www      1790:     $filename=~s/\/+/\//g;
1.607     raeburn  1791:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1792:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1793:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1794: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1795: 	return &repcopy_userfile($filename);
                   1796:     }
1.532     albertel 1797:     $filename=~s/[\n\r]//g;
1.8       www      1798:     my $transname="$filename.in.transfer";
1.828     www      1799: # FIXME: this should flock
1.607     raeburn  1800:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1801:     my $remoteurl=subscribe($filename);
1.64      www      1802:     if ($remoteurl =~ /^con_lost by/) {
                   1803: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1804:            return 'unavailable';
1.8       www      1805:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1806: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1807: 	   return 'not_found';
1.64      www      1808:     } elsif ($remoteurl =~ /^rejected by/) {
                   1809: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1810:            return 'forbidden';
1.20      www      1811:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1812:            return 'ok';
1.8       www      1813:     } else {
1.290     www      1814:         my $author=$filename;
                   1815:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1816:         my ($udom,$uname)=split(/\//,$author);
                   1817:         my $home=homeserver($uname,$udom);
                   1818:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1819:            my @parts=split(/\//,$filename);
                   1820:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1821:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1822:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1823: 	       return 'bad_request';
1.8       www      1824:            }
                   1825:            my $count;
                   1826:            for ($count=5;$count<$#parts;$count++) {
                   1827:                $path.="/$parts[$count]";
                   1828:                if ((-e $path)!=1) {
                   1829: 		   mkdir($path,0777);
                   1830:                }
                   1831:            }
                   1832:            my $ua=new LWP::UserAgent;
                   1833:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1834:            my $response=$ua->request($request,$transname);
                   1835:            if ($response->is_error()) {
                   1836: 	       unlink($transname);
                   1837:                my $message=$response->status_line;
1.672     albertel 1838:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1839:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1840:                return 'unavailable';
1.8       www      1841:            } else {
1.16      www      1842: 	       if ($remoteurl!~/\.meta$/) {
                   1843:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1844:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1845:                   if ($mresponse->is_error()) {
                   1846: 		      unlink($filename.'.meta');
                   1847:                       &logthis(
1.672     albertel 1848:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1849:                   }
                   1850: 	       }
1.8       www      1851:                rename($transname,$filename);
1.607     raeburn  1852:                return 'ok';
1.8       www      1853:            }
1.290     www      1854:        }
1.8       www      1855:     }
1.330     www      1856: }
                   1857: 
                   1858: # ------------------------------------------------ Get server side include body
                   1859: sub ssi_body {
1.381     albertel 1860:     my ($filelink,%form)=@_;
1.606     matthew  1861:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1862:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1863:     }
1.953     www      1864:     my $output='';
                   1865:     my $response;
1.980     raeburn  1866:     if ($filelink=~/^https?\:/) {
1.954     raeburn  1867:        ($output,$response)=&externalssi($filelink);
1.953     www      1868:     } else {
                   1869:        ($output,$response)=&ssi($filelink,%form);
                   1870:     }
1.778     albertel 1871:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1872:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 1873:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      1874:     if (wantarray) {
                   1875:         return ($output, $response);
                   1876:     } else {
                   1877:         return $output;
                   1878:     }
1.8       www      1879: }
                   1880: 
1.15      www      1881: # --------------------------------------------------------- Server Side Include
                   1882: 
1.782     albertel 1883: sub absolute_url {
                   1884:     my ($host_name) = @_;
                   1885:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1886:     if ($host_name eq '') {
                   1887: 	$host_name = $ENV{'SERVER_NAME'};
                   1888:     }
                   1889:     return $protocol.$host_name;
                   1890: }
                   1891: 
1.942     foxr     1892: #
                   1893: #   Server side include.
                   1894: # Parameters:
                   1895: #  fn     Possibly encrypted resource name/id.
                   1896: #  form   Hash that describes how the rendering should be done
                   1897: #         and other things.
1.944     foxr     1898: # Returns:
1.950     raeburn  1899: #   Scalar context: The content of the response.
                   1900: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     1901: #     
1.15      www      1902: sub ssi {
                   1903: 
1.944     foxr     1904:     my ($fn,%form)=@_;
1.15      www      1905:     my $ua=new LWP::UserAgent;
1.23      www      1906:     my $request;
1.711     albertel 1907: 
                   1908:     $form{'no_update_last_known'}=1;
1.895     albertel 1909:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1910:     if (%form) {
1.782     albertel 1911:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  1912:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      1913:     } else {
1.782     albertel 1914:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1915:     }
                   1916: 
1.15      www      1917:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1918:     my $response=$ua->request($request);
                   1919: 
1.944     foxr     1920:     if (wantarray) {
                   1921: 	return ($response->content, $response);
                   1922:     } else {
                   1923: 	return $response->content;
1.942     foxr     1924:     }
1.324     www      1925: }
                   1926: 
                   1927: sub externalssi {
                   1928:     my ($url)=@_;
                   1929:     my $ua=new LWP::UserAgent;
                   1930:     my $request=new HTTP::Request('GET',$url);
                   1931:     my $response=$ua->request($request);
1.954     raeburn  1932:     if (wantarray) {
                   1933:         return ($response->content, $response);
                   1934:     } else {
                   1935:         return $response->content;
                   1936:     }
1.15      www      1937: }
1.254     www      1938: 
1.492     albertel 1939: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1940: 
                   1941: sub allowuploaded {
                   1942:     my ($srcurl,$url)=@_;
                   1943:     $url=&clutter(&declutter($url));
                   1944:     my $dir=$url;
                   1945:     $dir=~s/\/[^\/]+$//;
                   1946:     my %httpref=();
                   1947:     my $httpurl=&hreflocation('',$url);
                   1948:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  1949:     &Apache::lonnet::appenv(\%httpref);
1.254     www      1950: }
1.477     raeburn  1951: 
1.478     albertel 1952: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1953: # input: action, courseID, current domain, intended
1.637     raeburn  1954: #        path to file, source of file, instruction to parse file for objects,
                   1955: #        ref to hash for embedded objects,
                   1956: #        ref to hash for codebase of java objects.
                   1957: #
1.485     raeburn  1958: # output: url to file (if action was uploaddoc), 
                   1959: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1960: #
1.478     albertel 1961: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1962: # course.
1.477     raeburn  1963: #
1.478     albertel 1964: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1965: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1966: #          course's home server.
1.477     raeburn  1967: #
1.478     albertel 1968: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1969: #          be copied from $source (current location) to 
                   1970: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1971: #         and will then be copied to
                   1972: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1973: #         course's home server.
1.485     raeburn  1974: #
1.481     raeburn  1975: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1976: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1977: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1978: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1979: #         in course's home server.
1.637     raeburn  1980: #
1.477     raeburn  1981: 
                   1982: sub process_coursefile {
1.638     albertel 1983:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1984:     my $fetchresult;
1.638     albertel 1985:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1986:     if ($action eq 'propagate') {
1.638     albertel 1987:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1988: 			     $home);
1.481     raeburn  1989:     } else {
1.477     raeburn  1990:         my $fpath = '';
                   1991:         my $fname = $file;
1.478     albertel 1992:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1993:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1994:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1995:         if ($action eq 'copy') {
                   1996:             if ($source eq '') {
                   1997:                 $fetchresult = 'no source file';
                   1998:                 return $fetchresult;
                   1999:             } else {
                   2000:                 my $destination = $filepath.'/'.$fname;
                   2001:                 rename($source,$destination);
                   2002:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2003:                                  $home);
1.481     raeburn  2004:             }
                   2005:         } elsif ($action eq 'uploaddoc') {
                   2006:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2007:             print $fh $env{'form.'.$source};
1.481     raeburn  2008:             close($fh);
1.637     raeburn  2009:             if ($parser eq 'parse') {
1.961     raeburn  2010:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
1.637     raeburn  2011:                 unless ($parse_result eq 'ok') {
                   2012:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2013:                 }
                   2014:             }
1.477     raeburn  2015:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2016:                                  $home);
1.481     raeburn  2017:             if ($fetchresult eq 'ok') {
                   2018:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2019:             } else {
                   2020:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2021:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2022:                 return '/adm/notfound.html';
                   2023:             }
1.477     raeburn  2024:         }
                   2025:     }
1.485     raeburn  2026:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2027:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2028:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2029:     }
                   2030:     return $fetchresult;
                   2031: }
                   2032: 
1.637     raeburn  2033: sub build_filepath {
                   2034:     my ($fpath) = @_;
                   2035:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2036:     unless ($fpath eq '') {
                   2037:         my @parts=split('/',$fpath);
                   2038:         foreach my $part (@parts) {
                   2039:             $filepath.= '/'.$part;
                   2040:             if ((-e $filepath)!=1) {
                   2041:                 mkdir($filepath,0777);
                   2042:             }
                   2043:         }
                   2044:     }
                   2045:     return $filepath;
                   2046: }
                   2047: 
                   2048: sub store_edited_file {
1.638     albertel 2049:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2050:     my $file = $primary_url;
                   2051:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2052:     my $fpath = '';
                   2053:     my $fname = $file;
                   2054:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2055:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2056:     my $filepath = &build_filepath($fpath);
                   2057:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2058:     print $fh $content;
                   2059:     close($fh);
1.638     albertel 2060:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2061:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2062: 			  $home);
1.637     raeburn  2063:     if ($$fetchresult eq 'ok') {
                   2064:         return '/uploaded/'.$fpath.'/'.$fname;
                   2065:     } else {
1.638     albertel 2066:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2067: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2068:         return '/adm/notfound.html';
                   2069:     }
                   2070: }
                   2071: 
1.531     albertel 2072: sub clean_filename {
1.831     albertel 2073:     my ($fname,$args)=@_;
1.315     www      2074: # Replace Windows backslashes by forward slashes
1.257     www      2075:     $fname=~s/\\/\//g;
1.831     albertel 2076:     if (!$args->{'keep_path'}) {
                   2077:         # Get rid of everything but the actual filename
                   2078: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2079:     }
1.315     www      2080: # Replace spaces by underscores
                   2081:     $fname=~s/\s+/\_/g;
                   2082: # Replace all other weird characters by nothing
1.831     albertel 2083:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2084: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2085: # numbers
                   2086:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2087:     return $fname;
                   2088: }
1.984     neumanie 2089: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
                   2090: sub resizeImage {
                   2091: 	my($img_url) = @_;	
                   2092: 	my $ima = Image::Magick->new;                       
                   2093:         $ima->Read($img_url);
                   2094: 	if($ima->Get('width') > 400)
                   2095: 	{
                   2096: 		my $factor = $ima->Get('width')/400;
                   2097:              	$ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
                   2098: 	}
                   2099: 	if($ima->Get('height') > 500)
                   2100:         {
                   2101:         	my $factor = $ima->Get('height')/500;
                   2102:                 $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
                   2103:         } 
                   2104: 		
                   2105: 	$ima->Write($img_url);
                   2106: }
1.531     albertel 2107: 
1.977     amueller 2108: #Wrapper function for userphotoupload
                   2109: sub userphotoupload
                   2110: {
                   2111: 	my($formname,$subdir) = @_;
                   2112: 	$upload_photo_form = 1;
                   2113: 	return &userfileupload($formname,undef,$subdir);
                   2114: }
                   2115: 
1.608     albertel 2116: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2117: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 2118: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 2119: #        $coursedoc - if true up to the current course
                   2120: #                     if false
                   2121: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2122: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2123: #        $allfiles - reference to hash for embedded objects
                   2124: #        $codebase - reference to hash for codebase of java objects
                   2125: #        $desuname - username for permanent storage of uploaded file
                   2126: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2127: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2128: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  2129: # 
1.686     albertel 2130: # output: url of file in userspace, or error: <message> 
                   2131: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2132: 
                   2133: 
1.531     albertel 2134: sub userfileupload {
1.860     raeburn  2135:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   2136:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 2137:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2138:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2139:     $fname=&clean_filename($fname);
1.315     www      2140: # See if there is anything left
1.257     www      2141:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2142:     chop($env{'form.'.$formname});
1.523     raeburn  2143:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2144:         my $now = time;
                   2145:         my $filepath = 'tmp/helprequests/'.$now;
                   2146:         my @parts=split(/\//,$filepath);
                   2147:         my $fullpath = $perlvar{'lonDaemons'};
                   2148:         for (my $i=0;$i<@parts;$i++) {
                   2149:             $fullpath .= '/'.$parts[$i];
                   2150:             if ((-e $fullpath)!=1) {
                   2151:                 mkdir($fullpath,0777);
                   2152:             }
                   2153:         }
                   2154:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2155:         print $fh $env{'form.'.$formname};
1.523     raeburn  2156:         close($fh);
1.741     raeburn  2157:         return $fullpath.'/'.$fname;
                   2158:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2159:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2160:                        '_'.$env{'user.domain'}.'/pending';
                   2161:         my @parts=split(/\//,$filepath);
                   2162:         my $fullpath = $perlvar{'lonDaemons'};
                   2163:         for (my $i=0;$i<@parts;$i++) {
                   2164:             $fullpath .= '/'.$parts[$i];
                   2165:             if ((-e $fullpath)!=1) {
                   2166:                 mkdir($fullpath,0777);
                   2167:             }
                   2168:         }
                   2169:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2170:         print $fh $env{'form.'.$formname};
                   2171:         close($fh);
                   2172:         return $fullpath.'/'.$fname;
1.523     raeburn  2173:     }
1.995     raeburn  2174:     if ($subdir eq 'scantron') {
                   2175:         $fname = 'scantron_orig_'.$fname;
                   2176:     } else {   
1.258     www      2177: # Create the directory if not present
1.995     raeburn  2178:         $fname="$subdir/$fname";
                   2179:     }
1.259     www      2180:     if ($coursedoc) {
1.638     albertel 2181: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2182: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2183:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2184:             return &finishuserfileupload($docuname,$docudom,
                   2185: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  2186: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  2187:         } else {
1.620     albertel 2188:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2189:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2190: 				       $fname,$formname,$parser,
                   2191: 				       $allfiles,$codebase);
1.481     raeburn  2192:         }
1.719     banghart 2193:     } elsif (defined($destuname)) {
                   2194:         my $docuname=$destuname;
                   2195:         my $docudom=$destudom;
1.860     raeburn  2196: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2197: 				     $parser,$allfiles,$codebase,
                   2198:                                      $thumbwidth,$thumbheight);
1.719     banghart 2199:         
1.259     www      2200:     } else {
1.638     albertel 2201:         my $docuname=$env{'user.name'};
                   2202:         my $docudom=$env{'user.domain'};
1.714     raeburn  2203:         if (exists($env{'form.group'})) {
                   2204:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2205:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2206:         }
1.860     raeburn  2207: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2208: 				     $parser,$allfiles,$codebase,
                   2209:                                      $thumbwidth,$thumbheight);
1.259     www      2210:     }
1.271     www      2211: }
                   2212: 
                   2213: sub finishuserfileupload {
1.860     raeburn  2214:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   2215:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  2216:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2217:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2218:   
1.860     raeburn  2219:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2220:     $file=$fname;
                   2221:     if ($fname=~m|/|) {
                   2222:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2223: 	$path.=$fnamepath.'/';
                   2224:     }
1.259     www      2225:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2226:     my $count;
                   2227:     for ($count=4;$count<=$#parts;$count++) {
                   2228:         $filepath.="/$parts[$count]";
                   2229:         if ((-e $filepath)!=1) {
                   2230: 	    mkdir($filepath,0777);
                   2231:         }
                   2232:     }
1.984     neumanie 2233: 
1.258     www      2234: # Save the file
                   2235:     {
1.701     albertel 2236: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2237: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2238: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2239: 	    return '/adm/notfound.html';
                   2240: 	}
                   2241: 	if (!print FH ($env{'form.'.$formname})) {
                   2242: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2243: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2244: 	    return '/adm/notfound.html';
                   2245: 	}
1.570     albertel 2246: 	close(FH);
1.977     amueller 2247: 	if($upload_photo_form==1)
                   2248: 	{
1.984     neumanie 2249: 		resizeImage($filepath.'/'.$file);		
1.977     amueller 2250: 		$upload_photo_form = 0;
                   2251: 	}
1.258     www      2252:     }
1.637     raeburn  2253:     if ($parser eq 'parse') {
1.961     raeburn  2254:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
1.638     albertel 2255: 						   $codebase);
1.637     raeburn  2256:         unless ($parse_result eq 'ok') {
1.638     albertel 2257:             &logthis('Failed to parse '.$filepath.$file.
                   2258: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  2259:         }
                   2260:     }
1.860     raeburn  2261:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2262:         my $input = $filepath.'/'.$file;
                   2263:         my $output = $filepath.'/'.'tn-'.$file;
                   2264:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2265:         system("convert -sample $thumbsize $input $output");
                   2266:         if (-e $filepath.'/'.'tn-'.$file) {
                   2267:             $fetchthumb  = 1; 
                   2268:         }
                   2269:     }
1.858     raeburn  2270:  
1.259     www      2271: # Notify homeserver to grep it
                   2272: #
1.984     neumanie 2273:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2274:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2275:     if ($fetchresult eq 'ok') {
1.860     raeburn  2276:         if ($fetchthumb) {
                   2277:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2278:             if ($thumbresult ne 'ok') {
                   2279:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2280:                          $docuhome.': '.$thumbresult);
                   2281:             }
                   2282:         }
1.259     www      2283: #
1.258     www      2284: # Return the URL to it
1.494     albertel 2285:         return '/uploaded/'.$path.$file;
1.263     www      2286:     } else {
1.494     albertel 2287:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2288: 		 ': '.$fetchresult);
1.263     www      2289:         return '/adm/notfound.html';
1.858     raeburn  2290:     }
1.493     albertel 2291: }
                   2292: 
1.637     raeburn  2293: sub extract_embedded_items {
1.961     raeburn  2294:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2295:     my @state = ();
                   2296:     my %javafiles = (
                   2297:                       codebase => '',
                   2298:                       code => '',
                   2299:                       archive => ''
                   2300:                     );
                   2301:     my %mediafiles = (
                   2302:                       src => '',
                   2303:                       movie => '',
                   2304:                      );
1.648     raeburn  2305:     my $p;
                   2306:     if ($content) {
                   2307:         $p = HTML::LCParser->new($content);
                   2308:     } else {
1.961     raeburn  2309:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2310:     }
1.641     albertel 2311:     while (my $t=$p->get_token()) {
1.640     albertel 2312: 	if ($t->[0] eq 'S') {
                   2313: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2314: 	    push(@state, $tagname);
1.648     raeburn  2315:             if (lc($tagname) eq 'allow') {
                   2316:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2317:             }
1.640     albertel 2318: 	    if (lc($tagname) eq 'img') {
                   2319: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2320: 	    }
1.886     albertel 2321: 	    if (lc($tagname) eq 'a') {
                   2322: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2323: 	    }
1.645     raeburn  2324:             if (lc($tagname) eq 'script') {
                   2325:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2326:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2327:                 } else {
                   2328:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2329:                 }
                   2330:             }
                   2331:             if (lc($tagname) eq 'link') {
                   2332:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2333:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2334:                 }
                   2335:             }
1.640     albertel 2336: 	    if (lc($tagname) eq 'object' ||
                   2337: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2338: 		foreach my $item (keys(%javafiles)) {
                   2339: 		    $javafiles{$item} = '';
                   2340: 		}
                   2341: 	    }
                   2342: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2343: 		my $name = lc($attr->{'name'});
                   2344: 		foreach my $item (keys(%javafiles)) {
                   2345: 		    if ($name eq $item) {
                   2346: 			$javafiles{$item} = $attr->{'value'};
                   2347: 			last;
                   2348: 		    }
                   2349: 		}
                   2350: 		foreach my $item (keys(%mediafiles)) {
                   2351: 		    if ($name eq $item) {
                   2352: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2353: 			last;
                   2354: 		    }
                   2355: 		}
                   2356: 	    }
                   2357: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2358: 		foreach my $item (keys(%javafiles)) {
                   2359: 		    if ($attr->{$item}) {
                   2360: 			$javafiles{$item} = $attr->{$item};
                   2361: 			last;
                   2362: 		    }
                   2363: 		}
                   2364: 		foreach my $item (keys(%mediafiles)) {
                   2365: 		    if ($attr->{$item}) {
                   2366: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2367: 			last;
                   2368: 		    }
                   2369: 		}
                   2370: 	    }
                   2371: 	} elsif ($t->[0] eq 'E') {
                   2372: 	    my ($tagname) = ($t->[1]);
                   2373: 	    if ($javafiles{'codebase'} ne '') {
                   2374: 		$javafiles{'codebase'} .= '/';
                   2375: 	    }  
                   2376: 	    if (lc($tagname) eq 'applet' ||
                   2377: 		lc($tagname) eq 'object' ||
                   2378: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2379: 		) {
                   2380: 		foreach my $item (keys(%javafiles)) {
                   2381: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2382: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2383: 			&add_filetype($allfiles,$file,$item);
                   2384: 		    }
                   2385: 		}
                   2386: 	    } 
                   2387: 	    pop @state;
                   2388: 	}
                   2389:     }
1.637     raeburn  2390:     return 'ok';
                   2391: }
                   2392: 
1.639     albertel 2393: sub add_filetype {
                   2394:     my ($allfiles,$file,$type)=@_;
                   2395:     if (exists($allfiles->{$file})) {
                   2396: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2397: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2398: 	}
                   2399:     } else {
                   2400: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2401:     }
                   2402: }
                   2403: 
1.493     albertel 2404: sub removeuploadedurl {
1.984     neumanie 2405:     my ($url)=@_;	
                   2406:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2407:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2408: }
                   2409: 
                   2410: sub removeuserfile {
                   2411:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2412:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2413:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2414:     if ($result eq 'ok') {	
1.798     raeburn  2415:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2416:             my $metafile = $fname.'.meta';
                   2417:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2418: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2419:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2420:             my $sqlresult = 
1.823     albertel 2421:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2422:                                         'portfolio_metadata',$group,
                   2423:                                         'delete');
1.798     raeburn  2424:         }
                   2425:     }
                   2426:     return $result;
1.257     www      2427: }
1.15      www      2428: 
1.530     albertel 2429: sub mkdiruserfile {
                   2430:     my ($docuname,$docudom,$dir)=@_;
                   2431:     my $home=&homeserver($docuname,$docudom);
                   2432:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2433: }
                   2434: 
1.531     albertel 2435: sub renameuserfile {
                   2436:     my ($docuname,$docudom,$old,$new)=@_;
                   2437:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2438:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2439:                         &escape("$old").':'.&escape("$new"),$home);
                   2440:     if ($result eq 'ok') {
                   2441:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2442:             my $oldmeta = $old.'.meta';
                   2443:             my $newmeta = $new.'.meta';
                   2444:             my $metaresult = 
                   2445:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2446: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2447:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2448:             my $sqlresult = 
1.823     albertel 2449:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2450:                                         'portfolio_metadata',$group,
                   2451:                                         'delete');
1.798     raeburn  2452:         }
                   2453:     }
                   2454:     return $result;
1.531     albertel 2455: }
                   2456: 
1.14      www      2457: # ------------------------------------------------------------------------- Log
                   2458: 
                   2459: sub log {
                   2460:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2461:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2462: }
                   2463: 
                   2464: # ------------------------------------------------------------------ Course Log
1.352     www      2465: #
                   2466: # This routine flushes several buffers of non-mission-critical nature
                   2467: #
1.157     www      2468: 
                   2469: sub flushcourselogs {
1.352     www      2470:     &logthis('Flushing log buffers');
                   2471: #
                   2472: # course logs
                   2473: # This is a log of all transactions in a course, which can be used
                   2474: # for data mining purposes
                   2475: #
                   2476: # It also collects the courseid database, which lists last transaction
                   2477: # times and course titles for all courseids
                   2478: #
                   2479:     my %courseidbuffer=();
1.921     raeburn  2480:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2481:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2482: 		          &escape($courselogs{$crsid}),
                   2483: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2484: 	    delete $courselogs{$crsid};
                   2485:         } else {
                   2486:             &logthis('Failed to flush log buffer for '.$crsid);
                   2487:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2488:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2489:                         " exceeded maximum size, deleting.</font>");
                   2490:                delete $courselogs{$crsid};
                   2491:             }
1.352     www      2492:         }
1.920     raeburn  2493:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2494:             'description' => $coursedescrbuf{$crsid},
                   2495:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2496:             'type'        => $coursetypebuf{$crsid},
                   2497:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2498:         };
1.191     harris41 2499:     }
1.352     www      2500: #
                   2501: # Write course id database (reverse lookup) to homeserver of courses 
                   2502: # Is used in pickcourse
                   2503: #
1.840     albertel 2504:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2505:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2506:                                     $courseidbuffer{$crs_home},
                   2507:                                     $crs_home,'timeonly');
1.352     www      2508:     }
                   2509: #
                   2510: # File accesses
                   2511: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2512: #
1.449     matthew  2513:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2514:         if ($entry =~ /___count$/) {
                   2515:             my ($dom,$name);
1.807     albertel 2516:             ($dom,$name,undef)=
1.811     albertel 2517: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2518:             if (! defined($dom) || $dom eq '' || 
                   2519:                 ! defined($name) || $name eq '') {
1.620     albertel 2520:                 my $cid = $env{'request.course.id'};
                   2521:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2522:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2523:             }
1.450     matthew  2524:             my $value = $accesshash{$entry};
                   2525:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2526:             my %temphash=($url => $value);
1.449     matthew  2527:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2528:             if ($result eq 'ok') {
                   2529:                 delete $accesshash{$entry};
                   2530:             } elsif ($result eq 'unknown_cmd') {
                   2531:                 # Target server has old code running on it.
1.450     matthew  2532:                 my %temphash=($entry => $value);
1.449     matthew  2533:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2534:                     delete $accesshash{$entry};
                   2535:                 }
                   2536:             }
                   2537:         } else {
1.811     albertel 2538:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2539:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2540:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2541:                 delete $accesshash{$entry};
                   2542:             }
1.185     www      2543:         }
1.191     harris41 2544:     }
1.352     www      2545: #
                   2546: # Roles
                   2547: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2548: #
1.800     albertel 2549:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2550:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2551: 	    split(/\:/,$entry);
                   2552:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2553:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2554:                 $rudom,$runame) eq 'ok') {
                   2555: 	    delete $userrolehash{$entry};
                   2556:         }
                   2557:     }
1.662     raeburn  2558: #
                   2559: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2560: #
                   2561:     my %domrolebuffer = ();
1.1000    raeburn  2562:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 2563:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2564:         if ($domrolebuffer{$rudom}) {
                   2565:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2566:                       '='.&escape($domainrolehash{$entry});
                   2567:         } else {
                   2568:             $domrolebuffer{$rudom}.=&escape($entry).
                   2569:                       '='.&escape($domainrolehash{$entry});
                   2570:         }
                   2571:         delete $domainrolehash{$entry};
                   2572:     }
                   2573:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2574: 	my %servers = &get_servers($dom,'library');
                   2575: 	foreach my $tryserver (keys(%servers)) {
                   2576: 	    unless (&reply('domroleput:'.$dom.':'.
                   2577: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2578: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2579: 	    }
1.662     raeburn  2580:         }
                   2581:     }
1.186     www      2582:     $dumpcount++;
1.157     www      2583: }
                   2584: 
                   2585: sub courselog {
                   2586:     my $what=shift;
1.158     www      2587:     $what=time.':'.$what;
1.620     albertel 2588:     unless ($env{'request.course.id'}) { return ''; }
                   2589:     $coursedombuf{$env{'request.course.id'}}=
                   2590:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2591:     $coursenumbuf{$env{'request.course.id'}}=
                   2592:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2593:     $coursehombuf{$env{'request.course.id'}}=
                   2594:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2595:     $coursedescrbuf{$env{'request.course.id'}}=
                   2596:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2597:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2598:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2599:     $courseownerbuf{$env{'request.course.id'}}=
                   2600:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2601:     $coursetypebuf{$env{'request.course.id'}}=
                   2602:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2603:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2604: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2605:     } else {
1.620     albertel 2606: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2607:     }
1.620     albertel 2608:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2609: 	&flushcourselogs();
                   2610:     }
1.158     www      2611: }
                   2612: 
                   2613: sub courseacclog {
                   2614:     my $fnsymb=shift;
1.620     albertel 2615:     unless ($env{'request.course.id'}) { return ''; }
                   2616:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2617:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2618:         $what.=':POST';
1.583     matthew  2619:         # FIXME: Probably ought to escape things....
1.800     albertel 2620: 	foreach my $key (keys(%env)) {
                   2621:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2622:                 my $formitem = $1;
                   2623:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2624:                     $what.=':'.$formitem.'='.$env{$key};
                   2625:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2626:                     $what.=':'.$formitem.'='.$env{$key};
                   2627:                 }
1.158     www      2628:             }
1.191     harris41 2629:         }
1.583     matthew  2630:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2631:         # FIXME: We should not be depending on a form parameter that someone
                   2632:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2633:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2634:             $what.= ':POST';
                   2635:             # FIXME: Probably ought to escape things....
                   2636:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2637:                                  'crsdiscuss') {
1.620     albertel 2638:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2639:             }
                   2640:         }
1.158     www      2641:     }
                   2642:     &courselog($what);
1.149     www      2643: }
                   2644: 
1.185     www      2645: sub countacc {
                   2646:     my $url=&declutter(shift);
1.458     matthew  2647:     return if (! defined($url) || $url eq '');
1.620     albertel 2648:     unless ($env{'request.course.id'}) { return ''; }
                   2649:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2650:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2651:     $accesshash{$key}++;
1.185     www      2652: }
1.349     www      2653: 
1.361     www      2654: sub linklog {
                   2655:     my ($from,$to)=@_;
                   2656:     $from=&declutter($from);
                   2657:     $to=&declutter($to);
                   2658:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2659:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2660: }
                   2661:   
1.349     www      2662: sub userrolelog {
                   2663:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2664:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2665:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2666:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2667:         ($trole=~/^ta/)) {
1.350     www      2668:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2669:        $userrolehash
                   2670:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2671:                     =$tend.':'.$tstart;
1.662     raeburn  2672:     }
1.898     albertel 2673:     if (($env{'request.role'} =~ /dc\./) &&
                   2674: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2675: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2676: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2677:        $userrolehash
                   2678:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2679:                     =$tend.':'.$tstart;
                   2680:     }
1.662     raeburn  2681:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2682:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2683:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2684:         ($trole=~/^sc/)) {
                   2685:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2686:        $domainrolehash
                   2687:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2688:                     = $tend.':'.$tstart;
                   2689:     }
1.351     www      2690: }
                   2691: 
1.957     raeburn  2692: sub courserolelog {
                   2693:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2694:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2695:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2696:         ($trole eq 'ta') || ($trole eq 'st') ||
                   2697:         ($trole=~/^cr/) || ($trole eq 'gr')) {
                   2698:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2699:             my $cdom = $1;
                   2700:             my $cnum = $2;
                   2701:             my $sec = $3;
                   2702:             my $namespace = 'rolelog';
                   2703:             my %storehash = (
                   2704:                                role    => $trole,
                   2705:                                start   => $tstart,
                   2706:                                end     => $tend,
                   2707:                                selfenroll => $selfenroll,
                   2708:                                context    => $context,
                   2709:                             );
                   2710:             if ($trole eq 'gr') {
                   2711:                 $namespace = 'groupslog';
                   2712:                 $storehash{'group'} = $sec;
                   2713:             } else {
                   2714:                 $storehash{'section'} = $sec;
                   2715:             }
                   2716:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  2717:             if (($trole ne 'st') || ($sec ne '')) {
                   2718:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   2719:             }
1.957     raeburn  2720:         }
                   2721:     }
                   2722:     return;
                   2723: }
                   2724: 
1.351     www      2725: sub get_course_adv_roles {
1.948     raeburn  2726:     my ($cid,$codes) = @_;
1.620     albertel 2727:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2728:     my %coursehash=&coursedescription($cid);
1.988     raeburn  2729:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      2730:     my %nothide=();
1.800     albertel 2731:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2732:         if ($user !~ /:/) {
                   2733: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2734:         } else {
                   2735:             $nothide{$user}=1;
                   2736:         }
1.470     www      2737:     }
1.351     www      2738:     my %returnhash=();
                   2739:     my %dumphash=
                   2740:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2741:     my $now=time;
1.997     raeburn  2742:     my %privileged;
1.1000    raeburn  2743:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 2744: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2745:         if (($tstart) && ($tstart<0)) { next; }
                   2746:         if (($tend) && ($tend<$now)) { next; }
                   2747:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2748:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2749: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  2750:         unless (ref($privileged{$domain}) eq 'HASH') {
                   2751:             my %dompersonnel =
1.998     raeburn  2752:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  2753:             $privileged{$domain} = {};
                   2754:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  2755:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  2756:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   2757:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   2758:                         $privileged{$udom}{$uname} = 1;
                   2759:                     }
                   2760:                 }
                   2761:             }
                   2762:         }
                   2763:         if ((exists($privileged{$domain}{$username})) && 
                   2764:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2765: 	if ($role eq 'cr') { next; }
1.948     raeburn  2766:         if ($codes) {
                   2767:             if ($section) { $role .= ':'.$section; }
                   2768:             if ($returnhash{$role}) {
                   2769:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2770:             } else {
                   2771:                 $returnhash{$role}=$username.':'.$domain;
                   2772:             }
1.351     www      2773:         } else {
1.988     raeburn  2774:             my $key=&plaintext($role,$crstype);
1.973     bisitz   2775:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  2776:             if ($returnhash{$key}) {
                   2777: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2778:             } else {
                   2779:                 $returnhash{$key}=$username.':'.$domain;
                   2780:             }
1.351     www      2781:         }
1.948     raeburn  2782:     }
1.400     www      2783:     return %returnhash;
                   2784: }
                   2785: 
                   2786: sub get_my_roles {
1.937     raeburn  2787:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2788:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2789:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2790:     my (%dumphash,%nothide);
1.858     raeburn  2791:     if ($context eq 'userroles') { 
                   2792:         %dumphash = &dump('roles',$udom,$uname);
                   2793:     } else {
                   2794:         %dumphash=
1.400     www      2795:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2796:         if ($hidepriv) {
                   2797:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2798:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2799:                 if ($user !~ /:/) {
                   2800:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2801:                 } else {
                   2802:                     $nothide{$user} = 1;
                   2803:                 }
                   2804:             }
                   2805:         }
1.858     raeburn  2806:     }
1.400     www      2807:     my %returnhash=();
                   2808:     my $now=time;
1.999     raeburn  2809:     my %privileged;
1.800     albertel 2810:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2811:         my ($role,$tend,$tstart);
                   2812:         if ($context eq 'userroles') {
                   2813: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2814:         } else {
                   2815:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2816:         }
1.400     www      2817:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2818:         my $status = 'active';
1.939     raeburn  2819:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2820:             $status = 'previous';
                   2821:         } 
                   2822:         if (($tstart) && ($now<$tstart)) {
                   2823:             $status = 'future';
                   2824:         }
                   2825:         if (ref($types) eq 'ARRAY') {
                   2826:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2827:                 next;
                   2828:             } 
                   2829:         } else {
                   2830:             if ($status ne 'active') {
                   2831:                 next;
                   2832:             }
                   2833:         }
1.867     raeburn  2834:         my ($rolecode,$username,$domain,$section,$area);
                   2835:         if ($context eq 'userroles') {
                   2836:             ($area,$rolecode) = split(/_/,$entry);
                   2837:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2838:         } else {
                   2839:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2840:         }
1.832     raeburn  2841:         if (ref($roledoms) eq 'ARRAY') {
                   2842:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2843:                 next;
                   2844:             }
                   2845:         }
                   2846:         if (ref($roles) eq 'ARRAY') {
                   2847:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2848:                 if ($role =~ /^cr\//) {
                   2849:                     if (!grep(/^cr$/,@{$roles})) {
                   2850:                         next;
                   2851:                     }
                   2852:                 } else {
                   2853:                     next;
                   2854:                 }
1.832     raeburn  2855:             }
1.867     raeburn  2856:         }
1.937     raeburn  2857:         if ($hidepriv) {
1.999     raeburn  2858:             if ($context eq 'userroles') {
                   2859:                 if ((&privileged($username,$domain)) &&
                   2860:                     (!$nothide{$username.':'.$domain})) {
                   2861:                     next;
                   2862:                 }
                   2863:             } else {
                   2864:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   2865:                     my %dompersonnel =
                   2866:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   2867:                     $privileged{$domain} = {};
                   2868:                     if (keys(%dompersonnel)) {
                   2869:                         foreach my $server (keys(%dompersonnel)) {
                   2870:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   2871:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   2872:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   2873:                                     $privileged{$udom}{$uname} = $trole;
                   2874:                                 }
                   2875:                             }
                   2876:                         }
                   2877:                     }
                   2878:                 }
                   2879:                 if (exists($privileged{$domain}{$username})) {
                   2880:                     if (!$nothide{$username.':'.$domain}) {
                   2881:                         next;
                   2882:                     }
                   2883:                 }
1.937     raeburn  2884:             }
                   2885:         }
1.933     raeburn  2886:         if ($withsec) {
                   2887:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2888:                 $tstart.':'.$tend;
                   2889:         } else {
                   2890:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2891:         }
1.832     raeburn  2892:     }
1.373     www      2893:     return %returnhash;
1.399     www      2894: }
                   2895: 
                   2896: # ----------------------------------------------------- Frontpage Announcements
                   2897: #
                   2898: #
                   2899: 
                   2900: sub postannounce {
                   2901:     my ($server,$text)=@_;
1.844     albertel 2902:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2903:     unless ($text=~/\w/) { $text=''; }
                   2904:     return &reply('setannounce:'.&escape($text),$server);
                   2905: }
                   2906: 
                   2907: sub getannounce {
1.448     albertel 2908: 
                   2909:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2910: 	my $announcement='';
1.800     albertel 2911: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2912: 	close($fh);
1.399     www      2913: 	if ($announcement=~/\w/) { 
                   2914: 	    return 
                   2915:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2916:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2917: 	} else {
                   2918: 	    return '';
                   2919: 	}
                   2920:     } else {
                   2921: 	return '';
                   2922:     }
1.351     www      2923: }
1.353     www      2924: 
                   2925: # ---------------------------------------------------------- Course ID routines
                   2926: # Deal with domain's nohist_courseid.db files
                   2927: #
                   2928: 
                   2929: sub courseidput {
1.921     raeburn  2930:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2931:     my $outcome;
                   2932:     if ($caller eq 'timeonly') {
                   2933:         my $cids = '';
                   2934:         foreach my $item (keys(%$storehash)) {
                   2935:             $cids.=&escape($item).'&';
                   2936:         }
                   2937:         $cids=~s/\&$//;
                   2938:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2939:                           $coursehome);       
                   2940:     } else {
                   2941:         my $items = '';
                   2942:         foreach my $item (keys(%$storehash)) {
                   2943:             $items.= &escape($item).'='.
                   2944:                      &freeze_escape($$storehash{$item}).'&';
                   2945:         }
                   2946:         $items=~s/\&$//;
                   2947:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2948:                           $coursehome);
1.918     raeburn  2949:     }
                   2950:     if ($outcome eq 'unknown_cmd') {
                   2951:         my $what;
                   2952:         foreach my $cid (keys(%$storehash)) {
                   2953:             $what .= &escape($cid).'=';
1.921     raeburn  2954:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2955:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2956:             }
                   2957:             $what =~ s/\:$/&/;
                   2958:         }
                   2959:         $what =~ s/\&$//;  
                   2960:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2961:     } else {
                   2962:         return $outcome;
                   2963:     }
1.353     www      2964: }
                   2965: 
                   2966: sub courseiddump {
1.921     raeburn  2967:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  2968:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.962     raeburn  2969:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
1.918     raeburn  2970:     my $as_hash = 1;
                   2971:     my %returnhash;
                   2972:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2973:     my %libserv = &all_library();
                   2974:     foreach my $tryserver (keys(%libserv)) {
                   2975:         if ( (  $hostidflag == 1 
                   2976: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2977: 	     || (!defined($hostidflag)) ) {
                   2978: 
1.918     raeburn  2979: 	    if (($domfilter eq '') ||
                   2980: 		(&host_domain($tryserver) eq $domfilter)) {
                   2981:                 my $rep = 
                   2982:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2983:                          $sincefilter.':'.&escape($descfilter).':'.
                   2984:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2985:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  2986:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  2987:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   2988:                          $showhidden.':'.$caller,$tryserver);
1.918     raeburn  2989:                 my @pairs=split(/\&/,$rep);
                   2990:                 foreach my $item (@pairs) {
                   2991:                     my ($key,$value)=split(/\=/,$item,2);
                   2992:                     $key = &unescape($key);
                   2993:                     next if ($key =~ /^error: 2 /);
                   2994:                     my $result = &thaw_unescape($value);
                   2995:                     if (ref($result) eq 'HASH') {
                   2996:                         $returnhash{$key}=$result;
                   2997:                     } else {
1.921     raeburn  2998:                         my @responses = split(/:/,$value);
                   2999:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3000:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3001:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3002:                         }
                   3003:                     } 
1.353     www      3004:                 }
                   3005:             }
                   3006:         }
                   3007:     }
                   3008:     return %returnhash;
                   3009: }
                   3010: 
1.658     raeburn  3011: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3012: 
                   3013: sub dcmailput {
1.685     raeburn  3014:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3015:     my $status = &Apache::lonnet::critical(
1.740     www      3016:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3017:        &escape($message),$server);
1.662     raeburn  3018:     return $status;
                   3019: }
                   3020: 
1.658     raeburn  3021: sub dcmaildump {
                   3022:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3023:     my %returnhash=();
1.846     albertel 3024: 
                   3025:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3026:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3027:                                                          &escape($enddate).':';
                   3028: 	my @esc_senders=map { &escape($_)} @$senders;
                   3029: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3030: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3031:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3032:             if (($key) && ($value)) {
                   3033:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3034:             }
                   3035:         }
                   3036:     }
                   3037:     return %returnhash;
                   3038: }
1.662     raeburn  3039: # ---------------------------------------------------------- Domain roles
                   3040: 
                   3041: sub get_domain_roles {
                   3042:     my ($dom,$roles,$startdate,$enddate)=@_;
                   3043:     if (undef($startdate) || $startdate eq '') {
                   3044:         $startdate = '.';
                   3045:     }
                   3046:     if (undef($enddate) || $enddate eq '') {
                   3047:         $enddate = '.';
                   3048:     }
1.922     raeburn  3049:     my $rolelist;
                   3050:     if (ref($roles) eq 'ARRAY') {
                   3051:         $rolelist = join(':',@{$roles});
                   3052:     }
1.662     raeburn  3053:     my %personnel = ();
1.841     albertel 3054: 
                   3055:     my %servers = &get_servers($dom,'library');
                   3056:     foreach my $tryserver (keys(%servers)) {
                   3057: 	%{$personnel{$tryserver}}=();
                   3058: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3059: 					    &escape($startdate).':'.
                   3060: 					    &escape($enddate).':'.
                   3061: 					    &escape($rolelist), $tryserver))) {
                   3062: 	    my ($key,$value) = split(/\=/,$line,2);
                   3063: 	    if (($key) && ($value)) {
                   3064: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3065: 	    }
                   3066: 	}
1.662     raeburn  3067:     }
                   3068:     return %personnel;
                   3069: }
1.658     raeburn  3070: 
1.149     www      3071: # ----------------------------------------------------------- Check out an item
                   3072: 
1.504     albertel 3073: sub get_first_access {
                   3074:     my ($type,$argsymb)=@_;
1.790     albertel 3075:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3076:     if ($argsymb) { $symb=$argsymb; }
                   3077:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3078:     if ($type eq 'course') {
                   3079: 	$res='course';
                   3080:     } elsif ($type eq 'map') {
1.588     albertel 3081: 	$res=&symbread($map);
                   3082:     } else {
                   3083: 	$res=$symb;
                   3084:     }
                   3085:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3086:     return $times{"$courseid\0$res"};
1.504     albertel 3087: }
                   3088: 
                   3089: sub set_first_access {
                   3090:     my ($type)=@_;
1.790     albertel 3091:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3092:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3093:     if ($type eq 'course') {
                   3094: 	$res='course';
                   3095:     } elsif ($type eq 'map') {
1.588     albertel 3096: 	$res=&symbread($map);
                   3097:     } else {
                   3098: 	$res=$symb;
                   3099:     }
                   3100:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3101:     if (!$firstaccess) {
1.588     albertel 3102: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3103:     }
                   3104:     return 'already_set';
1.504     albertel 3105: }
                   3106: 
1.149     www      3107: sub checkout {
                   3108:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   3109:     my $now=time;
                   3110:     my $lonhost=$perlvar{'lonHostID'};
                   3111:     my $infostr=&escape(
1.234     www      3112:                  'CHECKOUTTOKEN&'.
1.149     www      3113:                  $tuname.'&'.
                   3114:                  $tudom.'&'.
                   3115:                  $tcrsid.'&'.
                   3116:                  $symb.'&'.
                   3117: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   3118:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      3119:     if ($token=~/^error\:/) { 
1.672     albertel 3120:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3121:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3122:                  "</font>");
                   3123:         return ''; 
                   3124:     }
                   3125: 
1.149     www      3126:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   3127:     $token=~tr/a-z/A-Z/;
                   3128: 
1.153     www      3129:     my %infohash=('resource.0.outtoken' => $token,
                   3130:                   'resource.0.checkouttime' => $now,
                   3131:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      3132: 
                   3133:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3134:        return '';
1.151     www      3135:     } else {
1.672     albertel 3136:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3137:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3138:                  "</font>");
1.149     www      3139:     }    
                   3140: 
                   3141:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3142:                          &escape('Checkout '.$infostr.' - '.
                   3143:                                                  $token)) ne 'ok') {
                   3144: 	return '';
1.151     www      3145:     } else {
1.672     albertel 3146:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3147:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3148:                  "</font>");
1.149     www      3149:     }
1.151     www      3150:     return $token;
1.149     www      3151: }
                   3152: 
                   3153: # ------------------------------------------------------------ Check in an item
                   3154: 
                   3155: sub checkin {
                   3156:     my $token=shift;
1.150     www      3157:     my $now=time;
                   3158:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3159:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3160:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3161:     $dtoken=~s/\W/\_/g;
1.234     www      3162:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3163:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3164: 
1.154     www      3165:     unless (($tuname) && ($tudom)) {
                   3166:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3167:         return '';
                   3168:     }
                   3169:     
                   3170:     unless (&allowed('mgr',$tcrsid)) {
                   3171:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3172:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3173:         return '';
                   3174:     }
                   3175: 
1.153     www      3176:     my %infohash=('resource.0.intoken' => $token,
                   3177:                   'resource.0.checkintime' => $now,
                   3178:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3179: 
                   3180:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3181:        return '';
                   3182:     }    
                   3183: 
                   3184:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3185:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3186: 	return '';
                   3187:     }
                   3188: 
                   3189:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3190: }
                   3191: 
                   3192: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3193: 
                   3194: sub expirespread {
                   3195:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3196:     my $cid=$env{'request.course.id'}; 
1.110     www      3197:     if ($cid) {
                   3198:        my $now=time;
                   3199:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3200:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3201:                             $env{'course.'.$cid.'.num'}.
1.110     www      3202: 	        	    ':nohist_expirationdates:'.
                   3203:                             &escape($key).'='.$now,
1.620     albertel 3204:                             $env{'course.'.$cid.'.home'})
1.110     www      3205:     }
                   3206:     return 'ok';
1.14      www      3207: }
                   3208: 
1.109     www      3209: # ----------------------------------------------------- Devalidate Spreadsheets
                   3210: 
                   3211: sub devalidate {
1.325     www      3212:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3213:     my $cid=$env{'request.course.id'}; 
1.109     www      3214:     if ($cid) {
1.391     matthew  3215:         # delete the stored spreadsheets for
                   3216:         # - the student level sheet of this user in course's homespace
                   3217:         # - the assessment level sheet for this resource 
                   3218:         #   for this user in user's homespace
1.553     albertel 3219: 	# - current conditional state info
1.325     www      3220: 	my $key=$uname.':'.$udom.':';
1.109     www      3221:         my $status=
1.299     matthew  3222: 	    &del('nohist_calculatedsheets',
1.391     matthew  3223: 		 [$key.'studentcalc:'],
1.620     albertel 3224: 		 $env{'course.'.$cid.'.domain'},
                   3225: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3226: 		.' '.
                   3227: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3228: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3229:         unless ($status eq 'ok ok') {
                   3230:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3231:                     $uname.' at '.$udom.' for '.
1.109     www      3232: 		    $symb.': '.$status);
1.133     albertel 3233:         }
1.553     albertel 3234: 	&delenv('user.state.'.$cid);
1.109     www      3235:     }
                   3236: }
                   3237: 
1.265     albertel 3238: sub get_scalar {
                   3239:     my ($string,$end) = @_;
                   3240:     my $value;
                   3241:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3242: 	$value = $1;
                   3243:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3244: 	$value = $1;
                   3245:     }
                   3246:     return &unescape($value);
                   3247: }
                   3248: 
                   3249: sub array2str {
                   3250:   my (@array) = @_;
                   3251:   my $result=&arrayref2str(\@array);
                   3252:   $result=~s/^__ARRAY_REF__//;
                   3253:   $result=~s/__END_ARRAY_REF__$//;
                   3254:   return $result;
                   3255: }
                   3256: 
1.204     albertel 3257: sub arrayref2str {
                   3258:   my ($arrayref) = @_;
1.265     albertel 3259:   my $result='__ARRAY_REF__';
1.204     albertel 3260:   foreach my $elem (@$arrayref) {
1.265     albertel 3261:     if(ref($elem) eq 'ARRAY') {
                   3262:       $result.=&arrayref2str($elem).'&';
                   3263:     } elsif(ref($elem) eq 'HASH') {
                   3264:       $result.=&hashref2str($elem).'&';
                   3265:     } elsif(ref($elem)) {
                   3266:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3267:     } else {
                   3268:       $result.=&escape($elem).'&';
                   3269:     }
                   3270:   }
                   3271:   $result=~s/\&$//;
1.265     albertel 3272:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3273:   return $result;
                   3274: }
                   3275: 
1.168     albertel 3276: sub hash2str {
1.204     albertel 3277:   my (%hash) = @_;
                   3278:   my $result=&hashref2str(\%hash);
1.265     albertel 3279:   $result=~s/^__HASH_REF__//;
                   3280:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3281:   return $result;
                   3282: }
                   3283: 
                   3284: sub hashref2str {
                   3285:   my ($hashref)=@_;
1.265     albertel 3286:   my $result='__HASH_REF__';
1.800     albertel 3287:   foreach my $key (sort(keys(%$hashref))) {
                   3288:     if (ref($key) eq 'ARRAY') {
                   3289:       $result.=&arrayref2str($key).'=';
                   3290:     } elsif (ref($key) eq 'HASH') {
                   3291:       $result.=&hashref2str($key).'=';
                   3292:     } elsif (ref($key)) {
1.265     albertel 3293:       $result.='=';
1.800     albertel 3294:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3295:     } else {
1.800     albertel 3296: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3297:     }
                   3298: 
1.800     albertel 3299:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3300:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3301:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3302:       $result.=&hashref2str($hashref->{$key}).'&';
                   3303:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3304:        $result.='&';
1.800     albertel 3305:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3306:     } else {
1.800     albertel 3307:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3308:     }
                   3309:   }
1.168     albertel 3310:   $result=~s/\&$//;
1.265     albertel 3311:   $result .= '__END_HASH_REF__';
1.168     albertel 3312:   return $result;
                   3313: }
                   3314: 
                   3315: sub str2hash {
1.265     albertel 3316:     my ($string)=@_;
                   3317:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3318:     return %$hash;
                   3319: }
                   3320: 
                   3321: sub str2hashref {
1.168     albertel 3322:   my ($string) = @_;
1.265     albertel 3323: 
                   3324:   my %hash;
                   3325: 
                   3326:   if($string !~ /^__HASH_REF__/) {
                   3327:       if (! ($string eq '' || !defined($string))) {
                   3328: 	  $hash{'error'}='Not hash reference';
                   3329:       }
                   3330:       return (\%hash, $string);
                   3331:   }
                   3332: 
                   3333:   $string =~ s/^__HASH_REF__//;
                   3334: 
                   3335:   while($string !~ /^__END_HASH_REF__/) {
                   3336:       #key
                   3337:       my $key='';
                   3338:       if($string =~ /^__HASH_REF__/) {
                   3339:           ($key, $string)=&str2hashref($string);
                   3340:           if(defined($key->{'error'})) {
                   3341:               $hash{'error'}='Bad data';
                   3342:               return (\%hash, $string);
                   3343:           }
                   3344:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3345:           ($key, $string)=&str2arrayref($string);
                   3346:           if($key->[0] eq 'Array reference error') {
                   3347:               $hash{'error'}='Bad data';
                   3348:               return (\%hash, $string);
                   3349:           }
                   3350:       } else {
                   3351:           $string =~ s/^(.*?)=//;
1.267     albertel 3352: 	  $key=&unescape($1);
1.265     albertel 3353:       }
                   3354:       $string =~ s/^=//;
                   3355: 
                   3356:       #value
                   3357:       my $value='';
                   3358:       if($string =~ /^__HASH_REF__/) {
                   3359:           ($value, $string)=&str2hashref($string);
                   3360:           if(defined($value->{'error'})) {
                   3361:               $hash{'error'}='Bad data';
                   3362:               return (\%hash, $string);
                   3363:           }
                   3364:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3365:           ($value, $string)=&str2arrayref($string);
                   3366:           if($value->[0] eq 'Array reference error') {
                   3367:               $hash{'error'}='Bad data';
                   3368:               return (\%hash, $string);
                   3369:           }
                   3370:       } else {
                   3371: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3372:       }
                   3373:       $string =~ s/^&//;
                   3374: 
                   3375:       $hash{$key}=$value;
1.204     albertel 3376:   }
1.265     albertel 3377: 
                   3378:   $string =~ s/^__END_HASH_REF__//;
                   3379: 
                   3380:   return (\%hash, $string);
1.204     albertel 3381: }
                   3382: 
                   3383: sub str2array {
1.265     albertel 3384:     my ($string)=@_;
                   3385:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3386:     return @$array;
                   3387: }
                   3388: 
                   3389: sub str2arrayref {
1.204     albertel 3390:   my ($string) = @_;
1.265     albertel 3391:   my @array;
                   3392: 
                   3393:   if($string !~ /^__ARRAY_REF__/) {
                   3394:       if (! ($string eq '' || !defined($string))) {
                   3395: 	  $array[0]='Array reference error';
                   3396:       }
                   3397:       return (\@array, $string);
                   3398:   }
                   3399: 
                   3400:   $string =~ s/^__ARRAY_REF__//;
                   3401: 
                   3402:   while($string !~ /^__END_ARRAY_REF__/) {
                   3403:       my $value='';
                   3404:       if($string =~ /^__HASH_REF__/) {
                   3405:           ($value, $string)=&str2hashref($string);
                   3406:           if(defined($value->{'error'})) {
                   3407:               $array[0] ='Array reference error';
                   3408:               return (\@array, $string);
                   3409:           }
                   3410:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3411:           ($value, $string)=&str2arrayref($string);
                   3412:           if($value->[0] eq 'Array reference error') {
                   3413:               $array[0] ='Array reference error';
                   3414:               return (\@array, $string);
                   3415:           }
                   3416:       } else {
                   3417: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3418:       }
                   3419:       $string =~ s/^&//;
                   3420: 
                   3421:       push(@array, $value);
1.191     harris41 3422:   }
1.265     albertel 3423: 
                   3424:   $string =~ s/^__END_ARRAY_REF__//;
                   3425: 
                   3426:   return (\@array, $string);
1.168     albertel 3427: }
                   3428: 
1.167     albertel 3429: # -------------------------------------------------------------------Temp Store
                   3430: 
1.168     albertel 3431: sub tmpreset {
                   3432:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3433:   if (!$symb) {
                   3434:     $symb=&symbread();
1.620     albertel 3435:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3436:   }
                   3437:   $symb=escape($symb);
                   3438: 
1.620     albertel 3439:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3440:   $namespace=~s/\//\_/g;
                   3441:   $namespace=~s/\W//g;
                   3442: 
1.620     albertel 3443:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3444:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3445:   if ($domain eq 'public' && $stuname eq 'public') {
                   3446:       $stuname=$ENV{'REMOTE_ADDR'};
                   3447:   }
1.168     albertel 3448:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3449:   my %hash;
                   3450:   if (tie(%hash,'GDBM_File',
                   3451: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3452: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3453:     foreach my $key (keys(%hash)) {
1.180     albertel 3454:       if ($key=~ /:$symb/) {
1.168     albertel 3455: 	delete($hash{$key});
                   3456:       }
                   3457:     }
                   3458:   }
                   3459: }
                   3460: 
1.167     albertel 3461: sub tmpstore {
1.168     albertel 3462:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3463: 
                   3464:   if (!$symb) {
                   3465:     $symb=&symbread();
1.620     albertel 3466:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3467:   }
                   3468:   $symb=escape($symb);
                   3469: 
                   3470:   if (!$namespace) {
                   3471:     # I don't think we would ever want to store this for a course.
                   3472:     # it seems this will only be used if we don't have a course.
1.620     albertel 3473:     #$namespace=$env{'request.course.id'};
1.168     albertel 3474:     #if (!$namespace) {
1.620     albertel 3475:       $namespace=$env{'request.state'};
1.168     albertel 3476:     #}
                   3477:   }
                   3478:   $namespace=~s/\//\_/g;
                   3479:   $namespace=~s/\W//g;
1.620     albertel 3480:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3481:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3482:   if ($domain eq 'public' && $stuname eq 'public') {
                   3483:       $stuname=$ENV{'REMOTE_ADDR'};
                   3484:   }
1.168     albertel 3485:   my $now=time;
                   3486:   my %hash;
                   3487:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3488:   if (tie(%hash,'GDBM_File',
                   3489: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3490: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3491:     $hash{"version:$symb"}++;
                   3492:     my $version=$hash{"version:$symb"};
                   3493:     my $allkeys=''; 
                   3494:     foreach my $key (keys(%$storehash)) {
                   3495:       $allkeys.=$key.':';
1.591     albertel 3496:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3497:     }
                   3498:     $hash{"$version:$symb:timestamp"}=$now;
                   3499:     $allkeys.='timestamp';
                   3500:     $hash{"$version:keys:$symb"}=$allkeys;
                   3501:     if (untie(%hash)) {
                   3502:       return 'ok';
                   3503:     } else {
                   3504:       return "error:$!";
                   3505:     }
                   3506:   } else {
                   3507:     return "error:$!";
                   3508:   }
                   3509: }
1.167     albertel 3510: 
1.168     albertel 3511: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3512: 
1.168     albertel 3513: sub tmprestore {
                   3514:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3515: 
1.168     albertel 3516:   if (!$symb) {
                   3517:     $symb=&symbread();
1.620     albertel 3518:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3519:   }
                   3520:   $symb=escape($symb);
                   3521: 
1.620     albertel 3522:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3523: 
1.620     albertel 3524:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3525:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3526:   if ($domain eq 'public' && $stuname eq 'public') {
                   3527:       $stuname=$ENV{'REMOTE_ADDR'};
                   3528:   }
1.168     albertel 3529:   my %returnhash;
                   3530:   $namespace=~s/\//\_/g;
                   3531:   $namespace=~s/\W//g;
                   3532:   my %hash;
                   3533:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3534:   if (tie(%hash,'GDBM_File',
                   3535: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3536: 	  &GDBM_READER(),0640)) {
1.168     albertel 3537:     my $version=$hash{"version:$symb"};
                   3538:     $returnhash{'version'}=$version;
                   3539:     my $scope;
                   3540:     for ($scope=1;$scope<=$version;$scope++) {
                   3541:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3542:       my @keys=split(/:/,$vkeys);
                   3543:       my $key;
                   3544:       $returnhash{"$scope:keys"}=$vkeys;
                   3545:       foreach $key (@keys) {
1.591     albertel 3546: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3547: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3548:       }
                   3549:     }
1.168     albertel 3550:     if (!(untie(%hash))) {
                   3551:       return "error:$!";
                   3552:     }
                   3553:   } else {
                   3554:     return "error:$!";
                   3555:   }
                   3556:   return %returnhash;
1.167     albertel 3557: }
                   3558: 
1.9       www      3559: # ----------------------------------------------------------------------- Store
                   3560: 
                   3561: sub store {
1.124     www      3562:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3563:     my $home='';
                   3564: 
1.168     albertel 3565:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3566: 
1.213     www      3567:     $symb=&symbclean($symb);
1.122     albertel 3568:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3569: 
1.620     albertel 3570:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3571:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3572: 
                   3573:     &devalidate($symb,$stuname,$domain);
1.109     www      3574: 
                   3575:     $symb=escape($symb);
1.187     www      3576:     if (!$namespace) { 
1.620     albertel 3577:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3578:           return ''; 
                   3579:        } 
                   3580:     }
1.620     albertel 3581:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3582: 
                   3583:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3584:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3585: 
1.12      www      3586:     my $namevalue='';
1.800     albertel 3587:     foreach my $key (keys(%$storehash)) {
                   3588:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3589:     }
1.12      www      3590:     $namevalue=~s/\&$//;
1.187     www      3591:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3592:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3593: }
                   3594: 
1.47      www      3595: # -------------------------------------------------------------- Critical Store
                   3596: 
                   3597: sub cstore {
1.124     www      3598:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3599:     my $home='';
                   3600: 
1.168     albertel 3601:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3602: 
1.213     www      3603:     $symb=&symbclean($symb);
1.122     albertel 3604:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3605: 
1.620     albertel 3606:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3607:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3608: 
                   3609:     &devalidate($symb,$stuname,$domain);
1.109     www      3610: 
                   3611:     $symb=escape($symb);
1.187     www      3612:     if (!$namespace) { 
1.620     albertel 3613:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3614:           return ''; 
                   3615:        } 
                   3616:     }
1.620     albertel 3617:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3618: 
                   3619:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3620:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3621: 
1.47      www      3622:     my $namevalue='';
1.800     albertel 3623:     foreach my $key (keys(%$storehash)) {
                   3624:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3625:     }
1.47      www      3626:     $namevalue=~s/\&$//;
1.187     www      3627:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3628:     return critical
                   3629:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3630: }
                   3631: 
1.9       www      3632: # --------------------------------------------------------------------- Restore
                   3633: 
                   3634: sub restore {
1.124     www      3635:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3636:     my $home='';
                   3637: 
1.168     albertel 3638:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3639: 
1.122     albertel 3640:     if (!$symb) {
                   3641:       unless ($symb=escape(&symbread())) { return ''; }
                   3642:     } else {
1.213     www      3643:       $symb=&escape(&symbclean($symb));
1.122     albertel 3644:     }
1.188     www      3645:     if (!$namespace) { 
1.620     albertel 3646:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3647:           return ''; 
                   3648:        } 
                   3649:     }
1.620     albertel 3650:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3651:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3652:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3653:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3654: 
1.12      www      3655:     my %returnhash=();
1.800     albertel 3656:     foreach my $line (split(/\&/,$answer)) {
                   3657: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3658:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3659:     }
1.75      www      3660:     my $version;
                   3661:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3662:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3663:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3664:        }
1.75      www      3665:     }
1.13      www      3666:     return %returnhash;
1.34      www      3667: }
                   3668: 
                   3669: # ---------------------------------------------------------- Course Description
                   3670: 
                   3671: sub coursedescription {
1.731     albertel 3672:     my ($courseid,$args)=@_;
1.34      www      3673:     $courseid=~s/^\///;
1.49      www      3674:     $courseid=~s/\_/\//g;
1.34      www      3675:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3676:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3677:     my $normalid=$cdomain.'_'.$cnum;
                   3678:     # need to always cache even if we get errors otherwise we keep 
                   3679:     # trying and trying and trying to get the course description.
                   3680:     my %envhash=();
                   3681:     my %returnhash=();
1.731     albertel 3682:     
                   3683:     my $expiretime=600;
                   3684:     if ($env{'request.course.id'} eq $normalid) {
                   3685: 	$expiretime=120;
                   3686:     }
                   3687: 
                   3688:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3689:     if (!$args->{'freshen_cache'}
                   3690: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3691: 	foreach my $key (keys(%env)) {
                   3692: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3693: 	    my ($setting) = $1;
                   3694: 	    $returnhash{$setting} = $env{$key};
                   3695: 	}
                   3696: 	return %returnhash;
                   3697:     }
                   3698: 
                   3699:     # get the data agin
                   3700:     if (!$args->{'one_time'}) {
                   3701: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3702:     }
1.811     albertel 3703: 
1.34      www      3704:     if ($chome ne 'no_host') {
1.302     albertel 3705:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3706:        if (!exists($returnhash{'con_lost'})) {
                   3707:            $returnhash{'home'}= $chome;
                   3708: 	   $returnhash{'domain'} = $cdomain;
                   3709: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3710:            if (!defined($returnhash{'type'})) {
                   3711:                $returnhash{'type'} = 'Course';
                   3712:            }
1.130     albertel 3713:            while (my ($name,$value) = each %returnhash) {
1.53      www      3714:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3715:            }
1.270     www      3716:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3717:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3718: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3719:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3720:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3721:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3722:        }
                   3723:     }
1.731     albertel 3724:     if (!$args->{'one_time'}) {
1.949     raeburn  3725: 	&appenv(\%envhash);
1.731     albertel 3726:     }
1.302     albertel 3727:     return %returnhash;
1.461     www      3728: }
                   3729: 
                   3730: # -------------------------------------------------See if a user is privileged
                   3731: 
                   3732: sub privileged {
                   3733:     my ($username,$domain)=@_;
                   3734:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3735: 			&homeserver($username,$domain));
                   3736:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3737:     my $now=time;
                   3738:     if ($rolesdump ne '') {
1.800     albertel 3739:         foreach my $entry (split(/&/,$rolesdump)) {
                   3740: 	    if ($entry!~/^rolesdef_/) {
                   3741: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3742: 		$area=~s/\_\w\w$//;
                   3743: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3744: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3745: 		    my $active=1;
                   3746: 		    if ($tend) {
                   3747: 			if ($tend<$now) { $active=0; }
                   3748: 		    }
                   3749: 		    if ($tstart) {
                   3750: 			if ($tstart>$now) { $active=0; }
                   3751: 		    }
                   3752: 		    if ($active) { return 1; }
                   3753: 		}
                   3754: 	    }
                   3755: 	}
                   3756:     }
                   3757:     return 0;
1.9       www      3758: }
1.1       albertel 3759: 
1.103     harris41 3760: # -------------------------------------------------------- Get user privileges
1.11      www      3761: 
                   3762: sub rolesinit {
                   3763:     my ($domain,$username,$authhost)=@_;
1.966     raeburn  3764:     my %userroles;
1.11      www      3765:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.966     raeburn  3766:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
1.11      www      3767:     my %allroles=();
1.678     raeburn  3768:     my %allgroups=();   
1.11      www      3769:     my $now=time;
1.966     raeburn  3770:     %userroles = ('user.login.time' => $now);
1.678     raeburn  3771:     my $group_privs;
1.11      www      3772: 
                   3773:     if ($rolesdump ne '') {
1.800     albertel 3774:         foreach my $entry (split(/&/,$rolesdump)) {
                   3775: 	  if ($entry!~/^rolesdef_/) {
                   3776:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3777: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3778:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3779: 	    if ($role=~/^cr/) { 
1.807     albertel 3780: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3781: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3782: 		    ($tend,$tstart)=split('_',$trest);
                   3783: 		} else {
                   3784: 		    $trole=$role;
                   3785: 		}
1.678     raeburn  3786:             } elsif ($role =~ m|^gr/|) {
                   3787:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3788:                 ($trole,$group_privs) = split(/\//,$trole);
                   3789:                 $group_privs = &unescape($group_privs);
1.587     albertel 3790: 	    } else {
                   3791: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3792: 	    }
1.743     albertel 3793: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3794: 					 $username);
                   3795: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3796:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3797:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3798:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3799: 		my $spec=$trole.'.'.$area;
                   3800: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3801: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3802:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3803:                 } elsif ($trole eq 'gr') {
                   3804:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3805: 		} else {
1.567     raeburn  3806:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3807: 		}
1.12      www      3808:             }
1.662     raeburn  3809:           }
1.191     harris41 3810:         }
1.743     albertel 3811:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3812:         $userroles{'user.adv'}    = $adv;
                   3813: 	$userroles{'user.author'} = $author;
1.620     albertel 3814:         $env{'user.adv'}=$adv;
1.11      www      3815:     }
1.743     albertel 3816:     return \%userroles;  
1.11      www      3817: }
                   3818: 
1.567     raeburn  3819: sub set_arearole {
                   3820:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3821: # log the associated role with the area
                   3822:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3823:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3824: }
                   3825: 
                   3826: sub custom_roleprivs {
                   3827:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3828:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3829:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3830:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3831:         my ($rdummy,$roledef)=
                   3832:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3833:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3834:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3835:             if (defined($syspriv)) {
                   3836:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3837:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3838:             }
                   3839:             if ($tdomain ne '') {
                   3840:                 if (defined($dompriv)) {
                   3841:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3842:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3843:                 }
                   3844:                 if (($trest ne '') && (defined($coursepriv))) {
                   3845:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3846:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3847:                 }
                   3848:             }
                   3849:         }
                   3850:     }
                   3851: }
                   3852: 
1.678     raeburn  3853: sub group_roleprivs {
                   3854:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3855:     my $access = 1;
                   3856:     my $now = time;
                   3857:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3858:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3859:     if ($access) {
1.811     albertel 3860:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3861:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3862:     }
                   3863: }
1.567     raeburn  3864: 
                   3865: sub standard_roleprivs {
                   3866:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3867:     if (defined($pr{$trole.':s'})) {
                   3868:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3869:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3870:     }
                   3871:     if ($tdomain ne '') {
                   3872:         if (defined($pr{$trole.':d'})) {
                   3873:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3874:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3875:         }
                   3876:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3877:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3878:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3879:         }
                   3880:     }
                   3881: }
                   3882: 
                   3883: sub set_userprivs {
1.678     raeburn  3884:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3885:     my $author=0;
                   3886:     my $adv=0;
1.678     raeburn  3887:     my %grouproles = ();
                   3888:     if (keys(%{$allgroups}) > 0) {
1.1000    raeburn  3889:         foreach my $role (keys(%{$allroles})) {
1.681     raeburn  3890:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3891:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3892:                 $trole = $1;
                   3893:                 $area = $2;
1.681     raeburn  3894:                 $sec = $3;
                   3895:                 $extendedarea = $area.$sec;
                   3896:                 if (exists($$allgroups{$area})) {
                   3897:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3898:                         my $spec = $trole.'.'.$extendedarea;
                   3899:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3900:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3901:                     }
                   3902:                 }
                   3903:             }
                   3904:         }
                   3905:     }
1.800     albertel 3906:     foreach my $group (keys(%grouproles)) {
                   3907:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3908:     }
1.800     albertel 3909:     foreach my $role (keys(%{$allroles})) {
                   3910:         my %thesepriv;
1.941     raeburn  3911:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3912:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3913:             if ($item ne '') {
                   3914:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3915:                 if ($restrictions eq '') {
                   3916:                     $thesepriv{$privilege}='F';
                   3917:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3918:                     $thesepriv{$privilege}.=$restrictions;
                   3919:                 }
                   3920:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3921:             }
                   3922:         }
                   3923:         my $thesestr='';
1.800     albertel 3924:         foreach my $priv (keys(%thesepriv)) {
                   3925: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3926: 	}
                   3927:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3928:     }
                   3929:     return ($author,$adv);
                   3930: }
                   3931: 
1.994     raeburn  3932: sub role_status {
                   3933:     my ($rolekey,$then,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
                   3934:     my @pwhere = ();
                   3935:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   3936:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   3937:         unless (!defined($$role) || $$role eq '') {
                   3938:             $$where=join('.',@pwhere);
                   3939:             $$trolecode=$$role.'.'.$$where;
                   3940:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   3941:             $$tstatus='is';
                   3942:             if ($$tstart && $$tstart>$then) {
                   3943:                 $$tstatus='future';
                   3944:                 if ($$tstart<$now) { $$tstatus='will'; }
                   3945:             }
                   3946:             if ($$tend) {
                   3947:                 if ($$tend<$then) {
                   3948:                     $$tstatus='expired';
                   3949:                 } elsif ($$tend<$now) {
                   3950:                     $$tstatus='will_not';
                   3951:                 }
                   3952:             }
                   3953:         }
                   3954:     }
                   3955: }
                   3956: 
                   3957: sub check_adhoc_privs {
                   3958:     my ($cdom,$cnum,$then,$now,$checkrole) = @_;
                   3959:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   3960:     if ($env{$cckey}) {
                   3961:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
                   3962:         &role_status($cckey,$then,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
                   3963:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
                   3964:             &set_adhoc_privileges($cdom,$cnum,$checkrole);
                   3965:         }
                   3966:     } else {
                   3967:         &set_adhoc_privileges($cdom,$cnum,$checkrole);
                   3968:     }
                   3969: }
                   3970: 
                   3971: sub set_adhoc_privileges {
                   3972: # role can be cc or ca
                   3973:     my ($dcdom,$pickedcourse,$role) = @_;
                   3974:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   3975:     my $spec = $role.'.'.$area;
                   3976:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   3977:                                   $env{'user.name'});
                   3978:     my %ccrole = ();
                   3979:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   3980:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   3981:     &appenv(\%userroles,[$role,'cm']);
                   3982:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   3983:     &appenv( {'request.role'        => $spec,
                   3984:               'request.role.domain' => $dcdom,
                   3985:               'request.course.sec'  => ''
                   3986:              }
                   3987:            );
                   3988:     my $tadv=0;
                   3989:     if (&allowed('adv') eq 'F') { $tadv=1; }
                   3990:     &appenv({'request.role.adv'    => $tadv});
                   3991: }
                   3992: 
1.12      www      3993: # --------------------------------------------------------------- get interface
                   3994: 
                   3995: sub get {
1.131     albertel 3996:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3997:    my $items='';
1.800     albertel 3998:    foreach my $item (@$storearr) {
                   3999:        $items.=&escape($item).'&';
1.191     harris41 4000:    }
1.12      www      4001:    $items=~s/\&$//;
1.620     albertel 4002:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4003:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4004:    my $uhome=&homeserver($uname,$udomain);
                   4005: 
1.133     albertel 4006:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4007:    my @pairs=split(/\&/,$rep);
1.273     albertel 4008:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4009:      return @pairs;
                   4010:    }
1.15      www      4011:    my %returnhash=();
1.42      www      4012:    my $i=0;
1.800     albertel 4013:    foreach my $item (@$storearr) {
                   4014:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4015:       $i++;
1.191     harris41 4016:    }
1.15      www      4017:    return %returnhash;
1.27      www      4018: }
                   4019: 
                   4020: # --------------------------------------------------------------- del interface
                   4021: 
                   4022: sub del {
1.133     albertel 4023:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4024:    my $items='';
1.800     albertel 4025:    foreach my $item (@$storearr) {
                   4026:        $items.=&escape($item).'&';
1.191     harris41 4027:    }
1.984     neumanie 4028: 
1.27      www      4029:    $items=~s/\&$//;
1.620     albertel 4030:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4031:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4032:    my $uhome=&homeserver($uname,$udomain);
                   4033:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4034: }
                   4035: 
                   4036: # -------------------------------------------------------------- dump interface
                   4037: 
                   4038: sub dump {
1.755     albertel 4039:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   4040:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4041:     if (!$uname) { $uname=$env{'user.name'}; }
                   4042:     my $uhome=&homeserver($uname,$udomain);
                   4043:     if ($regexp) {
                   4044: 	$regexp=&escape($regexp);
                   4045:     } else {
                   4046: 	$regexp='.';
                   4047:     }
                   4048:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4049:     my @pairs=split(/\&/,$rep);
                   4050:     my %returnhash=();
                   4051:     foreach my $item (@pairs) {
                   4052: 	my ($key,$value)=split(/=/,$item,2);
                   4053: 	$key = &unescape($key);
                   4054: 	next if ($key =~ /^error: 2 /);
                   4055: 	$returnhash{$key}=&thaw_unescape($value);
                   4056:     }
                   4057:     return %returnhash;
1.407     www      4058: }
                   4059: 
1.717     albertel 4060: # --------------------------------------------------------- dumpstore interface
                   4061: 
                   4062: sub dumpstore {
                   4063:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4064:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4065:    if (!$uname) { $uname=$env{'user.name'}; }
                   4066:    my $uhome=&homeserver($uname,$udomain);
                   4067:    if ($regexp) {
                   4068:        $regexp=&escape($regexp);
                   4069:    } else {
                   4070:        $regexp='.';
                   4071:    }
                   4072:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4073:    my @pairs=split(/\&/,$rep);
                   4074:    my %returnhash=();
                   4075:    foreach my $item (@pairs) {
                   4076:        my ($key,$value)=split(/=/,$item,2);
                   4077:        next if ($key =~ /^error: 2 /);
                   4078:        $returnhash{$key}=&thaw_unescape($value);
                   4079:    }
                   4080:    return %returnhash;
1.717     albertel 4081: }
                   4082: 
1.407     www      4083: # -------------------------------------------------------------- keys interface
                   4084: 
                   4085: sub getkeys {
                   4086:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4087:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4088:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4089:    my $uhome=&homeserver($uname,$udomain);
                   4090:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4091:    my @keyarray=();
1.800     albertel 4092:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4093:       next if ($key =~ /^error: 2 /);
1.800     albertel 4094:       push(@keyarray,&unescape($key));
1.407     www      4095:    }
                   4096:    return @keyarray;
1.318     matthew  4097: }
                   4098: 
1.319     matthew  4099: # --------------------------------------------------------------- currentdump
                   4100: sub currentdump {
1.328     matthew  4101:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4102:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4103:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4104:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4105:    my $uhome = &homeserver($sname,$sdom);
                   4106:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4107:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4108:    #
1.318     matthew  4109:    my %returnhash=();
1.319     matthew  4110:    #
                   4111:    if ($rep eq "unknown_cmd") { 
                   4112:        # an old lond will not know currentdump
                   4113:        # Do a dump and make it look like a currentdump
1.822     albertel 4114:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4115:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4116:        my %hash = @tmp;
                   4117:        @tmp=();
1.424     matthew  4118:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4119:    } else {
                   4120:        my @pairs=split(/\&/,$rep);
1.800     albertel 4121:        foreach my $pair (@pairs) {
                   4122:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4123:            my ($symb,$param) = split(/:/,$key);
                   4124:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4125:                                                         &thaw_unescape($value);
1.319     matthew  4126:        }
1.191     harris41 4127:    }
1.12      www      4128:    return %returnhash;
1.424     matthew  4129: }
                   4130: 
                   4131: sub convert_dump_to_currentdump{
                   4132:     my %hash = %{shift()};
                   4133:     my %returnhash;
                   4134:     # Code ripped from lond, essentially.  The only difference
                   4135:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4136:     # we might run in to problems with parameter names =~ /^v\./
                   4137:     while (my ($key,$value) = each(%hash)) {
                   4138:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4139: 	$symb  = &unescape($symb);
                   4140: 	$param = &unescape($param);
1.424     matthew  4141:         next if ($v eq 'version' || $symb eq 'keys');
                   4142:         next if (exists($returnhash{$symb}) &&
                   4143:                  exists($returnhash{$symb}->{$param}) &&
                   4144:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4145:         $returnhash{$symb}->{$param}=$value;
                   4146:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4147:     }
                   4148:     #
                   4149:     # Remove all of the keys in the hashes which keep track of
                   4150:     # the version of the parameter.
                   4151:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4152:         # use a foreach because we are going to delete from the hash.
                   4153:         foreach my $key (keys(%$param_hash)) {
                   4154:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4155:         }
                   4156:     }
                   4157:     return \%returnhash;
1.12      www      4158: }
                   4159: 
1.627     albertel 4160: # ------------------------------------------------------ critical inc interface
                   4161: 
                   4162: sub cinc {
                   4163:     return &inc(@_,'critical');
                   4164: }
                   4165: 
1.449     matthew  4166: # --------------------------------------------------------------- inc interface
                   4167: 
                   4168: sub inc {
1.627     albertel 4169:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4170:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4171:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4172:     my $uhome=&homeserver($uname,$udomain);
                   4173:     my $items='';
                   4174:     if (! ref($store)) {
                   4175:         # got a single value, so use that instead
                   4176:         $items = &escape($store).'=&';
                   4177:     } elsif (ref($store) eq 'SCALAR') {
                   4178:         $items = &escape($$store).'=&';        
                   4179:     } elsif (ref($store) eq 'ARRAY') {
                   4180:         $items = join('=&',map {&escape($_);} @{$store});
                   4181:     } elsif (ref($store) eq 'HASH') {
                   4182:         while (my($key,$value) = each(%{$store})) {
                   4183:             $items.= &escape($key).'='.&escape($value).'&';
                   4184:         }
                   4185:     }
                   4186:     $items=~s/\&$//;
1.627     albertel 4187:     if ($critical) {
                   4188: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4189:     } else {
                   4190: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4191:     }
1.449     matthew  4192: }
                   4193: 
1.12      www      4194: # --------------------------------------------------------------- put interface
                   4195: 
                   4196: sub put {
1.134     albertel 4197:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4198:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4199:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4200:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4201:    my $items='';
1.800     albertel 4202:    foreach my $item (keys(%$storehash)) {
                   4203:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4204:    }
1.12      www      4205:    $items=~s/\&$//;
1.134     albertel 4206:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4207: }
                   4208: 
1.631     albertel 4209: # ------------------------------------------------------------ newput interface
                   4210: 
                   4211: sub newput {
                   4212:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4213:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4214:    if (!$uname) { $uname=$env{'user.name'}; }
                   4215:    my $uhome=&homeserver($uname,$udomain);
                   4216:    my $items='';
                   4217:    foreach my $key (keys(%$storehash)) {
                   4218:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4219:    }
                   4220:    $items=~s/\&$//;
                   4221:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4222: }
                   4223: 
                   4224: # ---------------------------------------------------------  putstore interface
                   4225: 
1.524     raeburn  4226: sub putstore {
1.715     albertel 4227:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4228:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4229:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4230:    my $uhome=&homeserver($uname,$udomain);
                   4231:    my $items='';
1.715     albertel 4232:    foreach my $key (keys(%$storehash)) {
                   4233:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4234:    }
1.715     albertel 4235:    $items=~s/\&$//;
1.716     albertel 4236:    my $esc_symb=&escape($symb);
                   4237:    my $esc_v=&escape($version);
1.715     albertel 4238:    my $reply =
1.716     albertel 4239:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4240: 	      $uhome);
                   4241:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4242:        # gfall back to way things use to be done
1.715     albertel 4243:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4244: 			    $uname);
1.524     raeburn  4245:    }
1.715     albertel 4246:    return $reply;
                   4247: }
                   4248: 
                   4249: sub old_putstore {
1.716     albertel 4250:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4251:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4252:     if (!$uname) { $uname=$env{'user.name'}; }
                   4253:     my $uhome=&homeserver($uname,$udomain);
                   4254:     my %newstorehash;
1.800     albertel 4255:     foreach my $item (keys(%$storehash)) {
                   4256: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4257: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4258:     }
                   4259:     my $items='';
                   4260:     my %allitems = ();
1.800     albertel 4261:     foreach my $item (keys(%newstorehash)) {
                   4262: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4263: 	    my $key = $1.':keys:'.$2;
                   4264: 	    $allitems{$key} .= $3.':';
                   4265: 	}
1.800     albertel 4266: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4267:     }
1.800     albertel 4268:     foreach my $item (keys(%allitems)) {
                   4269: 	$allitems{$item} =~ s/\:$//;
                   4270: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4271:     }
                   4272:     $items=~s/\&$//;
                   4273:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4274: }
                   4275: 
1.47      www      4276: # ------------------------------------------------------ critical put interface
                   4277: 
                   4278: sub cput {
1.134     albertel 4279:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4280:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4281:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4282:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4283:    my $items='';
1.800     albertel 4284:    foreach my $item (keys(%$storehash)) {
                   4285:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4286:    }
1.47      www      4287:    $items=~s/\&$//;
1.134     albertel 4288:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4289: }
                   4290: 
                   4291: # -------------------------------------------------------------- eget interface
                   4292: 
                   4293: sub eget {
1.133     albertel 4294:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4295:    my $items='';
1.800     albertel 4296:    foreach my $item (@$storearr) {
                   4297:        $items.=&escape($item).'&';
1.191     harris41 4298:    }
1.12      www      4299:    $items=~s/\&$//;
1.620     albertel 4300:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4301:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4302:    my $uhome=&homeserver($uname,$udomain);
                   4303:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4304:    my @pairs=split(/\&/,$rep);
                   4305:    my %returnhash=();
1.42      www      4306:    my $i=0;
1.800     albertel 4307:    foreach my $item (@$storearr) {
                   4308:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4309:       $i++;
1.191     harris41 4310:    }
1.12      www      4311:    return %returnhash;
                   4312: }
                   4313: 
1.667     albertel 4314: # ------------------------------------------------------------ tmpput interface
                   4315: sub tmpput {
1.802     raeburn  4316:     my ($storehash,$server,$context)=@_;
1.667     albertel 4317:     my $items='';
1.800     albertel 4318:     foreach my $item (keys(%$storehash)) {
                   4319: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4320:     }
                   4321:     $items=~s/\&$//;
1.802     raeburn  4322:     if (defined($context)) {
                   4323:         $items .= ':'.&escape($context);
                   4324:     }
1.667     albertel 4325:     return &reply("tmpput:$items",$server);
                   4326: }
                   4327: 
                   4328: # ------------------------------------------------------------ tmpget interface
                   4329: sub tmpget {
1.688     albertel 4330:     my ($token,$server)=@_;
                   4331:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4332:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4333:     my %returnhash;
                   4334:     foreach my $item (split(/\&/,$rep)) {
                   4335: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4336:         next if ($key =~ /^error: 2 /);
1.667     albertel 4337: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4338:     }
                   4339:     return %returnhash;
                   4340: }
                   4341: 
1.688     albertel 4342: # ------------------------------------------------------------ tmpget interface
                   4343: sub tmpdel {
                   4344:     my ($token,$server)=@_;
                   4345:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4346:     return &reply("tmpdel:$token",$server);
                   4347: }
                   4348: 
1.765     albertel 4349: # -------------------------------------------------- portfolio access checking
                   4350: 
                   4351: sub portfolio_access {
1.766     albertel 4352:     my ($requrl) = @_;
1.765     albertel 4353:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4354:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4355:     if ($result) {
                   4356:         my %setters;
                   4357:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4358:             my ($startblock,$endblock) =
                   4359:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4360:             if ($startblock && $endblock) {
                   4361:                 return 'B';
                   4362:             }
                   4363:         } else {
                   4364:             my ($startblock,$endblock) =
                   4365:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4366:             if ($startblock && $endblock) {
                   4367:                 return 'B';
                   4368:             }
                   4369:         }
                   4370:     }
1.765     albertel 4371:     if ($result eq 'ok') {
1.766     albertel 4372:        return 'F';
1.765     albertel 4373:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4374:        return 'A';
1.765     albertel 4375:     }
1.766     albertel 4376:     return '';
1.765     albertel 4377: }
                   4378: 
                   4379: sub get_portfolio_access {
1.767     albertel 4380:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4381: 
                   4382:     if (!ref($access_hash)) {
                   4383: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4384: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4385: 						   $file_name);
                   4386: 	$access_hash = $access_controls{$file_name};
                   4387:     }
                   4388: 
1.765     albertel 4389:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4390:     my $now = time;
                   4391:     if (ref($access_hash) eq 'HASH') {
                   4392:         foreach my $key (keys(%{$access_hash})) {
                   4393:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4394:             if ($start > $now) {
                   4395:                 next;
                   4396:             }
                   4397:             if ($end && $end<$now) {
                   4398:                 next;
                   4399:             }
                   4400:             if ($scope eq 'public') {
                   4401:                 $public = $key;
                   4402:                 last;
                   4403:             } elsif ($scope eq 'guest') {
                   4404:                 $guest = $key;
                   4405:             } elsif ($scope eq 'domains') {
                   4406:                 push(@domains,$key);
                   4407:             } elsif ($scope eq 'users') {
                   4408:                 push(@users,$key);
                   4409:             } elsif ($scope eq 'course') {
                   4410:                 push(@courses,$key);
                   4411:             } elsif ($scope eq 'group') {
                   4412:                 push(@groups,$key);
                   4413:             }
                   4414:         }
                   4415:         if ($public) {
                   4416:             return 'ok';
                   4417:         }
                   4418:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4419:             if ($guest) {
                   4420:                 return $guest;
                   4421:             }
                   4422:         } else {
                   4423:             if (@domains > 0) {
                   4424:                 foreach my $domkey (@domains) {
                   4425:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4426:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4427:                             return 'ok';
                   4428:                         }
                   4429:                     }
                   4430:                 }
                   4431:             }
                   4432:             if (@users > 0) {
                   4433:                 foreach my $userkey (@users) {
1.865     raeburn  4434:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4435:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4436:                             if (ref($item) eq 'HASH') {
                   4437:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4438:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4439:                                     return 'ok';
                   4440:                                 }
                   4441:                             }
                   4442:                         }
                   4443:                     } 
1.765     albertel 4444:                 }
                   4445:             }
                   4446:             my %roleshash;
                   4447:             my @courses_and_groups = @courses;
                   4448:             push(@courses_and_groups,@groups); 
                   4449:             if (@courses_and_groups > 0) {
                   4450:                 my (%allgroups,%allroles); 
                   4451:                 my ($start,$end,$role,$sec,$group);
                   4452:                 foreach my $envkey (%env) {
1.811     albertel 4453:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4454:                         my $cid = $2.'_'.$3; 
                   4455:                         if ($1 eq 'gr') {
                   4456:                             $group = $4;
                   4457:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4458:                         } else {
                   4459:                             if ($4 eq '') {
                   4460:                                 $sec = 'none';
                   4461:                             } else {
                   4462:                                 $sec = $4;
                   4463:                             }
                   4464:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4465:                         }
1.811     albertel 4466:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4467:                         my $cid = $2.'_'.$3;
                   4468:                         if ($4 eq '') {
                   4469:                             $sec = 'none';
                   4470:                         } else {
                   4471:                             $sec = $4;
                   4472:                         }
                   4473:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4474:                     }
                   4475:                 }
                   4476:                 if (keys(%allroles) == 0) {
                   4477:                     return;
                   4478:                 }
                   4479:                 foreach my $key (@courses_and_groups) {
                   4480:                     my %content = %{$$access_hash{$key}};
                   4481:                     my $cnum = $content{'number'};
                   4482:                     my $cdom = $content{'domain'};
                   4483:                     my $cid = $cdom.'_'.$cnum;
                   4484:                     if (!exists($allroles{$cid})) {
                   4485:                         next;
                   4486:                     }    
                   4487:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4488:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4489:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4490:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4491:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4492:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4493:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4494:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4495:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4496:                                         if (grep/^all$/,@sections) {
                   4497:                                             return 'ok';
                   4498:                                         } else {
                   4499:                                             if (grep/^$sec$/,@sections) {
                   4500:                                                 return 'ok';
                   4501:                                             }
                   4502:                                         }
                   4503:                                     }
                   4504:                                 }
                   4505:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4506:                                     if (grep/^none$/,@groups) {
                   4507:                                         return 'ok';
                   4508:                                     }
                   4509:                                 } else {
                   4510:                                     if (grep/^all$/,@groups) {
                   4511:                                         return 'ok';
                   4512:                                     } 
                   4513:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4514:                                         if (grep/^$group$/,@groups) {
                   4515:                                             return 'ok';
                   4516:                                         }
                   4517:                                     }
                   4518:                                 } 
                   4519:                             }
                   4520:                         }
                   4521:                     }
                   4522:                 }
                   4523:             }
                   4524:             if ($guest) {
                   4525:                 return $guest;
                   4526:             }
                   4527:         }
                   4528:     }
                   4529:     return;
                   4530: }
                   4531: 
                   4532: sub course_group_datechecker {
                   4533:     my ($dates,$now,$status) = @_;
                   4534:     my ($start,$end) = split(/\./,$dates);
                   4535:     if (!$start && !$end) {
                   4536:         return 'ok';
                   4537:     }
                   4538:     if (grep/^active$/,@{$status}) {
                   4539:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4540:             return 'ok';
                   4541:         }
                   4542:     }
                   4543:     if (grep/^previous$/,@{$status}) {
                   4544:         if ($end > $now ) {
                   4545:             return 'ok';
                   4546:         }
                   4547:     }
                   4548:     if (grep/^future$/,@{$status}) {
                   4549:         if ($start > $now) {
                   4550:             return 'ok';
                   4551:         }
                   4552:     }
                   4553:     return; 
                   4554: }
                   4555: 
                   4556: sub parse_portfolio_url {
                   4557:     my ($url) = @_;
                   4558: 
                   4559:     my ($type,$udom,$unum,$group,$file_name);
                   4560:     
1.823     albertel 4561:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4562: 	$type = 1;
                   4563:         $udom = $1;
                   4564:         $unum = $2;
                   4565:         $file_name = $3;
1.823     albertel 4566:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4567: 	$type = 2;
                   4568:         $udom = $1;
                   4569:         $unum = $2;
                   4570:         $group = $3;
                   4571:         $file_name = $3.'/'.$4;
                   4572:     }
                   4573:     if (wantarray) {
                   4574: 	return ($type,$udom,$unum,$file_name,$group);
                   4575:     }
                   4576:     return $type;
                   4577: }
                   4578: 
                   4579: sub is_portfolio_url {
                   4580:     my ($url) = @_;
                   4581:     return scalar(&parse_portfolio_url($url));
                   4582: }
                   4583: 
1.798     raeburn  4584: sub is_portfolio_file {
                   4585:     my ($file) = @_;
1.820     raeburn  4586:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4587:         return 1;
                   4588:     }
                   4589:     return;
                   4590: }
                   4591: 
1.976     raeburn  4592: sub usertools_access {
1.985     raeburn  4593:     my ($uname,$udom,$tool,$action,$context) = @_;
                   4594:     my ($access,%tools);
                   4595:     if ($context eq '') {
                   4596:         $context = 'tools';
                   4597:     }
                   4598:     if ($context eq 'requestcourses') {
                   4599:         %tools = (
                   4600:                       official   => 1,
                   4601:                       unofficial => 1,
                   4602:                  );
                   4603:     } else {
                   4604:         %tools = (
                   4605:                       aboutme   => 1,
                   4606:                       blog      => 1,
                   4607:                       portfolio => 1,
                   4608:                  );
                   4609:     }
1.976     raeburn  4610:     return if (!defined($tools{$tool}));
                   4611: 
                   4612:     if ((!defined($udom)) || (!defined($uname))) {
                   4613:         $udom = $env{'user.domain'};
                   4614:         $uname = $env{'user.name'};
                   4615:     }
                   4616: 
1.978     raeburn  4617:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4618:         if ($action ne 'reload') {
1.985     raeburn  4619:             if ($context eq 'requestcourses') {
                   4620:                 return $env{'environment.canrequest.'.$tool};
                   4621:             } else {
                   4622:                 return $env{'environment.availabletools.'.$tool};
                   4623:             }
                   4624:         }
1.976     raeburn  4625:     }
                   4626: 
                   4627:     my ($toolstatus,$inststatus);
                   4628: 
1.985     raeburn  4629:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   4630:          ($action ne 'reload')) {
                   4631:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  4632:         $inststatus = $env{'environment.inststatus'};
                   4633:     } else {
1.985     raeburn  4634:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool);
                   4635:         $toolstatus = $userenv{$context.'.'.$tool};
1.976     raeburn  4636:         $inststatus = $userenv{'inststatus'};
                   4637:     }
                   4638: 
                   4639:     if ($toolstatus ne '') {
                   4640:         if ($toolstatus) {
                   4641:             $access = 1;
                   4642:         } else {
                   4643:             $access = 0;
                   4644:         }
                   4645:         return $access;
                   4646:     }
                   4647: 
                   4648:     my $is_adv = &is_advanced_user($udom,$uname);
                   4649:     my %domdef = &get_domain_defaults($udom);
                   4650:     if (ref($domdef{$tool}) eq 'HASH') {
                   4651:         if ($is_adv) {
                   4652:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   4653:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   4654:                     $access = 1;
                   4655:                 } else {
                   4656:                     $access = 0;
                   4657:                 }
                   4658:                 return $access;
                   4659:             }
                   4660:         }
                   4661:         if ($inststatus ne '') {
                   4662:             my ($hasaccess,$hasnoaccess);
                   4663:             foreach my $affiliation (split(/:/,$inststatus)) {
                   4664:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   4665:                     if ($domdef{$tool}{$affiliation}) {
                   4666:                         $hasaccess = 1;
                   4667:                     } else {
                   4668:                         $hasnoaccess = 1;
                   4669:                     }
                   4670:                 }
                   4671:             }
                   4672:             if ($hasaccess || $hasnoaccess) {
                   4673:                 if ($hasaccess) {
                   4674:                     $access = 1;
                   4675:                 } elsif ($hasnoaccess) {
                   4676:                     $access = 0; 
                   4677:                 }
                   4678:                 return $access;
                   4679:             }
                   4680:         } else {
                   4681:             if ($domdef{$tool}{'default'} ne '') {
                   4682:                 if ($domdef{$tool}{'default'}) {
                   4683:                     $access = 1;
                   4684:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   4685:                     $access = 0;
                   4686:                 }
                   4687:                 return $access;
                   4688:             }
                   4689:         }
                   4690:     } else {
1.985     raeburn  4691:         if ($context eq 'tools') {
                   4692:             $access = 1;
                   4693:         } else {
                   4694:             $access = 0;
                   4695:         }
1.976     raeburn  4696:         return $access;
                   4697:     }
                   4698: }
                   4699: 
                   4700: sub is_advanced_user {
                   4701:     my ($udom,$uname) = @_;
                   4702:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   4703:     my %allroles;
                   4704:     my $is_adv;
                   4705:     foreach my $role (keys(%roleshash)) {
                   4706:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   4707:         my $area = '/'.$tdomain.'/'.$trest;
                   4708:         if ($sec ne '') {
                   4709:             $area .= '/'.$sec;
                   4710:         }
                   4711:         if (($area ne '') && ($trole ne '')) {
                   4712:             my $spec=$trole.'.'.$area;
                   4713:             if ($trole =~ /^cr\//) {
                   4714:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4715:             } elsif ($trole ne 'gr') {
                   4716:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4717:             }
                   4718:         }
                   4719:     }
                   4720:     foreach my $role (keys(%allroles)) {
                   4721:         last if ($is_adv);
                   4722:         foreach my $item (split(/:/,$allroles{$role})) {
                   4723:             if ($item ne '') {
                   4724:                 my ($privilege,$restrictions)=split(/&/,$item);
                   4725:                 if ($privilege eq 'adv') {
                   4726:                     $is_adv = 1;
                   4727:                     last;
                   4728:                 }
                   4729:             }
                   4730:         }
                   4731:     }
                   4732:     return $is_adv;
                   4733: }
1.798     raeburn  4734: 
1.341     www      4735: # ---------------------------------------------- Custom access rule evaluation
                   4736: 
                   4737: sub customaccess {
                   4738:     my ($priv,$uri)=@_;
1.807     albertel 4739:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4740:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4741:     $udom = &LONCAPA::clean_domain($udom);
                   4742:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4743:     my $access=0;
1.800     albertel 4744:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4745: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4746: 	if ($type eq 'user') {
                   4747: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4748: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4749: 		if ($tdom) {
                   4750: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4751: 		}
1.896     albertel 4752: 		if ($tuname) {
                   4753: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4754: 		}
                   4755: 		$access=($effect eq 'allow');
                   4756: 		last;
                   4757: 	    }
                   4758: 	} else {
                   4759: 	    if ($role) {
                   4760: 		if ($role ne $urole) { next; }
                   4761: 	    }
                   4762: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4763: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4764: 		if ($tdom) {
                   4765: 		    if ($tdom ne $udom) { next; }
                   4766: 		}
                   4767: 		if ($tcrs) {
                   4768: 		    if ($tcrs ne $ucrs) { next; }
                   4769: 		}
                   4770: 		if ($tsec) {
                   4771: 		    if ($tsec ne $usec) { next; }
                   4772: 		}
                   4773: 		$access=($effect eq 'allow');
                   4774: 		last;
                   4775: 	    }
                   4776: 	    if ($realm eq '' && $role eq '') {
                   4777: 		$access=($effect eq 'allow');
                   4778: 	    }
1.402     bowersj2 4779: 	}
1.341     www      4780:     }
                   4781:     return $access;
                   4782: }
                   4783: 
1.103     harris41 4784: # ------------------------------------------------- Check for a user privilege
1.12      www      4785: 
                   4786: sub allowed {
1.810     raeburn  4787:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4788:     my $ver_orguri=$uri;
1.439     www      4789:     $uri=&deversion($uri);
1.152     www      4790:     my $orguri=$uri;
1.52      www      4791:     $uri=&declutter($uri);
1.809     raeburn  4792: 
1.810     raeburn  4793:     if ($priv eq 'evb') {
                   4794: # Evade communication block restrictions for specified role in a course
                   4795:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4796:             return $1;
                   4797:         } else {
                   4798:             return;
                   4799:         }
                   4800:     }
                   4801: 
1.620     albertel 4802:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4803: # Free bre access to adm and meta resources
1.775     albertel 4804:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4805: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4806: 	&& ($priv eq 'bre')) {
1.14      www      4807: 	return 'F';
1.159     www      4808:     }
                   4809: 
1.545     banghart 4810: # Free bre access to user's own portfolio contents
1.714     raeburn  4811:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4812:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4813: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4814:         my %setters;
                   4815:         my ($startblock,$endblock) = 
                   4816:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4817:         if ($startblock && $endblock) {
                   4818:             return 'B';
                   4819:         } else {
                   4820:             return 'F';
                   4821:         }
1.545     banghart 4822:     }
                   4823: 
1.762     raeburn  4824: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4825:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4826:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4827:         if (exists($env{'request.course.id'})) {
                   4828:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4829:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4830:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4831:                 my $courseprivid=$env{'request.course.id'};
                   4832:                 $courseprivid=~s/\_/\//;
                   4833:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4834:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4835:                     return $1; 
1.762     raeburn  4836:                 } else {
                   4837:                     if ($env{'request.course.sec'}) {
                   4838:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4839:                     }
                   4840:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4841:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4842:                         return $2;
                   4843:                     }
1.714     raeburn  4844:                 }
                   4845:             }
                   4846:         }
                   4847:     }
                   4848: 
1.159     www      4849: # Free bre to public access
                   4850: 
                   4851:     if ($priv eq 'bre') {
1.238     www      4852:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4853: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4854:            return 'F'; 
                   4855:         }
1.238     www      4856:         if ($copyright eq 'priv') {
                   4857:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4858: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4859: 		return '';
                   4860:             }
                   4861:         }
                   4862:         if ($copyright eq 'domain') {
                   4863:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4864: 	    unless (($env{'user.domain'} eq $1) ||
                   4865:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4866: 		return '';
                   4867:             }
1.262     matthew  4868:         }
1.620     albertel 4869:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4870:             # Library role, so allow browsing of resources in this domain.
                   4871:             return 'F';
1.238     www      4872:         }
1.341     www      4873:         if ($copyright eq 'custom') {
                   4874: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4875:         }
1.14      www      4876:     }
1.264     matthew  4877:     # Domain coordinator is trying to create a course
1.620     albertel 4878:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4879:         # uri is the requested domain in this case.
                   4880:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4881:         # a role of dc for the domain in question.
1.620     albertel 4882:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4883:     }
1.29      www      4884: 
1.52      www      4885:     my $thisallowed='';
                   4886:     my $statecond=0;
                   4887:     my $courseprivid='';
                   4888: 
                   4889: # Course
                   4890: 
1.620     albertel 4891:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4892:        $thisallowed.=$1;
                   4893:     }
1.29      www      4894: 
1.52      www      4895: # Domain
                   4896: 
1.620     albertel 4897:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4898:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4899:        $thisallowed.=$1;
                   4900:     }
1.52      www      4901: 
                   4902: # Course: uri itself is a course
1.66      www      4903:     my $courseuri=$uri;
                   4904:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4905:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4906: 
1.620     albertel 4907:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4908:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4909:        $thisallowed.=$1;
                   4910:     }
1.29      www      4911: 
1.665     albertel 4912: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4913: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4914:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4915: 	$thisallowed='';
1.671     raeburn  4916:         my ($match)=&is_on_map($uri);
                   4917:         if ($match) {
                   4918:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4919:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4920:                 $thisallowed.=$1;
                   4921:             }
                   4922:         } else {
1.705     albertel 4923:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4924:             if ($refuri) {
                   4925:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4926:                     $thisallowed='F';
1.671     raeburn  4927:                 } else {
                   4928:                     $refuri=&declutter($refuri);
                   4929:                     my ($match) = &is_on_map($refuri);
                   4930:                     if ($match) {
                   4931:                         $thisallowed='F';
                   4932:                     }
1.669     raeburn  4933:                 }
1.671     raeburn  4934:             }
                   4935:         }
1.314     www      4936:     }
1.492     albertel 4937: 
1.766     albertel 4938:     if ($priv eq 'bre'
                   4939: 	&& $thisallowed ne 'F' 
                   4940: 	&& $thisallowed ne '2'
                   4941: 	&& &is_portfolio_url($uri)) {
                   4942: 	$thisallowed = &portfolio_access($uri);
                   4943:     }
                   4944:     
1.52      www      4945: # Full access at system, domain or course-wide level? Exit.
1.29      www      4946:     if ($thisallowed=~/F/) {
                   4947: 	return 'F';
                   4948:     }
                   4949: 
1.52      www      4950: # If this is generating or modifying users, exit with special codes
1.29      www      4951: 
1.643     www      4952:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4953: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4954: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4955: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4956: 	    unless ($auname) { return $thisallowed; }
                   4957: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4958: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4959: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4960: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4961: 	}
1.52      www      4962: 	return $thisallowed;
                   4963:     }
                   4964: #
1.103     harris41 4965: # Gathered so far: system, domain and course wide privileges
1.52      www      4966: #
                   4967: # Course: See if uri or referer is an individual resource that is part of 
                   4968: # the course
                   4969: 
1.620     albertel 4970:     if ($env{'request.course.id'}) {
1.232     www      4971: 
1.620     albertel 4972:        $courseprivid=$env{'request.course.id'};
                   4973:        if ($env{'request.course.sec'}) {
                   4974:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4975:        }
                   4976:        $courseprivid=~s/\_/\//;
                   4977:        my $checkreferer=1;
1.232     www      4978:        my ($match,$cond)=&is_on_map($uri);
                   4979:        if ($match) {
                   4980:            $statecond=$cond;
1.620     albertel 4981:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4982:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4983:                $thisallowed.=$1;
                   4984:                $checkreferer=0;
                   4985:            }
1.29      www      4986:        }
1.83      www      4987:        
1.148     www      4988:        if ($checkreferer) {
1.620     albertel 4989: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4990:             unless ($refuri) {
1.800     albertel 4991:                 foreach my $key (keys(%env)) {
                   4992: 		    if ($key=~/^httpref\..*\*/) {
                   4993: 			my $pattern=$key;
1.156     www      4994:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4995:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4996:                         $pattern=~s/\//\\\//g;
1.152     www      4997:                         if ($orguri=~/$pattern/) {
1.800     albertel 4998: 			    $refuri=$env{$key};
1.148     www      4999:                         }
                   5000:                     }
1.191     harris41 5001:                 }
1.148     www      5002:             }
1.232     www      5003: 
1.148     www      5004:          if ($refuri) { 
1.152     www      5005: 	  $refuri=&declutter($refuri);
1.232     www      5006:           my ($match,$cond)=&is_on_map($refuri);
                   5007:             if ($match) {
                   5008:               my $refstatecond=$cond;
1.620     albertel 5009:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5010:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5011:                   $thisallowed.=$1;
1.53      www      5012:                   $uri=$refuri;
                   5013:                   $statecond=$refstatecond;
1.52      www      5014:               }
                   5015:           }
1.148     www      5016:         }
1.29      www      5017:        }
1.52      www      5018:    }
1.29      www      5019: 
1.52      www      5020: #
1.103     harris41 5021: # Gathered now: all privileges that could apply, and condition number
1.52      www      5022: # 
                   5023: #
                   5024: # Full or no access?
                   5025: #
1.29      www      5026: 
1.52      www      5027:     if ($thisallowed=~/F/) {
                   5028: 	return 'F';
                   5029:     }
1.29      www      5030: 
1.52      www      5031:     unless ($thisallowed) {
                   5032:         return '';
                   5033:     }
1.29      www      5034: 
1.52      www      5035: # Restrictions exist, deal with them
                   5036: #
                   5037: #   C:according to course preferences
                   5038: #   R:according to resource settings
                   5039: #   L:unless locked
                   5040: #   X:according to user session state
                   5041: #
                   5042: 
                   5043: # Possibly locked functionality, check all courses
1.54      www      5044: # Locks might take effect only after 10 minutes cache expiration for other
                   5045: # courses, and 2 minutes for current course
1.52      www      5046: 
                   5047:     my $envkey;
                   5048:     if ($thisallowed=~/L/) {
1.1000    raeburn  5049:         foreach $envkey (keys(%env)) {
1.54      www      5050:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5051:                my $courseid=$2;
                   5052:                my $roleid=$1.'.'.$2;
1.92      www      5053:                $courseid=~s/^\///;
1.54      www      5054:                my $expiretime=600;
1.620     albertel 5055:                if ($env{'request.role'} eq $roleid) {
1.54      www      5056: 		  $expiretime=120;
                   5057:                }
                   5058: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5059:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5060:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5061: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5062:                }
1.620     albertel 5063:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5064:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5065: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5066:                        &log($env{'user.domain'},$env{'user.name'},
                   5067:                             $env{'user.home'},
1.57      www      5068:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5069:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5070:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5071: 		       return '';
                   5072:                    }
                   5073:                }
1.620     albertel 5074:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5075:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5076: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5077:                        &log($env{'user.domain'},$env{'user.name'},
                   5078:                             $env{'user.home'},
1.57      www      5079:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5080:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5081:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5082: 		       return '';
                   5083:                    }
                   5084:                }
                   5085: 	   }
1.29      www      5086:        }
1.52      www      5087:     }
                   5088:    
                   5089: #
                   5090: # Rest of the restrictions depend on selected course
                   5091: #
                   5092: 
1.620     albertel 5093:     unless ($env{'request.course.id'}) {
1.766     albertel 5094: 	if ($thisallowed eq 'A') {
                   5095: 	    return 'A';
1.814     raeburn  5096:         } elsif ($thisallowed eq 'B') {
                   5097:             return 'B';
1.766     albertel 5098: 	} else {
                   5099: 	    return '1';
                   5100: 	}
1.52      www      5101:     }
1.29      www      5102: 
1.52      www      5103: #
                   5104: # Now user is definitely in a course
                   5105: #
1.53      www      5106: 
                   5107: 
                   5108: # Course preferences
                   5109: 
                   5110:    if ($thisallowed=~/C/) {
1.620     albertel 5111:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5112:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5113:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5114: 	   =~/\Q$rolecode\E/) {
1.689     albertel 5115: 	   if ($priv ne 'pch') { 
                   5116: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5117: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5118: 			$env{'request.course.id'});
                   5119: 	   }
1.237     www      5120:            return '';
                   5121:        }
                   5122: 
1.620     albertel 5123:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5124: 	   =~/\Q$unamedom\E/) {
1.689     albertel 5125: 	   if ($priv ne 'pch') { 
                   5126: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5127: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5128: 			$env{'request.course.id'});
                   5129: 	   }
1.54      www      5130:            return '';
                   5131:        }
1.53      www      5132:    }
                   5133: 
                   5134: # Resource preferences
                   5135: 
                   5136:    if ($thisallowed=~/R/) {
1.620     albertel 5137:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5138:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 5139: 	   if ($priv ne 'pch') { 
                   5140: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5141: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5142: 	   }
                   5143: 	   return '';
1.54      www      5144:        }
1.53      www      5145:    }
1.30      www      5146: 
1.246     www      5147: # Restricted by state or randomout?
1.30      www      5148: 
1.52      www      5149:    if ($thisallowed=~/X/) {
1.620     albertel 5150:       if ($env{'acc.randomout'}) {
1.579     albertel 5151: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5152:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5153:             return ''; 
                   5154:          }
1.247     www      5155:       }
                   5156:       if (&condval($statecond)) {
1.52      www      5157: 	 return '2';
                   5158:       } else {
                   5159:          return '';
                   5160:       }
                   5161:    }
1.30      www      5162: 
1.766     albertel 5163:     if ($thisallowed eq 'A') {
                   5164: 	return 'A';
1.814     raeburn  5165:     } elsif ($thisallowed eq 'B') {
                   5166:         return 'B';
1.766     albertel 5167:     }
1.52      www      5168:    return 'F';
1.232     www      5169: }
                   5170: 
1.710     albertel 5171: sub split_uri_for_cond {
                   5172:     my $uri=&deversion(&declutter(shift));
                   5173:     my @uriparts=split(/\//,$uri);
                   5174:     my $filename=pop(@uriparts);
                   5175:     my $pathname=join('/',@uriparts);
                   5176:     return ($pathname,$filename);
                   5177: }
1.232     www      5178: # --------------------------------------------------- Is a resource on the map?
                   5179: 
                   5180: sub is_on_map {
1.710     albertel 5181:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5182:     #Trying to find the conditional for the file
1.620     albertel 5183:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5184: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5185:     if ($match) {
1.289     bowersj2 5186: 	return (1,$1);
                   5187:     } else {
1.434     www      5188: 	return (0,0);
1.289     bowersj2 5189:     }
1.12      www      5190: }
                   5191: 
1.427     www      5192: # --------------------------------------------------------- Get symb from alias
                   5193: 
                   5194: sub get_symb_from_alias {
                   5195:     my $symb=shift;
                   5196:     my ($map,$resid,$url)=&decode_symb($symb);
                   5197: # Already is a symb
                   5198:     if ($url) { return $symb; }
                   5199: # Must be an alias
                   5200:     my $aliassymb='';
                   5201:     my %bighash;
1.620     albertel 5202:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5203:                             &GDBM_READER(),0640)) {
                   5204:         my $rid=$bighash{'mapalias_'.$symb};
                   5205: 	if ($rid) {
                   5206: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5207: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5208: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5209: 	}
                   5210:         untie %bighash;
                   5211:     }
                   5212:     return $aliassymb;
                   5213: }
                   5214: 
1.12      www      5215: # ----------------------------------------------------------------- Define Role
                   5216: 
                   5217: sub definerole {
                   5218:   if (allowed('mcr','/')) {
                   5219:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5220:     foreach my $role (split(':',$sysrole)) {
                   5221: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5222:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5223:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5224: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5225:                return "refused:s:$crole&$cqual"; 
                   5226:             }
                   5227:         }
1.191     harris41 5228:     }
1.800     albertel 5229:     foreach my $role (split(':',$domrole)) {
                   5230: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5231:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5232:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5233: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5234:                return "refused:d:$crole&$cqual"; 
                   5235:             }
                   5236:         }
1.191     harris41 5237:     }
1.800     albertel 5238:     foreach my $role (split(':',$courole)) {
                   5239: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5240:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5241:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5242: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5243:                return "refused:c:$crole&$cqual"; 
                   5244:             }
                   5245:         }
1.191     harris41 5246:     }
1.620     albertel 5247:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5248:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5249: 	        "rolesdef_$rolename=".
                   5250:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5251:     return reply($command,$env{'user.home'});
1.12      www      5252:   } else {
                   5253:     return 'refused';
                   5254:   }
1.105     harris41 5255: }
                   5256: 
                   5257: # ---------------- Make a metadata query against the network of library servers
                   5258: 
                   5259: sub metadata_query {
1.244     matthew  5260:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5261:     my %rhash;
1.845     albertel 5262:     my %libserv = &all_library();
1.244     matthew  5263:     my @server_list = (defined($server_array) ? @$server_array
                   5264:                                               : keys(%libserv) );
                   5265:     for my $server (@server_list) {
1.118     harris41 5266: 	unless ($custom or $customshow) {
                   5267: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5268: 	    $rhash{$server}=$reply;
                   5269: 	}
                   5270: 	else {
                   5271: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5272: 			     &escape($custom).':'.&escape($customshow),
                   5273: 			     $server);
                   5274: 	    $rhash{$server}=$reply;
                   5275: 	}
1.112     harris41 5276:     }
1.118     harris41 5277:     return \%rhash;
1.240     www      5278: }
                   5279: 
                   5280: # ----------------------------------------- Send log queries and wait for reply
                   5281: 
                   5282: sub log_query {
                   5283:     my ($uname,$udom,$query,%filters)=@_;
                   5284:     my $uhome=&homeserver($uname,$udom);
                   5285:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5286:     my $uhost=&hostname($uhome);
1.800     albertel 5287:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5288:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5289:                        $uhome);
1.479     albertel 5290:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5291:     return get_query_reply($queryid);
                   5292: }
                   5293: 
1.818     raeburn  5294: # -------------------------- Update MySQL table for portfolio file
                   5295: 
                   5296: sub update_portfolio_table {
1.821     raeburn  5297:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5298:     if ($group ne '') {
                   5299:         $file_name =~s /^\Q$group\E//;
                   5300:     }
1.818     raeburn  5301:     my $homeserver = &homeserver($uname,$udom);
                   5302:     my $queryid=
1.821     raeburn  5303:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5304:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5305:     my $reply = &get_query_reply($queryid);
                   5306:     return $reply;
                   5307: }
                   5308: 
1.899     raeburn  5309: # -------------------------- Update MySQL allusers table
                   5310: 
                   5311: sub update_allusers_table {
                   5312:     my ($uname,$udom,$names) = @_;
                   5313:     my $homeserver = &homeserver($uname,$udom);
                   5314:     my $queryid=
                   5315:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5316:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5317:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5318:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5319:                'generation='.&escape($names->{'generation'}).'%%'.
                   5320:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5321:                'id='.&escape($names->{'id'}),$homeserver);
                   5322:     my $reply = &get_query_reply($queryid);
                   5323:     return $reply;
                   5324: }
                   5325: 
1.508     raeburn  5326: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5327: 
                   5328: sub fetch_enrollment_query {
1.511     raeburn  5329:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5330:     my $homeserver;
1.547     raeburn  5331:     my $maxtries = 1;
1.508     raeburn  5332:     if ($context eq 'automated') {
                   5333:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5334:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5335:     } else {
                   5336:         $homeserver = &homeserver($cnum,$dom);
                   5337:     }
1.838     albertel 5338:     my $host=&hostname($homeserver);
1.506     raeburn  5339:     my $cmd = '';
1.1000    raeburn  5340:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 5341:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5342:     }
                   5343:     $cmd =~ s/%%$//;
                   5344:     $cmd = &escape($cmd);
                   5345:     my $query = 'fetchenrollment';
1.620     albertel 5346:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5347:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5348:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5349:         return 'error: '.$queryid;
                   5350:     }
1.506     raeburn  5351:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5352:     my $tries = 1;
                   5353:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5354:         $reply = &get_query_reply($queryid);
                   5355:         $tries ++;
                   5356:     }
1.526     raeburn  5357:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5358:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5359:     } else {
1.901     albertel 5360:         my @responses = split(/:/,$reply);
1.515     raeburn  5361:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5362:             foreach my $line (@responses) {
                   5363:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5364:                 $$replyref{$key} = $value;
                   5365:             }
                   5366:         } else {
1.506     raeburn  5367:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5368:             foreach my $line (@responses) {
                   5369:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5370:                 $$replyref{$key} = $value;
                   5371:                 if ($value > 0) {
1.800     albertel 5372:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5373:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5374:                         my $destname = $pathname.'/'.$filename;
                   5375:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5376:                         if ($xml_classlist =~ /^error/) {
                   5377:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5378:                         } else {
1.506     raeburn  5379:                             if ( open(FILE,">$destname") ) {
                   5380:                                 print FILE &unescape($xml_classlist);
                   5381:                                 close(FILE);
1.526     raeburn  5382:                             } else {
                   5383:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5384:                             }
                   5385:                         }
                   5386:                     }
                   5387:                 }
                   5388:             }
                   5389:         }
                   5390:         return 'ok';
                   5391:     }
                   5392:     return 'error';
                   5393: }
                   5394: 
1.242     www      5395: sub get_query_reply {
                   5396:     my $queryid=shift;
1.240     www      5397:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5398:     my $reply='';
                   5399:     for (1..100) {
                   5400: 	sleep 2;
                   5401:         if (-e $replyfile.'.end') {
1.448     albertel 5402: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5403: 		$reply = join('',<$fh>);
                   5404: 		close($fh);
1.240     www      5405: 	   } else { return 'error: reply_file_error'; }
1.242     www      5406:            return &unescape($reply);
                   5407: 	}
1.240     www      5408:     }
1.242     www      5409:     return 'timeout:'.$queryid;
1.240     www      5410: }
                   5411: 
                   5412: sub courselog_query {
1.241     www      5413: #
                   5414: # possible filters:
                   5415: # url: url or symb
                   5416: # username
                   5417: # domain
                   5418: # action: view, submit, grade
                   5419: # start: timestamp
                   5420: # end: timestamp
                   5421: #
1.240     www      5422:     my (%filters)=@_;
1.620     albertel 5423:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5424:     if ($filters{'url'}) {
                   5425: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5426:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5427:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5428:     }
1.620     albertel 5429:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5430:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5431:     return &log_query($cname,$cdom,'courselog',%filters);
                   5432: }
                   5433: 
                   5434: sub userlog_query {
1.858     raeburn  5435: #
                   5436: # possible filters:
                   5437: # action: log check role
                   5438: # start: timestamp
                   5439: # end: timestamp
                   5440: #
1.240     www      5441:     my ($uname,$udom,%filters)=@_;
                   5442:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5443: }
                   5444: 
1.506     raeburn  5445: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5446: 
                   5447: sub auto_run {
1.508     raeburn  5448:     my ($cnum,$cdom) = @_;
1.876     raeburn  5449:     my $response = 0;
                   5450:     my $settings;
                   5451:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5452:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5453:         $settings = $domconfig{'autoenroll'};
                   5454:         if ($settings->{'run'} eq '1') {
                   5455:             $response = 1;
                   5456:         }
                   5457:     } else {
1.934     raeburn  5458:         my $homeserver;
                   5459:         if (&is_course($cdom,$cnum)) {
                   5460:             $homeserver = &homeserver($cnum,$cdom);
                   5461:         } else {
                   5462:             $homeserver = &domain($cdom,'primary');
                   5463:         }
                   5464:         if ($homeserver ne 'no_host') {
                   5465:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5466:         }
1.876     raeburn  5467:     }
1.506     raeburn  5468:     return $response;
                   5469: }
1.776     albertel 5470: 
1.506     raeburn  5471: sub auto_get_sections {
1.508     raeburn  5472:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   5473:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  5474:     my @secs = ();
1.511     raeburn  5475:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  5476:     unless ($response eq 'refused') {
1.901     albertel 5477:         @secs = split(/:/,$response);
1.506     raeburn  5478:     }
                   5479:     return @secs;
                   5480: }
1.776     albertel 5481: 
1.506     raeburn  5482: sub auto_new_course {
1.508     raeburn  5483:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5484:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5485:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5486:     return $response;
                   5487: }
1.776     albertel 5488: 
1.506     raeburn  5489: sub auto_validate_courseID {
1.508     raeburn  5490:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5491:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5492:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5493:     return $response;
                   5494: }
1.776     albertel 5495: 
1.506     raeburn  5496: sub auto_create_password {
1.873     raeburn  5497:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5498:     my ($homeserver,$response);
1.506     raeburn  5499:     my $create_passwd = 0;
                   5500:     my $authchk = '';
1.873     raeburn  5501:     if ($udom =~ /^$match_domain$/) {
                   5502:         $homeserver = &domain($udom,'primary');
                   5503:     }
                   5504:     if ($homeserver eq '') {
                   5505:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5506:             $homeserver = &homeserver($cnum,$cdom);
                   5507:         }
                   5508:     }
                   5509:     if ($homeserver eq '') {
                   5510:         $authchk = 'nodomain';
1.506     raeburn  5511:     } else {
1.873     raeburn  5512:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5513:         if ($response eq 'refused') {
                   5514:             $authchk = 'refused';
                   5515:         } else {
1.901     albertel 5516:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5517:         }
1.506     raeburn  5518:     }
                   5519:     return ($authparam,$create_passwd,$authchk);
                   5520: }
                   5521: 
1.706     raeburn  5522: sub auto_photo_permission {
                   5523:     my ($cnum,$cdom,$students) = @_;
                   5524:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5525:     my ($outcome,$perm_reqd,$conditions) = 
                   5526: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5527:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5528: 	return (undef,undef);
                   5529:     }
1.706     raeburn  5530:     return ($outcome,$perm_reqd,$conditions);
                   5531: }
                   5532: 
                   5533: sub auto_checkphotos {
                   5534:     my ($uname,$udom,$pid) = @_;
                   5535:     my $homeserver = &homeserver($uname,$udom);
                   5536:     my ($result,$resulttype);
                   5537:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5538: 				   &escape($uname).':'.&escape($pid),
                   5539: 				   $homeserver));
1.709     albertel 5540:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5541: 	return (undef,undef);
                   5542:     }
1.706     raeburn  5543:     if ($outcome) {
                   5544:         ($result,$resulttype) = split(/:/,$outcome);
                   5545:     } 
                   5546:     return ($result,$resulttype);
                   5547: }
                   5548: 
                   5549: sub auto_photochoice {
                   5550:     my ($cnum,$cdom) = @_;
                   5551:     my $homeserver = &homeserver($cnum,$cdom);
                   5552:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5553: 						       &escape($cdom),
                   5554: 						       $homeserver)));
1.709     albertel 5555:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5556: 	return (undef,undef);
                   5557:     }
1.706     raeburn  5558:     return ($update,$comment);
                   5559: }
                   5560: 
                   5561: sub auto_photoupdate {
                   5562:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5563:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5564:     my $host=&hostname($homeserver);
1.706     raeburn  5565:     my $cmd = '';
                   5566:     my $maxtries = 1;
1.800     albertel 5567:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5568:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5569:     }
                   5570:     $cmd =~ s/%%$//;
                   5571:     $cmd = &escape($cmd);
                   5572:     my $query = 'institutionalphotos';
                   5573:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5574:     unless ($queryid=~/^\Q$host\E\_/) {
                   5575:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5576:         return 'error: '.$queryid;
                   5577:     }
                   5578:     my $reply = &get_query_reply($queryid);
                   5579:     my $tries = 1;
                   5580:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5581:         $reply = &get_query_reply($queryid);
                   5582:         $tries ++;
                   5583:     }
                   5584:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5585:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5586:     } else {
                   5587:         my @responses = split(/:/,$reply);
                   5588:         my $outcome = shift(@responses); 
                   5589:         foreach my $item (@responses) {
                   5590:             my ($key,$value) = split(/=/,$item);
                   5591:             $$photo{$key} = $value;
                   5592:         }
                   5593:         return $outcome;
                   5594:     }
                   5595:     return 'error';
                   5596: }
                   5597: 
1.521     raeburn  5598: sub auto_instcode_format {
1.793     albertel 5599:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5600: 	$cat_order) = @_;
1.521     raeburn  5601:     my $courses = '';
1.772     raeburn  5602:     my @homeservers;
1.521     raeburn  5603:     if ($caller eq 'global') {
1.841     albertel 5604: 	my %servers = &get_servers($codedom,'library');
                   5605: 	foreach my $tryserver (keys(%servers)) {
                   5606: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5607: 		push(@homeservers,$tryserver);
                   5608: 	    }
1.584     raeburn  5609:         }
1.521     raeburn  5610:     } else {
1.772     raeburn  5611:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5612:     }
1.793     albertel 5613:     foreach my $code (keys(%{$instcodes})) {
                   5614:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5615:     }
                   5616:     chop($courses);
1.772     raeburn  5617:     my $ok_response = 0;
                   5618:     my $response;
                   5619:     while (@homeservers > 0 && $ok_response == 0) {
                   5620:         my $server = shift(@homeservers); 
                   5621:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5622:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5623:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5624: 		split(/:/,$response);
1.772     raeburn  5625:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5626:             push(@{$codetitles},&str2array($codetitles_str));
                   5627:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5628:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5629:             $ok_response = 1;
                   5630:         }
                   5631:     }
                   5632:     if ($ok_response) {
1.521     raeburn  5633:         return 'ok';
1.772     raeburn  5634:     } else {
                   5635:         return $response;
1.521     raeburn  5636:     }
                   5637: }
                   5638: 
1.792     raeburn  5639: sub auto_instcode_defaults {
                   5640:     my ($domain,$returnhash,$code_order) = @_;
                   5641:     my @homeservers;
1.841     albertel 5642: 
                   5643:     my %servers = &get_servers($domain,'library');
                   5644:     foreach my $tryserver (keys(%servers)) {
                   5645: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5646: 	    push(@homeservers,$tryserver);
                   5647: 	}
1.792     raeburn  5648:     }
1.841     albertel 5649: 
1.792     raeburn  5650:     my $response;
1.841     albertel 5651:     foreach my $server (@homeservers) {
1.792     raeburn  5652:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5653:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5654: 	
                   5655: 	foreach my $pair (split(/\&/,$response)) {
                   5656: 	    my ($name,$value)=split(/\=/,$pair);
                   5657: 	    if ($name eq 'code_order') {
                   5658: 		@{$code_order} = split(/\&/,&unescape($value));
                   5659: 	    } else {
                   5660: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5661: 	    }
                   5662: 	}
                   5663: 	return 'ok';
1.792     raeburn  5664:     }
1.841     albertel 5665: 
                   5666:     return $response;
1.792     raeburn  5667: } 
                   5668: 
1.777     albertel 5669: sub auto_validate_class_sec {
1.918     raeburn  5670:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5671:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5672:     my $ownerlist;
                   5673:     if (ref($owners) eq 'ARRAY') {
                   5674:         $ownerlist = join(',',@{$owners});
                   5675:     } else {
                   5676:         $ownerlist = $owners;
                   5677:     }
1.773     raeburn  5678:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5679:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5680:     return $response;
                   5681: }
                   5682: 
1.679     raeburn  5683: # ------------------------------------------------------- Course Group routines
                   5684: 
                   5685: sub get_coursegroups {
1.809     raeburn  5686:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5687:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5688: }
                   5689: 
1.679     raeburn  5690: sub modify_coursegroup {
                   5691:     my ($cdom,$cnum,$groupsettings) = @_;
                   5692:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5693: }
                   5694: 
1.809     raeburn  5695: sub toggle_coursegroup_status {
                   5696:     my ($cdom,$cnum,$group,$action) = @_;
                   5697:     my ($from_namespace,$to_namespace);
                   5698:     if ($action eq 'delete') {
                   5699:         $from_namespace = 'coursegroups';
                   5700:         $to_namespace = 'deleted_groups';
                   5701:     } else {
                   5702:         $from_namespace = 'deleted_groups';
                   5703:         $to_namespace = 'coursegroups';
                   5704:     }
                   5705:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5706:     if (my $tmp = &error(%curr_group)) {
                   5707:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5708:         return ('read error',$tmp);
                   5709:     } else {
                   5710:         my %savedsettings = %curr_group; 
1.809     raeburn  5711:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5712:         my $deloutcome;
                   5713:         if ($result eq 'ok') {
1.809     raeburn  5714:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5715:         } else {
                   5716:             return ('write error',$result);
                   5717:         }
                   5718:         if ($deloutcome eq 'ok') {
                   5719:             return 'ok';
                   5720:         } else {
                   5721:             return ('delete error',$deloutcome);
                   5722:         }
                   5723:     }
                   5724: }
                   5725: 
1.679     raeburn  5726: sub modify_group_roles {
1.957     raeburn  5727:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  5728:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5729:     my $role = 'gr/'.&escape($userprivs);
                   5730:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  5731:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  5732:     if ($result eq 'ok') {
                   5733:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5734:     }
1.679     raeburn  5735:     return $result;
                   5736: }
                   5737: 
                   5738: sub modify_coursegroup_membership {
                   5739:     my ($cdom,$cnum,$membership) = @_;
                   5740:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5741:     return $result;
                   5742: }
                   5743: 
1.682     raeburn  5744: sub get_active_groups {
                   5745:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5746:     my $now = time;
                   5747:     my %groups = ();
                   5748:     foreach my $key (keys(%env)) {
1.811     albertel 5749:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5750:             my ($start,$end) = split(/\./,$env{$key});
                   5751:             if (($end!=0) && ($end<$now)) { next; }
                   5752:             if (($start!=0) && ($start>$now)) { next; }
                   5753:             if ($1 eq $cdom && $2 eq $cnum) {
                   5754:                 $groups{$3} = $env{$key} ;
                   5755:             }
                   5756:         }
                   5757:     }
                   5758:     return %groups;
                   5759: }
                   5760: 
1.683     raeburn  5761: sub get_group_membership {
                   5762:     my ($cdom,$cnum,$group) = @_;
                   5763:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5764: }
                   5765: 
                   5766: sub get_users_groups {
                   5767:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5768:     my @usersgroups;
1.683     raeburn  5769:     my $cachetime=1800;
                   5770: 
                   5771:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5772:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5773:     if (defined($cached)) {
1.734     albertel 5774:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5775:     } else {  
                   5776:         $grouplist = '';
1.816     raeburn  5777:         my $courseurl = &courseid_to_courseurl($courseid);
                   5778:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5779:         my $access_end = $env{'course.'.$courseid.
                   5780:                               '.default_enrollment_end_date'};
                   5781:         my $now = time;
                   5782:         foreach my $key (keys(%roleshash)) {
                   5783:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5784:                 my $group = $1;
                   5785:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5786:                     my $start = $2;
                   5787:                     my $end = $1;
                   5788:                     if ($start == -1) { next; } # deleted from group
                   5789:                     if (($start!=0) && ($start>$now)) { next; }
                   5790:                     if (($end!=0) && ($end<$now)) {
                   5791:                         if ($access_end && $access_end < $now) {
                   5792:                             if ($access_end - $end < 86400) {
                   5793:                                 push(@usersgroups,$group);
1.733     raeburn  5794:                             }
                   5795:                         }
1.817     raeburn  5796:                         next;
1.733     raeburn  5797:                     }
1.817     raeburn  5798:                     push(@usersgroups,$group);
1.683     raeburn  5799:                 }
                   5800:             }
                   5801:         }
1.817     raeburn  5802:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5803:         $grouplist = join(':',@usersgroups);
                   5804:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5805:     }
1.733     raeburn  5806:     return @usersgroups;
1.683     raeburn  5807: }
                   5808: 
                   5809: sub devalidate_getgroups_cache {
                   5810:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5811:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5812: 
1.683     raeburn  5813:     my $hashid="$udom:$uname:$courseid";
                   5814:     &devalidate_cache_new('getgroups',$hashid);
                   5815: }
                   5816: 
1.12      www      5817: # ------------------------------------------------------------------ Plain Text
                   5818: 
                   5819: sub plaintext {
1.988     raeburn  5820:     my ($short,$type,$cid,$forcedefault) = @_;
1.758     albertel 5821:     if ($short =~ /^cr/) {
                   5822: 	return (split('/',$short))[-1];
                   5823:     }
1.742     raeburn  5824:     if (!defined($cid)) {
                   5825:         $cid = $env{'request.course.id'};
                   5826:     }
1.988     raeburn  5827:     if (defined($cid) && ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '')) {
                   5828:         unless ($forcedefault) {
                   5829:             my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   5830:             &Apache::lonlocal::mt_escape(\$roletext);
                   5831:             return &Apache::lonlocal::mt($roletext);
                   5832:         }
1.742     raeburn  5833:     }
                   5834:     my %rolenames = (
                   5835:                       Course => 'std',
                   5836:                       Group => 'alt1',
                   5837:                     );
                   5838:     if (defined($type) && 
                   5839:          defined($rolenames{$type}) && 
                   5840:          defined($prp{$short}{$rolenames{$type}})) {
                   5841:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5842:     } else {
                   5843:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5844:     }
1.12      www      5845: }
                   5846: 
                   5847: # ----------------------------------------------------------------- Assign Role
                   5848: 
                   5849: sub assignrole {
1.957     raeburn  5850:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   5851:         $context)=@_;
1.21      www      5852:     my $mrole;
                   5853:     if ($role =~ /^cr\//) {
1.393     www      5854:         my $cwosec=$url;
1.811     albertel 5855:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5856: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5857:            &logthis('Refused custom assignrole: '.
                   5858:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5859: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5860:            return 'refused'; 
                   5861:         }
1.21      www      5862:         $mrole='cr';
1.678     raeburn  5863:     } elsif ($role =~ /^gr\//) {
                   5864:         my $cwogrp=$url;
1.811     albertel 5865:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5866:         unless (&allowed('mdg',$cwogrp)) {
                   5867:             &logthis('Refused group assignrole: '.
                   5868:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5869:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5870:             return 'refused';
                   5871:         }
                   5872:         $mrole='gr';
1.21      www      5873:     } else {
1.82      www      5874:         my $cwosec=$url;
1.811     albertel 5875:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5876:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5877:             my $refused;
                   5878:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5879:                 if (!(&allowed('c'.$role,$url))) {
                   5880:                     $refused = 1;
                   5881:                 }
                   5882:             } else {
                   5883:                 $refused = 1;
                   5884:             }
1.947     raeburn  5885:             if ($refused) {
                   5886:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5887:                     $refused = '';
                   5888:                 } else {
                   5889:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   5890:                              ' '.$role.' '.$end.' '.$start.' by '.
                   5891: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   5892:                     return 'refused';
                   5893:                 }
1.932     raeburn  5894:             }
1.104     www      5895:         }
1.21      www      5896:         $mrole=$role;
                   5897:     }
1.620     albertel 5898:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5899:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5900:     if ($end) { $command.='_'.$end; }
1.21      www      5901:     if ($start) {
                   5902: 	if ($end) { 
1.81      www      5903:            $command.='_'.$start; 
1.21      www      5904:         } else {
1.81      www      5905:            $command.='_0_'.$start;
1.21      www      5906:         }
                   5907:     }
1.739     raeburn  5908:     my $origstart = $start;
                   5909:     my $origend = $end;
1.957     raeburn  5910:     my $delflag;
1.357     www      5911: # actually delete
                   5912:     if ($deleteflag) {
1.373     www      5913: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5914: # modify command to delete the role
1.620     albertel 5915:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5916:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5917: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5918: # set start and finish to negative values for userrolelog
                   5919:            $start=-1;
                   5920:            $end=-1;
1.957     raeburn  5921:            $delflag = 1;
1.357     www      5922:         }
                   5923:     }
                   5924: # send command
1.349     www      5925:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5926: # log new user role if status is ok
1.349     www      5927:     if ($answer eq 'ok') {
1.663     raeburn  5928: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5929: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  5930:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  5931:         unless ($role =~ /^gr/) {
                   5932:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  5933:                                              $origstart,$selfenroll,$context);
1.739     raeburn  5934:         }
1.349     www      5935:     }
                   5936:     return $answer;
1.169     harris41 5937: }
                   5938: 
                   5939: # -------------------------------------------------- Modify user authentication
1.197     www      5940: # Overrides without validation
                   5941: 
1.169     harris41 5942: sub modifyuserauth {
                   5943:     my ($udom,$uname,$umode,$upass)=@_;
                   5944:     my $uhome=&homeserver($uname,$udom);
1.197     www      5945:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5946:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5947:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5948:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5949:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5950: 		     &escape($upass),$uhome);
1.620     albertel 5951:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5952:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5953:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5954:     &log($udom,,$uname,$uhome,
1.620     albertel 5955:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5956:                                      $env{'user.name'}.', '.$umode.
1.197     www      5957:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5958:     unless ($reply eq 'ok') {
1.197     www      5959:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5960: 	return 'error: '.$reply;
                   5961:     }   
1.170     harris41 5962:     return 'ok';
1.80      www      5963: }
                   5964: 
1.81      www      5965: # --------------------------------------------------------------- Modify a user
1.80      www      5966: 
1.81      www      5967: sub modifyuser {
1.206     matthew  5968:     my ($udom,    $uname, $uid,
                   5969:         $umode,   $upass, $first,
                   5970:         $middle,  $last,  $gene,
1.963     raeburn  5971:         $forceid, $desiredhome, $email, $inststatus)=@_;
1.807     albertel 5972:     $udom= &LONCAPA::clean_domain($udom);
                   5973:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5974:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5975:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5976: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5977:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5978:                                      ' desiredhome not specified'). 
1.620     albertel 5979:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5980:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5981:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5982: # ----------------------------------------------------------------- Create User
1.406     albertel 5983:     if (($uhome eq 'no_host') && 
                   5984: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5985:         my $unhome='';
1.844     albertel 5986:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5987:             $unhome = $desiredhome;
1.620     albertel 5988: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5989: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5990:         } else { # load balancing routine for determining $unhome
1.81      www      5991:             my $loadm=10000000;
1.841     albertel 5992: 	    my %servers = &get_servers($udom,'library');
                   5993: 	    foreach my $tryserver (keys(%servers)) {
                   5994: 		my $answer=reply('load',$tryserver);
                   5995: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5996: 		    $loadm=$answer;
                   5997: 		    $unhome=$tryserver;
                   5998: 		}
1.80      www      5999: 	    }
                   6000:         }
                   6001:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  6002: 	    return 'error: unable to find a home server for '.$uname.
                   6003:                    ' in domain '.$udom;
1.80      www      6004:         }
                   6005:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   6006:                          &escape($upass),$unhome);
                   6007: 	unless ($reply eq 'ok') {
                   6008:             return 'error: '.$reply;
                   6009:         }   
1.230     stredwic 6010:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      6011:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  6012: 	    return 'error: unable verify users home machine.';
1.80      www      6013:         }
1.209     matthew  6014:     }   # End of creation of new user
1.80      www      6015: # ---------------------------------------------------------------------- Add ID
                   6016:     if ($uid) {
                   6017:        $uid=~tr/A-Z/a-z/;
                   6018:        my %uidhash=&idrget($udom,$uname);
1.196     www      6019:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   6020:          && (!$forceid)) {
1.80      www      6021: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  6022: 	      return 'error: user id "'.$uid.'" does not match '.
                   6023:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      6024:           }
                   6025:        } else {
                   6026: 	  &idput($udom,($uname => $uid));
                   6027:        }
                   6028:     }
                   6029: # -------------------------------------------------------------- Add names, etc
1.313     matthew  6030:     my @tmp=&get('environment',
1.899     raeburn  6031: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  6032:                     'permanentemail','inststatus'],
1.134     albertel 6033: 		   $udom,$uname);
1.313     matthew  6034:     my %names;
                   6035:     if ($tmp[0] =~ m/^error:.*/) { 
                   6036:         %names=(); 
                   6037:     } else {
                   6038:         %names = @tmp;
                   6039:     }
1.388     www      6040: #
                   6041: # Make sure to not trash student environment if instructor does not bother
                   6042: # to supply name and email information
                   6043: #
                   6044:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  6045:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      6046:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  6047:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      6048:     if ($email) {
                   6049:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  6050:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      6051:     }
1.899     raeburn  6052:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  6053:     if (defined($inststatus)) {
                   6054:         $names{'inststatus'} = '';
                   6055:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   6056:         if (ref($usertypes) eq 'HASH') {
                   6057:             my @okstatuses; 
                   6058:             foreach my $item (split(/:/,$inststatus)) {
                   6059:                 if (defined($usertypes->{$item})) {
                   6060:                     push(@okstatuses,$item);  
                   6061:                 }
                   6062:             }
                   6063:             if (@okstatuses) {
                   6064:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   6065:             }
                   6066:         }
                   6067:     }
1.134     albertel 6068:     my $reply = &put('environment', \%names, $udom,$uname);
                   6069:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  6070:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      6071:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963     raeburn  6072:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
                   6073:                  $umode.', '.$first.', '.$middle.', '.
                   6074: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
                   6075:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   6076:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   6077:     } else {
                   6078:         $logmsg .= ' during self creation';
                   6079:     }
                   6080:     &logthis($logmsg);
1.134     albertel 6081:     return 'ok';
1.80      www      6082: }
                   6083: 
1.81      www      6084: # -------------------------------------------------------------- Modify student
1.80      www      6085: 
1.81      www      6086: sub modifystudent {
                   6087:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  6088:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  6089:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 6090:     if (!$cid) {
1.620     albertel 6091: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6092: 	    return 'not_in_class';
                   6093: 	}
1.80      www      6094:     }
                   6095: # --------------------------------------------------------------- Make the user
1.81      www      6096:     my $reply=&modifyuser
1.209     matthew  6097: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  6098:          $desiredhome,$email,$inststatus);
1.80      www      6099:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  6100:     # This will cause &modify_student_enrollment to get the uid from the
                   6101:     # students environment
                   6102:     $uid = undef if (!$forceid);
1.455     albertel 6103:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  6104: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  6105:     return $reply;
                   6106: }
                   6107: 
                   6108: sub modify_student_enrollment {
1.957     raeburn  6109:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 6110:     my ($cdom,$cnum,$chome);
                   6111:     if (!$cid) {
1.620     albertel 6112: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6113: 	    return 'not_in_class';
                   6114: 	}
1.620     albertel 6115: 	$cdom=$env{'course.'.$cid.'.domain'};
                   6116: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 6117:     } else {
                   6118: 	($cdom,$cnum)=split(/_/,$cid);
                   6119:     }
1.620     albertel 6120:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 6121:     if (!$chome) {
1.457     raeburn  6122: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  6123:     }
1.455     albertel 6124:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  6125:     # Make sure the user exists
1.81      www      6126:     my $uhome=&homeserver($uname,$udom);
                   6127:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6128: 	return 'error: no such user';
                   6129:     }
1.297     matthew  6130:     # Get student data if we were not given enough information
                   6131:     if (!defined($first)  || $first  eq '' || 
                   6132:         !defined($last)   || $last   eq '' || 
                   6133:         !defined($uid)    || $uid    eq '' || 
                   6134:         !defined($middle) || $middle eq '' || 
                   6135:         !defined($gene)   || $gene   eq '') {
1.294     matthew  6136:         # They did not supply us with enough data to enroll the student, so
                   6137:         # we need to pick up more information.
1.297     matthew  6138:         my %tmp = &get('environment',
1.294     matthew  6139:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  6140:                        ,$udom,$uname);
                   6141: 
1.800     albertel 6142:         #foreach my $key (keys(%tmp)) {
                   6143:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 6144:         #}
1.294     matthew  6145:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   6146:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   6147:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  6148:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  6149:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   6150:     }
1.556     albertel 6151:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 6152:     my $reply=cput('classlist',
                   6153: 		   {"$uname:$udom" => 
1.515     raeburn  6154: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 6155: 		   $cdom,$cnum);
1.81      www      6156:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   6157: 	return 'error: '.$reply;
1.652     albertel 6158:     } else {
                   6159: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      6160:     }
1.297     matthew  6161:     # Add student role to user
1.83      www      6162:     my $uurl='/'.$cid;
1.81      www      6163:     $uurl=~s/\_/\//g;
                   6164:     if ($usec) {
                   6165: 	$uurl.='/'.$usec;
                   6166:     }
1.957     raeburn  6167:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      6168: }
                   6169: 
1.556     albertel 6170: sub format_name {
                   6171:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   6172:     my $name;
                   6173:     if ($first ne 'lastname') {
                   6174: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   6175:     } else {
                   6176: 	if ($lastname=~/\S/) {
                   6177: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   6178: 	    $name=~s/\s+,/,/;
                   6179: 	} else {
                   6180: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   6181: 	}
                   6182:     }
                   6183:     $name=~s/^\s+//;
                   6184:     $name=~s/\s+$//;
                   6185:     $name=~s/\s+/ /g;
                   6186:     return $name;
                   6187: }
                   6188: 
1.84      www      6189: # ------------------------------------------------- Write to course preferences
                   6190: 
                   6191: sub writecoursepref {
                   6192:     my ($courseid,%prefs)=@_;
                   6193:     $courseid=~s/^\///;
                   6194:     $courseid=~s/\_/\//g;
                   6195:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   6196:     my $chome=homeserver($cnum,$cdomain);
                   6197:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   6198: 	return 'error: no such course';
                   6199:     }
                   6200:     my $cstring='';
1.800     albertel 6201:     foreach my $pref (keys(%prefs)) {
                   6202: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 6203:     }
1.84      www      6204:     $cstring=~s/\&$//;
                   6205:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   6206: }
                   6207: 
                   6208: # ---------------------------------------------------------- Make/modify course
                   6209: 
                   6210: sub createcourse {
1.741     raeburn  6211:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   6212:         $course_owner,$crstype)=@_;
1.84      www      6213:     $url=&declutter($url);
                   6214:     my $cid='';
1.264     matthew  6215:     unless (&allowed('ccc',$udom)) {
1.84      www      6216:         return 'refused';
                   6217:     }
                   6218: # ------------------------------------------------------------------- Create ID
1.674     www      6219:    my $uname=int(1+rand(9)).
                   6220:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   6221:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      6222:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   6223: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 6224:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      6225:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6226:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   6227:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 6228:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      6229:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6230:            return 'error: unable to generate unique course-ID';
                   6231:        } 
                   6232:    }
1.264     matthew  6233: # ------------------------------------------------ Check supplied server name
1.620     albertel 6234:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 6235:     if (! &is_library($course_server)) {
1.264     matthew  6236:         return 'error:bad server name '.$course_server;
                   6237:     }
1.84      www      6238: # ------------------------------------------------------------- Make the course
                   6239:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  6240:                       $course_server);
1.84      www      6241:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 6242:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      6243:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6244: 	return 'error: no such course';
                   6245:     }
1.271     www      6246: # ----------------------------------------------------------------- Course made
1.516     raeburn  6247: # log existence
1.918     raeburn  6248:     my $newcourse = {
                   6249:                     $udom.'_'.$uname => {
1.921     raeburn  6250:                                      description => $description,
                   6251:                                      inst_code   => $inst_code,
                   6252:                                      owner       => $course_owner,
                   6253:                                      type        => $crstype,
1.918     raeburn  6254:                                                 },
                   6255:                     };
1.921     raeburn  6256:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      6257: # set toplevel url
1.271     www      6258:     my $topurl=$url;
                   6259:     unless ($nonstandard) {
                   6260: # ------------------------------------------ For standard courses, make top url
                   6261:         my $mapurl=&clutter($url);
1.278     www      6262:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 6263:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      6264: <map>
                   6265: <resource id="1" type="start"></resource>
                   6266: <resource id="2" src="$mapurl"></resource>
                   6267: <resource id="3" type="finish"></resource>
                   6268: <link index="1" from="1" to="2"></link>
                   6269: <link index="2" from="2" to="3"></link>
                   6270: </map>
                   6271: ENDINITMAP
                   6272:         $topurl=&declutter(
1.638     albertel 6273:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      6274:                           );
                   6275:     }
                   6276: # ----------------------------------------------------------- Write preferences
1.84      www      6277:     &writecoursepref($udom.'_'.$uname,
                   6278:                      ('description' => $description,
1.271     www      6279:                       'url'         => $topurl));
1.84      www      6280:     return '/'.$udom.'/'.$uname;
                   6281: }
                   6282: 
1.813     albertel 6283: sub is_course {
                   6284:     my ($cdom,$cnum) = @_;
                   6285:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  6286: 				undef,'.');
1.813     albertel 6287:     if (exists($courses{$cdom.'_'.$cnum})) {
                   6288:         return 1;
                   6289:     }
                   6290:     return 0;
                   6291: }
                   6292: 
1.21      www      6293: # ---------------------------------------------------------- Assign Custom Role
                   6294: 
                   6295: sub assigncustomrole {
1.957     raeburn  6296:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6297:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  6298:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      6299: }
                   6300: 
                   6301: # ----------------------------------------------------------------- Revoke Role
                   6302: 
                   6303: sub revokerole {
1.957     raeburn  6304:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6305:     my $now=time;
1.965     raeburn  6306:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      6307: }
                   6308: 
                   6309: # ---------------------------------------------------------- Revoke Custom Role
                   6310: 
                   6311: sub revokecustomrole {
1.957     raeburn  6312:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6313:     my $now=time;
1.357     www      6314:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  6315:            $deleteflag,$selfenroll,$context);
1.17      www      6316: }
                   6317: 
1.533     banghart 6318: # ------------------------------------------------------------ Disk usage
1.535     albertel 6319: sub diskusage {
1.955     raeburn  6320:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   6321:     $directorypath =~ s/\/$//;
                   6322:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   6323:                        .&escape($getpropath).':'.&escape($uname).':'
                   6324:                        .&escape($udom),homeserver($uname,$udom));
                   6325:     if ($listing eq 'unknown_cmd') {
                   6326:         if ($getpropath) {
                   6327:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   6328:         }
                   6329:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   6330:     }
1.514     albertel 6331:     return $listing;
1.512     banghart 6332: }
                   6333: 
1.566     banghart 6334: sub is_locked {
                   6335:     my ($file_name, $domain, $user) = @_;
                   6336:     my @check;
                   6337:     my $is_locked;
                   6338:     push @check, $file_name;
1.613     albertel 6339:     my %locked = &get('file_permissions',\@check,
1.620     albertel 6340: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 6341:     my ($tmp)=keys(%locked);
                   6342:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  6343:     
1.566     banghart 6344:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  6345:         $is_locked = 'false';
                   6346:         foreach my $entry (@{$locked{$file_name}}) {
                   6347:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  6348:                $is_locked = 'true';
                   6349:                last;
1.745     raeburn  6350:            }
                   6351:        }
1.566     banghart 6352:     } else {
                   6353:         $is_locked = 'false';
                   6354:     }
                   6355: }
                   6356: 
1.759     albertel 6357: sub declutter_portfile {
                   6358:     my ($file) = @_;
1.833     albertel 6359:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 6360:     return $file;
                   6361: }
                   6362: 
1.559     banghart 6363: # ------------------------------------------------------------- Mark as Read Only
                   6364: 
                   6365: sub mark_as_readonly {
                   6366:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 6367:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6368:     my ($tmp)=keys(%current_permissions);
                   6369:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 6370:     foreach my $file (@{$files}) {
1.759     albertel 6371: 	$file = &declutter_portfile($file);
1.561     banghart 6372:         push(@{$current_permissions{$file}},$what);
1.559     banghart 6373:     }
1.613     albertel 6374:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6375:     return;
                   6376: }
                   6377: 
1.572     banghart 6378: # ------------------------------------------------------------Save Selected Files
                   6379: 
                   6380: sub save_selected_files {
                   6381:     my ($user, $path, @files) = @_;
                   6382:     my $filename = $user."savedfiles";
1.573     banghart 6383:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 6384:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 6385:     foreach my $file (@files) {
1.620     albertel 6386:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 6387:     }
                   6388:     foreach my $file (@other_files) {
1.574     banghart 6389:         print (OUT $file."\n");
1.572     banghart 6390:     }
1.574     banghart 6391:     close (OUT);
1.572     banghart 6392:     return 'ok';
                   6393: }
                   6394: 
1.574     banghart 6395: sub clear_selected_files {
                   6396:     my ($user) = @_;
                   6397:     my $filename = $user."savedfiles";
                   6398:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6399:     print (OUT undef);
                   6400:     close (OUT);
                   6401:     return ("ok");    
                   6402: }
                   6403: 
1.572     banghart 6404: sub files_in_path {
                   6405:     my ($user, $path) = @_;
                   6406:     my $filename = $user."savedfiles";
                   6407:     my %return_files;
1.574     banghart 6408:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 6409:     while (my $line_in = <IN>) {
1.574     banghart 6410:         chomp ($line_in);
                   6411:         my @paths_and_file = split (m!/!, $line_in);
                   6412:         my $file_part = pop (@paths_and_file);
                   6413:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 6414:         $path_part.='/';
                   6415:         my $path_and_file = $path_part.$file_part;
                   6416:         if ($path_part eq $path) {
                   6417:             $return_files{$file_part}= 'selected';
                   6418:         }
                   6419:     }
1.574     banghart 6420:     close (IN);
                   6421:     return (\%return_files);
1.572     banghart 6422: }
                   6423: 
                   6424: # called in portfolio select mode, to show files selected NOT in current directory
                   6425: sub files_not_in_path {
                   6426:     my ($user, $path) = @_;
                   6427:     my $filename = $user."savedfiles";
                   6428:     my @return_files;
                   6429:     my $path_part;
1.800     albertel 6430:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6431:     while (my $line = <IN>) {
1.572     banghart 6432:         #ok, I know it's clunky, but I want it to work
1.800     albertel 6433:         my @paths_and_file = split(m|/|, $line);
                   6434:         my $file_part = pop(@paths_and_file);
                   6435:         chomp($file_part);
                   6436:         my $path_part = join('/', @paths_and_file);
1.572     banghart 6437:         $path_part .= '/';
                   6438:         my $path_and_file = $path_part.$file_part;
                   6439:         if ($path_part ne $path) {
1.800     albertel 6440:             push(@return_files, ($path_and_file));
1.572     banghart 6441:         }
                   6442:     }
1.800     albertel 6443:     close(OUT);
1.574     banghart 6444:     return (@return_files);
1.572     banghart 6445: }
                   6446: 
1.745     raeburn  6447: #----------------------------------------------Get portfolio file permissions
1.629     banghart 6448: 
1.745     raeburn  6449: sub get_portfile_permissions {
                   6450:     my ($domain,$user) = @_;
1.613     albertel 6451:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6452:     my ($tmp)=keys(%current_permissions);
                   6453:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6454:     return \%current_permissions;
                   6455: }
                   6456: 
                   6457: #---------------------------------------------Get portfolio file access controls
                   6458: 
1.749     raeburn  6459: sub get_access_controls {
1.745     raeburn  6460:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 6461:     my %access;
                   6462:     my $real_file = $file;
                   6463:     $file =~ s/\.meta$//;
1.745     raeburn  6464:     if (defined($file)) {
1.749     raeburn  6465:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   6466:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 6467:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  6468:             }
                   6469:         }
1.745     raeburn  6470:     } else {
1.749     raeburn  6471:         foreach my $key (keys(%{$current_permissions})) {
                   6472:             if ($key =~ /\0accesscontrol$/) {
                   6473:                 if (defined($group)) {
                   6474:                     if ($key !~ m-^\Q$group\E/-) {
                   6475:                         next;
                   6476:                     }
                   6477:                 }
                   6478:                 my ($fullpath) = split(/\0/,$key);
                   6479:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   6480:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   6481:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   6482:                     }
                   6483:                 }
                   6484:             }
                   6485:         }
                   6486:     }
                   6487:     return %access;
                   6488: }
                   6489: 
                   6490: sub modify_access_controls {
                   6491:     my ($file_name,$changes,$domain,$user)=@_;
                   6492:     my ($outcome,$deloutcome);
                   6493:     my %store_permissions;
                   6494:     my %new_values;
                   6495:     my %new_control;
                   6496:     my %translation;
                   6497:     my @deletions = ();
                   6498:     my $now = time;
                   6499:     if (exists($$changes{'activate'})) {
                   6500:         if (ref($$changes{'activate'}) eq 'HASH') {
                   6501:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   6502:             my $numnew = scalar(@newitems);
                   6503:             for (my $i=0; $i<$numnew; $i++) {
                   6504:                 my $newkey = $newitems[$i];
                   6505:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  6506:                 if ($newkey =~ /^\d+:/) { 
                   6507:                     $newkey =~ s/^(\d+)/$newid/;
                   6508:                     $translation{$1} = $newid;
                   6509:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   6510:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   6511:                     $translation{$1} = $newid;
                   6512:                 }
1.749     raeburn  6513:                 $new_values{$file_name."\0".$newkey} = 
                   6514:                                           $$changes{'activate'}{$newitems[$i]};
                   6515:                 $new_control{$newkey} = $now;
                   6516:             }
                   6517:         }
                   6518:     }
                   6519:     my %todelete;
                   6520:     my %changed_items;
                   6521:     foreach my $action ('delete','update') {
                   6522:         if (exists($$changes{$action})) {
                   6523:             if (ref($$changes{$action}) eq 'HASH') {
                   6524:                 foreach my $key (keys(%{$$changes{$action}})) {
                   6525:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   6526:                     if ($action eq 'delete') { 
                   6527:                         $todelete{$itemnum} = 1;
                   6528:                     } else {
                   6529:                         $changed_items{$itemnum} = $key;
                   6530:                     }
                   6531:                 }
1.745     raeburn  6532:             }
                   6533:         }
1.749     raeburn  6534:     }
                   6535:     # get lock on access controls for file.
                   6536:     my $lockhash = {
                   6537:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   6538:                                                        ':'.$env{'user.domain'},
                   6539:                    }; 
                   6540:     my $tries = 0;
                   6541:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6542:    
                   6543:     while (($gotlock ne 'ok') && $tries <3) {
                   6544:         $tries ++;
                   6545:         sleep 1;
                   6546:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6547:     }
                   6548:     if ($gotlock eq 'ok') {
                   6549:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6550:         my ($tmp)=keys(%curr_permissions);
                   6551:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6552:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6553:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6554:             if (ref($curr_controls) eq 'HASH') {
                   6555:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6556:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6557:                     if (defined($todelete{$itemnum})) {
                   6558:                         push(@deletions,$file_name."\0".$control_item);
                   6559:                     } else {
                   6560:                         if (defined($changed_items{$itemnum})) {
                   6561:                             $new_control{$changed_items{$itemnum}} = $now;
                   6562:                             push(@deletions,$file_name."\0".$control_item);
                   6563:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6564:                         } else {
                   6565:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6566:                         }
                   6567:                     }
1.745     raeburn  6568:                 }
                   6569:             }
                   6570:         }
1.970     raeburn  6571:         my ($group);
                   6572:         if (&is_course($domain,$user)) {
                   6573:             ($group,my $file) = split(/\//,$file_name,2);
                   6574:         }
1.749     raeburn  6575:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6576:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6577:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6578:         #  remove lock
                   6579:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6580:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6581:         my $sqlresult =
1.970     raeburn  6582:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  6583:                                     $group);
1.749     raeburn  6584:     } else {
                   6585:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6586:     }
1.749     raeburn  6587:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6588: }
                   6589: 
1.827     raeburn  6590: sub make_public_indefinitely {
                   6591:     my ($requrl) = @_;
                   6592:     my $now = time;
                   6593:     my $action = 'activate';
                   6594:     my $aclnum = 0;
                   6595:     if (&is_portfolio_url($requrl)) {
                   6596:         my (undef,$udom,$unum,$file_name,$group) =
                   6597:             &parse_portfolio_url($requrl);
                   6598:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6599:         my %access_controls = &get_access_controls($current_perms,
                   6600:                                                    $group,$file_name);
                   6601:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6602:             my ($num,$scope,$end,$start) = 
                   6603:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6604:             if ($scope eq 'public') {
                   6605:                 if ($start <= $now && $end == 0) {
                   6606:                     $action = 'none';
                   6607:                 } else {
                   6608:                     $action = 'update';
                   6609:                     $aclnum = $num;
                   6610:                 }
                   6611:                 last;
                   6612:             }
                   6613:         }
                   6614:         if ($action eq 'none') {
                   6615:              return 'ok';
                   6616:         } else {
                   6617:             my %changes;
                   6618:             my $newend = 0;
                   6619:             my $newstart = $now;
                   6620:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6621:             $changes{$action}{$newkey} = {
                   6622:                 type => 'public',
                   6623:                 time => {
                   6624:                     start => $newstart,
                   6625:                     end   => $newend,
                   6626:                 },
                   6627:             };
                   6628:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6629:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6630:             return $outcome;
                   6631:         }
                   6632:     } else {
                   6633:         return 'invalid';
                   6634:     }
                   6635: }
                   6636: 
1.745     raeburn  6637: #------------------------------------------------------Get Marked as Read Only
                   6638: 
                   6639: sub get_marked_as_readonly {
                   6640:     my ($domain,$user,$what,$group) = @_;
                   6641:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6642:     my @readonly_files;
1.629     banghart 6643:     my $cmp1=$what;
                   6644:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6645:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6646:         if (defined($group)) {
                   6647:             if ($file_name !~ m-^\Q$group\E/-) {
                   6648:                 next;
                   6649:             }
                   6650:         }
1.561     banghart 6651:         if (ref($value) eq "ARRAY"){
                   6652:             foreach my $stored_what (@{$value}) {
1.629     banghart 6653:                 my $cmp2=$stored_what;
1.759     albertel 6654:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6655:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6656:                 }
1.629     banghart 6657:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6658:                     push(@readonly_files, $file_name);
1.745     raeburn  6659:                     last;
1.563     banghart 6660:                 } elsif (!defined($what)) {
                   6661:                     push(@readonly_files, $file_name);
1.745     raeburn  6662:                     last;
1.561     banghart 6663:                 }
                   6664:             }
1.745     raeburn  6665:         }
1.561     banghart 6666:     }
                   6667:     return @readonly_files;
                   6668: }
1.577     banghart 6669: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6670: 
1.577     banghart 6671: sub get_marked_as_readonly_hash {
1.745     raeburn  6672:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6673:     my %readonly_files;
1.745     raeburn  6674:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6675:         if (defined($group)) {
                   6676:             if ($file_name !~ m-^\Q$group\E/-) {
                   6677:                 next;
                   6678:             }
                   6679:         }
1.577     banghart 6680:         if (ref($value) eq "ARRAY"){
                   6681:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6682:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6683:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6684:                         if ($lock_descriptor eq 'graded') {
                   6685:                             $readonly_files{$file_name} = 'graded';
                   6686:                         } elsif ($lock_descriptor eq 'handback') {
                   6687:                             $readonly_files{$file_name} = 'handback';
                   6688:                         } else {
                   6689:                             if (!exists($readonly_files{$file_name})) {
                   6690:                                 $readonly_files{$file_name} = 'locked';
                   6691:                             }
                   6692:                         }
1.745     raeburn  6693:                     }
1.750     banghart 6694:                 } 
1.577     banghart 6695:             }
                   6696:         } 
                   6697:     }
                   6698:     return %readonly_files;
                   6699: }
1.559     banghart 6700: # ------------------------------------------------------------ Unmark as Read Only
                   6701: 
                   6702: sub unmark_as_readonly {
1.629     banghart 6703:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6704:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6705:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6706:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6707:     my $symb_crs = $what;
                   6708:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6709:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6710:     my ($tmp)=keys(%current_permissions);
                   6711:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6712:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6713:     foreach my $file (@readonly_files) {
1.759     albertel 6714: 	my $clean_file = &declutter_portfile($file);
                   6715: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6716: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6717:         my @new_locks;
                   6718:         my @del_keys;
                   6719:         if (ref($current_locks) eq "ARRAY"){
                   6720:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6721:                 my $compare=$locker;
1.749     raeburn  6722:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6723:                     $compare=join('',@{$locker});
1.746     raeburn  6724:                     if ($compare ne $symb_crs) {
                   6725:                         push(@new_locks, $locker);
                   6726:                     }
1.563     banghart 6727:                 }
                   6728:             }
1.650     albertel 6729:             if (scalar(@new_locks) > 0) {
1.563     banghart 6730:                 $current_permissions{$file} = \@new_locks;
                   6731:             } else {
                   6732:                 push(@del_keys, $file);
1.613     albertel 6733:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6734:                 delete($current_permissions{$file});
1.563     banghart 6735:             }
                   6736:         }
1.561     banghart 6737:     }
1.613     albertel 6738:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6739:     return;
                   6740: }
1.512     banghart 6741: 
1.17      www      6742: # ------------------------------------------------------------ Directory lister
                   6743: 
                   6744: sub dirlist {
1.955     raeburn  6745:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      6746:     $uri=~s/^\///;
                   6747:     $uri=~s/\/$//;
1.253     stredwic 6748:     my ($udom, $uname);
1.955     raeburn  6749:     if ($getuserdir) {
1.253     stredwic 6750:         $udom = $userdomain;
                   6751:         $uname = $username;
1.955     raeburn  6752:     } else {
                   6753:         (undef,$udom,$uname)=split(/\//,$uri);
                   6754:         if(defined($userdomain)) {
                   6755:             $udom = $userdomain;
                   6756:         }
                   6757:         if(defined($username)) {
                   6758:             $uname = $username;
                   6759:         }
1.253     stredwic 6760:     }
1.955     raeburn  6761:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 6762: 
1.955     raeburn  6763:     $dirRoot = $perlvar{'lonDocRoot'};
                   6764:     if (defined($getpropath)) {
                   6765:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 6766:         $dirRoot =~ s/\/$//;
1.955     raeburn  6767:     } elsif (defined($getuserdir)) {
                   6768:         my $subdir=$uname.'__';
                   6769:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6770:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   6771:                    ."/$udom/$subdir/$uname";
                   6772:     } elsif (defined($alternateRoot)) {
                   6773:         $dirRoot = $alternateRoot;
1.751     banghart 6774:     }
1.253     stredwic 6775: 
                   6776:     if($udom) {
                   6777:         if($uname) {
1.955     raeburn  6778:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  6779:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  6780:                               .':'.&escape($uname).':'.&escape($udom),
                   6781:                               &homeserver($uname,$udom));
                   6782:             if ($listing eq 'unknown_cmd') {
                   6783:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6784:                                   &homeserver($uname,$udom));
                   6785:             } else {
                   6786:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6787:             }
1.605     matthew  6788:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6789:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6790: 				  &homeserver($uname,$udom));
1.605     matthew  6791:                 @listing_results = split(/:/,$listing);
                   6792:             } else {
                   6793:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6794:             }
                   6795:             return @listing_results;
1.955     raeburn  6796:         } elsif(!$alternateRoot) {
1.800     albertel 6797:             my %allusers;
1.841     albertel 6798: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  6799:  	    foreach my $tryserver (keys(%servers)) {
                   6800:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   6801:                                   &escape($udom),$tryserver);
                   6802:                 if ($listing eq 'unknown_cmd') {
                   6803: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6804: 				      $udom, $tryserver);
                   6805:                 } else {
                   6806:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6807:                 }
1.841     albertel 6808: 		if ($listing eq 'unknown_cmd') {
                   6809: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6810: 				      $udom, $tryserver);
                   6811: 		    @listing_results = split(/:/,$listing);
                   6812: 		} else {
                   6813: 		    @listing_results =
                   6814: 			map { &unescape($_); } split(/:/,$listing);
                   6815: 		}
                   6816: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6817: 		    $listing_results[0] ne 'empty'       &&
                   6818: 		    $listing_results[0] ne 'con_lost') {
                   6819: 		    foreach my $line (@listing_results) {
                   6820: 			my ($entry) = split(/&/,$line,2);
                   6821: 			$allusers{$entry} = 1;
                   6822: 		    }
                   6823: 		}
1.253     stredwic 6824:             }
                   6825:             my $alluserstr='';
1.800     albertel 6826:             foreach my $user (sort(keys(%allusers))) {
                   6827:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6828:             }
                   6829:             $alluserstr=~s/:$//;
                   6830:             return split(/:/,$alluserstr);
                   6831:         } else {
1.800     albertel 6832:             return ('missing user name');
1.253     stredwic 6833:         }
1.955     raeburn  6834:     } elsif(!defined($getpropath)) {
1.841     albertel 6835:         my @all_domains = sort(&all_domains());
1.955     raeburn  6836:         foreach my $domain (@all_domains) {
                   6837:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6838:         }
                   6839:         return @all_domains;
                   6840:     } else {
1.800     albertel 6841:         return ('missing domain');
1.275     stredwic 6842:     }
                   6843: }
                   6844: 
                   6845: # --------------------------------------------- GetFileTimestamp
                   6846: # This function utilizes dirlist and returns the date stamp for
                   6847: # when it was last modified.  It will also return an error of -1
                   6848: # if an error occurs
                   6849: 
                   6850: sub GetFileTimestamp {
1.955     raeburn  6851:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 6852:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6853:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  6854:     my ($fileStat) = 
                   6855:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   6856:                                  undef,$getuserdir);
1.275     stredwic 6857:     my @stats = split('&', $fileStat);
                   6858:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6859:         # @stats contains first the filename, then the stat output
                   6860:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6861:     } else {
                   6862:         return -1;
1.253     stredwic 6863:     }
1.26      www      6864: }
                   6865: 
1.712     albertel 6866: sub stat_file {
                   6867:     my ($uri) = @_;
1.787     albertel 6868:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6869: 
1.955     raeburn  6870:     my ($udom,$uname,$file);
1.712     albertel 6871:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6872: 	($udom,$uname,$file) =
1.811     albertel 6873: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6874: 	$file = 'userfiles/'.$file;
                   6875:     }
                   6876:     if ($uri =~ m-^/res/-) {
                   6877: 	($udom,$uname) = 
1.807     albertel 6878: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6879: 	$file = $uri;
                   6880:     }
                   6881: 
                   6882:     if (!$udom || !$uname || !$file) {
                   6883: 	# unable to handle the uri
                   6884: 	return ();
                   6885:     }
1.956     raeburn  6886:     my $getpropath;
                   6887:     if ($file =~ /^userfiles\//) {
                   6888:         $getpropath = 1;
                   6889:     }
1.955     raeburn  6890:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 6891:     my @stats = split('&', $result);
1.721     banghart 6892:     
1.712     albertel 6893:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6894: 	shift(@stats); #filename is first
                   6895: 	return @stats;
                   6896:     }
                   6897:     return ();
                   6898: }
                   6899: 
1.26      www      6900: # -------------------------------------------------------- Value of a Condition
                   6901: 
1.713     albertel 6902: # gets the value of a specific preevaluated condition
                   6903: #    stored in the string  $env{user.state.<cid>}
                   6904: # or looks up a condition reference in the bighash and if if hasn't
                   6905: # already been evaluated recurses into docondval to get the value of
                   6906: # the condition, then memoizing it to 
                   6907: #   $env{user.state.<cid>.<condition>}
1.40      www      6908: sub directcondval {
                   6909:     my $number=shift;
1.620     albertel 6910:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6911: 	&Apache::lonuserstate::evalstate();
                   6912:     }
1.713     albertel 6913:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6914: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6915:     } elsif ($number =~ /^_/) {
                   6916: 	my $sub_condition;
                   6917: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6918: 		&GDBM_READER(),0640)) {
                   6919: 	    $sub_condition=$bighash{'conditions'.$number};
                   6920: 	    untie(%bighash);
                   6921: 	}
                   6922: 	my $value = &docondval($sub_condition);
1.949     raeburn  6923: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 6924: 	return $value;
                   6925:     }
1.620     albertel 6926:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6927:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6928:     } else {
                   6929:        return 2;
                   6930:     }
                   6931: }
                   6932: 
1.713     albertel 6933: # get the collection of conditions for this resource
1.26      www      6934: sub condval {
                   6935:     my $condidx=shift;
1.54      www      6936:     my $allpathcond='';
1.713     albertel 6937:     foreach my $cond (split(/\|/,$condidx)) {
                   6938: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6939: 	    $allpathcond.=
                   6940: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6941: 	}
1.191     harris41 6942:     }
1.54      www      6943:     $allpathcond=~s/\|$//;
1.713     albertel 6944:     return &docondval($allpathcond);
                   6945: }
                   6946: 
                   6947: #evaluates an expression of conditions
                   6948: sub docondval {
                   6949:     my ($allpathcond) = @_;
                   6950:     my $result=0;
                   6951:     if ($env{'request.course.id'}
                   6952: 	&& defined($allpathcond)) {
                   6953: 	my $operand='|';
                   6954: 	my @stack;
                   6955: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6956: 	    if ($chunk eq '(') {
                   6957: 		push @stack,($operand,$result);
                   6958: 	    } elsif ($chunk eq ')') {
                   6959: 		my $before=pop @stack;
                   6960: 		if (pop @stack eq '&') {
                   6961: 		    $result=$result>$before?$before:$result;
                   6962: 		} else {
                   6963: 		    $result=$result>$before?$result:$before;
                   6964: 		}
                   6965: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6966: 		$operand=$chunk;
                   6967: 	    } else {
                   6968: 		my $new=directcondval($chunk);
                   6969: 		if ($operand eq '&') {
                   6970: 		    $result=$result>$new?$new:$result;
                   6971: 		} else {
                   6972: 		    $result=$result>$new?$result:$new;
                   6973: 		}
                   6974: 	    }
                   6975: 	}
1.26      www      6976:     }
                   6977:     return $result;
1.421     albertel 6978: }
                   6979: 
                   6980: # ---------------------------------------------------- Devalidate courseresdata
                   6981: 
                   6982: sub devalidatecourseresdata {
                   6983:     my ($coursenum,$coursedomain)=@_;
                   6984:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6985:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6986: }
                   6987: 
1.763     www      6988: 
1.200     www      6989: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6990: #
                   6991: #  Parameters:
                   6992: #      $coursenum    - Number of the course.
                   6993: #      $coursedomain - Domain at which the course was created.
                   6994: #  Returns:
                   6995: #     A hash of the course parameters along (I think) with timestamps
                   6996: #     and version info.
1.877     foxr     6997: 
1.624     albertel 6998: sub get_courseresdata {
                   6999:     my ($coursenum,$coursedomain)=@_;
1.200     www      7000:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   7001:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7002:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 7003:     my %dumpreply;
1.417     albertel 7004:     unless (defined($cached)) {
1.624     albertel 7005: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 7006: 	$result=\%dumpreply;
1.251     albertel 7007: 	my ($tmp) = keys(%dumpreply);
                   7008: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 7009: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 7010: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   7011: 	    return $tmp;
1.416     albertel 7012: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 7013: 	    $result=undef;
1.599     albertel 7014: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 7015: 	}
                   7016:     }
1.624     albertel 7017:     return $result;
                   7018: }
                   7019: 
1.633     albertel 7020: sub devalidateuserresdata {
                   7021:     my ($uname,$udom)=@_;
                   7022:     my $hashid="$udom:$uname";
                   7023:     &devalidate_cache_new('userres',$hashid);
                   7024: }
                   7025: 
1.624     albertel 7026: sub get_userresdata {
                   7027:     my ($uname,$udom)=@_;
                   7028:     #most student don\'t have any data set, check if there is some data
                   7029:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   7030: 
                   7031:     my $hashid="$udom:$uname";
                   7032:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   7033:     if (!defined($cached)) {
                   7034: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   7035: 	$result=\%resourcedata;
                   7036: 	&do_cache_new('userres',$hashid,$result,600);
                   7037:     }
                   7038:     my ($tmp)=keys(%$result);
                   7039:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   7040: 	return $result;
                   7041:     }
                   7042:     #error 2 occurs when the .db doesn't exist
                   7043:     if ($tmp!~/error: 2 /) {
1.672     albertel 7044: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 7045: 		 " Trying to get resource data for ".
                   7046: 		 $uname." at ".$udom.": ".
                   7047: 		 $tmp."</font>");
                   7048:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 7049: 	#&EXT_cache_set($udom,$uname);
                   7050: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 7051: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 7052:     }
                   7053:     return $tmp;
                   7054: }
1.879     foxr     7055: #----------------------------------------------- resdata - return resource data
                   7056: #  Purpose:
                   7057: #    Return resource data for either users or for a course.
                   7058: #  Parameters:
                   7059: #     $name      - Course/user name.
                   7060: #     $domain    - Name of the domain the user/course is registered on.
                   7061: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   7062: #     @which     - Array of names of resources desired.
                   7063: #  Returns:
                   7064: #     The value of the first reasource in @which that is found in the
                   7065: #     resource hash.
                   7066: #  Exceptional Conditions:
                   7067: #     If the $type passed in is not valid (not the string 'course' or 
                   7068: #     'user', an undefined  reference is returned.
                   7069: #     If none of the resources are found, an undef is returned
1.624     albertel 7070: sub resdata {
                   7071:     my ($name,$domain,$type,@which)=@_;
                   7072:     my $result;
                   7073:     if ($type eq 'course') {
                   7074: 	$result=&get_courseresdata($name,$domain);
                   7075:     } elsif ($type eq 'user') {
                   7076: 	$result=&get_userresdata($name,$domain);
                   7077:     }
                   7078:     if (!ref($result)) { return $result; }    
1.251     albertel 7079:     foreach my $item (@which) {
1.927     albertel 7080: 	if (defined($result->{$item->[0]})) {
                   7081: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 7082: 	}
1.250     albertel 7083:     }
1.291     albertel 7084:     return undef;
1.200     www      7085: }
                   7086: 
1.379     matthew  7087: #
                   7088: # EXT resource caching routines
                   7089: #
                   7090: 
                   7091: sub clear_EXT_cache_status {
1.383     albertel 7092:     &delenv('cache.EXT.');
1.379     matthew  7093: }
                   7094: 
                   7095: sub EXT_cache_status {
                   7096:     my ($target_domain,$target_user) = @_;
1.383     albertel 7097:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 7098:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  7099:         # We know already the user has no data
                   7100:         return 1;
                   7101:     } else {
                   7102:         return 0;
                   7103:     }
                   7104: }
                   7105: 
                   7106: sub EXT_cache_set {
                   7107:     my ($target_domain,$target_user) = @_;
1.383     albertel 7108:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  7109:     #&appenv({$cachename => time});
1.379     matthew  7110: }
                   7111: 
1.28      www      7112: # --------------------------------------------------------- Value of a Variable
1.58      www      7113: sub EXT {
1.715     albertel 7114: 
1.395     albertel 7115:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      7116:     unless ($varname) { return ''; }
1.218     albertel 7117:     #get real user name/domain, courseid and symb
                   7118:     my $courseid;
1.359     albertel 7119:     my $publicuser;
1.427     www      7120:     if ($symbparm) {
                   7121: 	$symbparm=&get_symb_from_alias($symbparm);
                   7122:     }
1.218     albertel 7123:     if (!($uname && $udom)) {
1.790     albertel 7124:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 7125:       if (!$symbparm) {	$symbparm=$cursymb; }
                   7126:     } else {
1.620     albertel 7127: 	$courseid=$env{'request.course.id'};
1.218     albertel 7128:     }
1.48      www      7129:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   7130:     my $rest;
1.320     albertel 7131:     if (defined($therest[0])) {
1.48      www      7132:        $rest=join('.',@therest);
                   7133:     } else {
                   7134:        $rest='';
                   7135:     }
1.320     albertel 7136: 
1.57      www      7137:     my $qualifierrest=$qualifier;
                   7138:     if ($rest) { $qualifierrest.='.'.$rest; }
                   7139:     my $spacequalifierrest=$space;
                   7140:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      7141:     if ($realm eq 'user') {
1.48      www      7142: # --------------------------------------------------------------- user.resource
                   7143: 	if ($space eq 'resource') {
1.651     albertel 7144: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   7145: 		  || defined($Apache::lonhomework::parsing_a_task))
                   7146: 		 &&
1.744     albertel 7147: 		 ($symbparm eq &symbread()) ) {	
                   7148: 		# if we are in the middle of processing the resource the
                   7149: 		# get the value we are planning on committing
                   7150:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   7151:                     return $Apache::lonhomework::results{$qualifierrest};
                   7152:                 } else {
                   7153:                     return $Apache::lonhomework::history{$qualifierrest};
                   7154:                 }
1.335     albertel 7155: 	    } else {
1.359     albertel 7156: 		my %restored;
1.620     albertel 7157: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 7158: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   7159: 		} else {
                   7160: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   7161: 		}
1.335     albertel 7162: 		return $restored{$qualifierrest};
                   7163: 	    }
1.48      www      7164: # ----------------------------------------------------------------- user.access
                   7165:         } elsif ($space eq 'access') {
1.218     albertel 7166: 	    # FIXME - not supporting calls for a specific user
1.48      www      7167:             return &allowed($qualifier,$rest);
                   7168: # ------------------------------------------ user.preferences, user.environment
                   7169:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 7170: 	    if (($uname eq $env{'user.name'}) &&
                   7171: 		($udom eq $env{'user.domain'})) {
                   7172: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 7173: 	    } else {
1.359     albertel 7174: 		my %returnhash;
                   7175: 		if (!$publicuser) {
                   7176: 		    %returnhash=&userenvironment($udom,$uname,
                   7177: 						 $qualifierrest);
                   7178: 		}
1.218     albertel 7179: 		return $returnhash{$qualifierrest};
                   7180: 	    }
1.48      www      7181: # ----------------------------------------------------------------- user.course
                   7182:         } elsif ($space eq 'course') {
1.218     albertel 7183: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 7184:             return $env{join('.',('request.course',$qualifier))};
1.48      www      7185: # ------------------------------------------------------------------- user.role
                   7186:         } elsif ($space eq 'role') {
1.218     albertel 7187: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 7188:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      7189:             if ($qualifier eq 'value') {
                   7190: 		return $role;
                   7191:             } elsif ($qualifier eq 'extent') {
                   7192:                 return $where;
                   7193:             }
                   7194: # ----------------------------------------------------------------- user.domain
                   7195:         } elsif ($space eq 'domain') {
1.218     albertel 7196:             return $udom;
1.48      www      7197: # ------------------------------------------------------------------- user.name
                   7198:         } elsif ($space eq 'name') {
1.218     albertel 7199:             return $uname;
1.48      www      7200: # ---------------------------------------------------- Any other user namespace
1.29      www      7201:         } else {
1.359     albertel 7202: 	    my %reply;
                   7203: 	    if (!$publicuser) {
                   7204: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   7205: 	    }
                   7206: 	    return $reply{$qualifierrest};
1.48      www      7207:         }
1.236     www      7208:     } elsif ($realm eq 'query') {
                   7209: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 7210:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   7211: 						[$spacequalifierrest]);
1.620     albertel 7212: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      7213:    } elsif ($realm eq 'request') {
1.48      www      7214: # ------------------------------------------------------------- request.browser
                   7215:         if ($space eq 'browser') {
1.430     www      7216: 	    if ($qualifier eq 'textremote') {
1.676     albertel 7217: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      7218: 		    return 1;
                   7219: 		} else {
                   7220: 		    return 0;
                   7221: 		}
                   7222: 	    } else {
1.620     albertel 7223: 		return $env{'browser.'.$qualifier};
1.430     www      7224: 	    }
1.57      www      7225: # ------------------------------------------------------------ request.filename
                   7226:         } else {
1.620     albertel 7227:             return $env{'request.'.$spacequalifierrest};
1.29      www      7228:         }
1.28      www      7229:     } elsif ($realm eq 'course') {
1.48      www      7230: # ---------------------------------------------------------- course.description
1.620     albertel 7231:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      7232:     } elsif ($realm eq 'resource') {
1.165     www      7233: 
1.620     albertel 7234: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 7235: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   7236: 	}
1.693     albertel 7237: 
                   7238: 	if ($space eq 'title') {
                   7239: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   7240: 	    return &gettitle($symbparm);
                   7241: 	}
                   7242: 	
                   7243: 	if ($space eq 'map') {
                   7244: 	    my ($map) = &decode_symb($symbparm);
                   7245: 	    return &symbread($map);
                   7246: 	}
1.905     albertel 7247: 	if ($space eq 'filename') {
                   7248: 	    if ($symbparm) {
                   7249: 		return &clutter((&decode_symb($symbparm))[2]);
                   7250: 	    }
                   7251: 	    return &hreflocation('',$env{'request.filename'});
                   7252: 	}
1.693     albertel 7253: 
                   7254: 	my ($section, $group, @groups);
1.593     albertel 7255: 	my ($courselevelm,$courselevel);
1.539     albertel 7256: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7257: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      7258: 
1.218     albertel 7259: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      7260: 
1.60      www      7261: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 7262: 	    my $symbp=$symbparm;
1.735     albertel 7263: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 7264: 
                   7265: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   7266: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   7267: 
1.620     albertel 7268: 	    if (($env{'user.name'} eq $uname) &&
                   7269: 		($env{'user.domain'} eq $udom)) {
                   7270: 		$section=$env{'request.course.sec'};
1.733     raeburn  7271:                 @groups = split(/:/,$env{'request.course.groups'});  
                   7272:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 7273: 	    } else {
1.539     albertel 7274: 		if (! defined($usection)) {
1.551     albertel 7275: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 7276: 		} else {
                   7277: 		    $section = $usection;
                   7278: 		}
1.733     raeburn  7279:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 7280: 	    }
                   7281: 
                   7282: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   7283: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   7284: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   7285: 
1.593     albertel 7286: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 7287: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 7288: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      7289: 
1.60      www      7290: # ----------------------------------------------------------- first, check user
1.624     albertel 7291: 
                   7292: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 7293: 				       ([$courselevelr,'resource'],
                   7294: 					[$courselevelm,'map'     ],
                   7295: 					[$courselevel, 'course'  ]));
1.931     albertel 7296: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      7297: 
1.594     albertel 7298: # ------------------------------------------------ second, check some of course
1.684     raeburn  7299:             my $coursereply;
1.691     raeburn  7300:             if (@groups > 0) {
                   7301:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   7302:                                        $mapparm,$spacequalifierrest);
1.927     albertel 7303:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  7304:             }
1.96      www      7305: 
1.684     raeburn  7306: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 7307: 				  $env{'course.'.$courseid.'.domain'},
                   7308: 				  'course',
                   7309: 				  ([$seclevelr,   'resource'],
                   7310: 				   [$seclevelm,   'map'     ],
                   7311: 				   [$seclevel,    'course'  ],
                   7312: 				   [$courselevelr,'resource']));
                   7313: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      7314: 
1.60      www      7315: # ------------------------------------------------------ third, check map parms
1.218     albertel 7316: 	    my %parmhash=();
                   7317: 	    my $thisparm='';
                   7318: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 7319: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 7320: 		    &GDBM_READER(),0640)) {
1.218     albertel 7321: 		$thisparm=$parmhash{$symbparm};
                   7322: 		untie(%parmhash);
                   7323: 	    }
1.927     albertel 7324: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 7325: 	}
1.594     albertel 7326: # ------------------------------------------ fourth, look in resource metadata
1.71      www      7327: 
1.218     albertel 7328: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 7329: 	my $filename;
                   7330: 	if (!$symbparm) { $symbparm=&symbread(); }
                   7331: 	if ($symbparm) {
1.409     www      7332: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 7333: 	} else {
1.620     albertel 7334: 	    $filename=$env{'request.filename'};
1.282     albertel 7335: 	}
                   7336: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 7337: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 7338: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 7339: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      7340: 
1.927     albertel 7341: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 7342: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7343: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 7344: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   7345: 				     $env{'course.'.$courseid.'.domain'},
                   7346: 				     'course',
1.927     albertel 7347: 				     ([$courselevelm,'map'   ],
                   7348: 				      [$courselevel, 'course']));
                   7349: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 7350: 	}
1.145     www      7351: # ------------------------------------------------------------------ Cascade up
1.218     albertel 7352: 	unless ($space eq '0') {
1.336     albertel 7353: 	    my @parts=split(/_/,$space);
                   7354: 	    my $id=pop(@parts);
                   7355: 	    my $part=join('_',@parts);
                   7356: 	    if ($part eq '') { $part='0'; }
1.927     albertel 7357: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 7358: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  7359: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 7360: 	}
1.395     albertel 7361: 	if ($recurse) { return undef; }
                   7362: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 7363: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      7364: # ---------------------------------------------------- Any other user namespace
                   7365:     } elsif ($realm eq 'environment') {
                   7366: # ----------------------------------------------------------------- environment
1.620     albertel 7367: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   7368: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 7369: 	} else {
1.770     albertel 7370: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   7371: 		return '';
                   7372: 	    }
1.219     albertel 7373: 	    my %returnhash=&userenvironment($udom,$uname,
                   7374: 					    $spacequalifierrest);
                   7375: 	    return $returnhash{$spacequalifierrest};
                   7376: 	}
1.28      www      7377:     } elsif ($realm eq 'system') {
1.48      www      7378: # ----------------------------------------------------------------- system.time
                   7379: 	if ($space eq 'time') {
                   7380: 	    return time;
                   7381:         }
1.696     albertel 7382:     } elsif ($realm eq 'server') {
                   7383: # ----------------------------------------------------------------- system.time
                   7384: 	if ($space eq 'name') {
                   7385: 	    return $ENV{'SERVER_NAME'};
                   7386:         }
1.28      www      7387:     }
1.48      www      7388:     return '';
1.61      www      7389: }
                   7390: 
1.927     albertel 7391: sub get_reply {
                   7392:     my ($reply_value) = @_;
1.940     raeburn  7393:     if (ref($reply_value) eq 'ARRAY') {
                   7394:         if (wantarray) {
                   7395: 	    return @$reply_value;
                   7396:         }
                   7397:         return $reply_value->[0];
                   7398:     } else {
                   7399:         return $reply_value;
1.927     albertel 7400:     }
                   7401: }
                   7402: 
1.691     raeburn  7403: sub check_group_parms {
                   7404:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   7405:     my @groupitems = ();
                   7406:     my $resultitem;
1.927     albertel 7407:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  7408:     foreach my $group (@{$groups}) {
                   7409:         foreach my $level (@levels) {
1.927     albertel 7410:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   7411:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  7412:         }
                   7413:     }
                   7414:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   7415:                             $env{'course.'.$courseid.'.domain'},
                   7416:                                      'course',@groupitems);
                   7417:     return $coursereply;
                   7418: }
                   7419: 
                   7420: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  7421:     my ($courseid,@groups) = @_;
                   7422:     @groups = sort(@groups);
1.691     raeburn  7423:     return @groups;
                   7424: }
                   7425: 
1.395     albertel 7426: sub packages_tab_default {
                   7427:     my ($uri,$varname)=@_;
                   7428:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 7429: 
                   7430:     my (@extension,@specifics,$do_default);
                   7431:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 7432: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 7433: 	if ($pack_type eq 'default') {
                   7434: 	    $do_default=1;
                   7435: 	} elsif ($pack_type eq 'extension') {
                   7436: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 7437: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 7438: 	    # only look at packages defaults for packages that this id is
1.738     albertel 7439: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   7440: 	}
                   7441:     }
                   7442:     # first look for a package that matches the requested part id
                   7443:     foreach my $package (@specifics) {
                   7444: 	my (undef,$pack_type,$pack_part)=@{$package};
                   7445: 	next if ($pack_part ne $part);
                   7446: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7447: 	    return $packagetab{"$pack_type&$name&default"};
                   7448: 	}
                   7449:     }
                   7450:     # look for any possible matching non extension_ package
                   7451:     foreach my $package (@specifics) {
                   7452: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 7453: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7454: 	    return $packagetab{"$pack_type&$name&default"};
                   7455: 	}
1.585     albertel 7456: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 7457: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   7458: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 7459: 	}
                   7460:     }
1.738     albertel 7461:     # look for any posible extension_ match
                   7462:     foreach my $package (@extension) {
                   7463: 	my ($package,$pack_type)=@{$package};
                   7464: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7465: 	    return $packagetab{"$pack_type&$name&default"};
                   7466: 	}
                   7467: 	if (defined($packagetab{$package."&$name&default"})) {
                   7468: 	    return $packagetab{$package."&$name&default"};
                   7469: 	}
                   7470:     }
                   7471:     # look for a global default setting
                   7472:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   7473: 	return $packagetab{"default&$name&default"};
                   7474:     }
1.395     albertel 7475:     return undef;
                   7476: }
                   7477: 
1.334     albertel 7478: sub add_prefix_and_part {
                   7479:     my ($prefix,$part)=@_;
                   7480:     my $keyroot;
                   7481:     if (defined($prefix) && $prefix !~ /^__/) {
                   7482: 	# prefix that has a part already
                   7483: 	$keyroot=$prefix;
                   7484:     } elsif (defined($prefix)) {
                   7485: 	# prefix that is missing a part
                   7486: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   7487:     } else {
                   7488: 	# no prefix at all
                   7489: 	if (defined($part)) { $keyroot='_'.$part; }
                   7490:     }
                   7491:     return $keyroot;
                   7492: }
                   7493: 
1.71      www      7494: # ---------------------------------------------------------------- Get metadata
                   7495: 
1.599     albertel 7496: my %metaentry;
1.71      www      7497: sub metadata {
1.176     www      7498:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      7499:     $uri=&declutter($uri);
1.288     albertel 7500:     # if it is a non metadata possible uri return quickly
1.529     albertel 7501:     if (($uri eq '') || 
                   7502: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 7503: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 7504:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   7505: 	return undef;
                   7506:     }
                   7507:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   7508: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 7509: 	return undef;
1.288     albertel 7510:     }
1.73      www      7511:     my $filename=$uri;
                   7512:     $uri=~s/\.meta$//;
1.172     www      7513: #
                   7514: # Is the metadata already cached?
1.177     www      7515: # Look at timestamp of caching
1.172     www      7516: # Everything is cached by the main uri, libraries are never directly cached
                   7517: #
1.428     albertel 7518:     if (!defined($liburi)) {
1.599     albertel 7519: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 7520: 	if (defined($cached)) { return $result->{':'.$what}; }
                   7521:     }
                   7522:     {
1.172     www      7523: #
                   7524: # Is this a recursive call for a library?
                   7525: #
1.599     albertel 7526: #	if (! exists($metacache{$uri})) {
                   7527: #	    $metacache{$uri}={};
                   7528: #	}
1.924     albertel 7529: 	my $cachetime = 60*60;
1.171     www      7530:         if ($liburi) {
                   7531: 	    $liburi=&declutter($liburi);
                   7532:             $filename=$liburi;
1.401     bowersj2 7533:         } else {
1.599     albertel 7534: 	    &devalidate_cache_new('meta',$uri);
                   7535: 	    undef(%metaentry);
1.401     bowersj2 7536: 	}
1.140     www      7537:         my %metathesekeys=();
1.73      www      7538:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 7539: 	my $metastring;
1.924     albertel 7540: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 7541: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 7542: 	    $metastring = 
1.929     albertel 7543: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 7544: 					  ('grade_target' => 'meta'));
                   7545: 	    $cachetime = 1; # only want this cached in the child not long term
                   7546: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 7547: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 7548: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 7549: 	    $metastring=&getfile($file);
1.489     albertel 7550: 	}
1.208     albertel 7551:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      7552:         my $token;
1.140     www      7553:         undef %metathesekeys;
1.71      www      7554:         while ($token=$parser->get_token) {
1.339     albertel 7555: 	    if ($token->[0] eq 'S') {
                   7556: 		if (defined($token->[2]->{'package'})) {
1.172     www      7557: #
                   7558: # This is a package - get package info
                   7559: #
1.339     albertel 7560: 		    my $package=$token->[2]->{'package'};
                   7561: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7562: 		    if (defined($token->[2]->{'id'})) { 
                   7563: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7564: 		    }
1.599     albertel 7565: 		    if ($metaentry{':packages'}) {
                   7566: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7567: 		    } else {
1.599     albertel 7568: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7569: 		    }
1.736     albertel 7570: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7571: 			my $part=$keyroot;
                   7572: 			$part=~s/^\_//;
1.736     albertel 7573: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7574: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7575: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7576: 			    # ignore package.tab specified default values
                   7577:                             # here &package_tab_default() will fetch those
                   7578: 			    if ($subp eq 'default') { next; }
1.736     albertel 7579: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7580: 			    my $unikey;
                   7581: 			    if ($pack =~ /_0$/) {
                   7582: 				$unikey='parameter_0_'.$name;
                   7583: 				$part=0;
                   7584: 			    } else {
                   7585: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7586: 			    }
1.339     albertel 7587: 			    if ($subp eq 'display') {
                   7588: 				$value.=' [Part: '.$part.']';
                   7589: 			    }
1.599     albertel 7590: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7591: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7592: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7593: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7594: 			    }
1.599     albertel 7595: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7596: 				$metaentry{':'.$unikey}=
                   7597: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7598: 			    }
1.339     albertel 7599: 			}
                   7600: 		    }
                   7601: 		} else {
1.172     www      7602: #
                   7603: # This is not a package - some other kind of start tag
1.339     albertel 7604: #
                   7605: 		    my $entry=$token->[1];
                   7606: 		    my $unikey;
                   7607: 		    if ($entry eq 'import') {
                   7608: 			$unikey='';
                   7609: 		    } else {
                   7610: 			$unikey=$entry;
                   7611: 		    }
                   7612: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7613: 
                   7614: 		    if (defined($token->[2]->{'id'})) { 
                   7615: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7616: 		    }
1.175     www      7617: 
1.339     albertel 7618: 		    if ($entry eq 'import') {
1.175     www      7619: #
                   7620: # Importing a library here
1.339     albertel 7621: #
                   7622: 			if ($depthcount<20) {
                   7623: 			    my $location=$parser->get_text('/import');
                   7624: 			    my $dir=$filename;
                   7625: 			    $dir=~s|[^/]*$||;
                   7626: 			    $location=&filelocation($dir,$location);
1.736     albertel 7627: 			    my $metadata = 
                   7628: 				&metadata($uri,'keys', $location,$unikey,
                   7629: 					  $depthcount+1);
                   7630: 			    foreach my $meta (split(',',$metadata)) {
                   7631: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7632: 				$metathesekeys{$meta}=1;
1.339     albertel 7633: 			    }
                   7634: 			}
                   7635: 		    } else { 
                   7636: 			
                   7637: 			if (defined($token->[2]->{'name'})) { 
                   7638: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7639: 			}
                   7640: 			$metathesekeys{$unikey}=1;
1.736     albertel 7641: 			foreach my $param (@{$token->[3]}) {
                   7642: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7643: 				$token->[2]->{$param};
1.339     albertel 7644: 			}
                   7645: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7646: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7647: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7648: 		 # only ws inside the tag, and not in default, so use default
                   7649: 		 # as value
1.599     albertel 7650: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7651: 			} elsif ( $internaltext =~ /\S/ ) {
                   7652: 		  # something interesting inside the tag
                   7653: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7654: 			} else {
1.908     albertel 7655: 		  # no interesting values, don't set a default
1.339     albertel 7656: 			}
1.172     www      7657: # end of not-a-package not-a-library import
1.339     albertel 7658: 		    }
1.172     www      7659: # end of not-a-package start tag
1.339     albertel 7660: 		}
1.172     www      7661: # the next is the end of "start tag"
1.339     albertel 7662: 	    }
                   7663: 	}
1.483     albertel 7664: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7665: 	$extension = lc($extension);
                   7666: 	if ($extension eq 'htm') { $extension='html'; }
                   7667: 
1.737     albertel 7668: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7669: 	    #no specific packages #how's our extension
                   7670: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7671: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7672: 					 \%metathesekeys);
                   7673: 	}
1.883     albertel 7674: 
                   7675: 	if (!exists($metaentry{':packages'})
                   7676: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7677: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7678: 		#no specific packages well let's get default then
                   7679: 		if ($key!~/^default&/) { next; }
1.488     albertel 7680: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7681: 					     \%metathesekeys);
                   7682: 	    }
                   7683: 	}
1.338     www      7684: # are there custom rights to evaluate
1.599     albertel 7685: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7686: 
1.338     www      7687:     #
                   7688:     # Importing a rights file here
1.339     albertel 7689:     #
                   7690: 	    unless ($depthcount) {
1.599     albertel 7691: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7692: 		my $dir=$filename;
                   7693: 		$dir=~s|[^/]*$||;
                   7694: 		$location=&filelocation($dir,$location);
1.736     albertel 7695: 		my $rights_metadata =
                   7696: 		    &metadata($uri,'keys',$location,'_rights',
                   7697: 			      $depthcount+1);
                   7698: 		foreach my $rights (split(',',$rights_metadata)) {
                   7699: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7700: 		    $metathesekeys{$rights}=1;
1.339     albertel 7701: 		}
                   7702: 	    }
                   7703: 	}
1.737     albertel 7704: 	# uniqifiy package listing
                   7705: 	my %seen;
                   7706: 	my @uniq_packages =
                   7707: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7708: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7709: 
                   7710: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7711: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7712: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7713: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7714: # this is the end of "was not already recently cached
1.71      www      7715:     }
1.599     albertel 7716:     return $metaentry{':'.$what};
1.261     albertel 7717: }
                   7718: 
1.488     albertel 7719: sub metadata_create_package_def {
1.483     albertel 7720:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7721:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7722:     if ($subp eq 'default') { next; }
                   7723:     
1.599     albertel 7724:     if (defined($metaentry{':packages'})) {
                   7725: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7726:     } else {
1.599     albertel 7727: 	$metaentry{':packages'}=$package;
1.483     albertel 7728:     }
                   7729:     my $value=$packagetab{$key};
                   7730:     my $unikey;
                   7731:     $unikey='parameter_0_'.$name;
1.599     albertel 7732:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7733:     $$metathesekeys{$unikey}=1;
1.599     albertel 7734:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7735: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7736:     }
1.599     albertel 7737:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7738: 	$metaentry{':'.$unikey}=
                   7739: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7740:     }
                   7741: }
                   7742: 
1.261     albertel 7743: sub metadata_generate_part0 {
                   7744:     my ($metadata,$metacache,$uri) = @_;
                   7745:     my %allnames;
1.737     albertel 7746:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7747: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7748: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7749: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7750: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7751: 	    $allnames{$name}=$part;
                   7752: 	  }
                   7753: 	}
                   7754:     }
                   7755:     foreach my $name (keys(%allnames)) {
                   7756:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7757:       my $key=":parameter_0_$name";
1.261     albertel 7758:       $$metacache{"$key.part"}='0';
                   7759:       $$metacache{"$key.name"}=$name;
1.428     albertel 7760:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7761: 					   $allnames{$name}.'_'.$name.
                   7762: 					   '.type'};
1.428     albertel 7763:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7764: 			     '.display'};
1.644     www      7765:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7766:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7767:       $$metacache{"$key.display"}=$olddis;
                   7768:     }
1.71      www      7769: }
                   7770: 
1.764     albertel 7771: # ------------------------------------------------------ Devalidate title cache
                   7772: 
                   7773: sub devalidate_title_cache {
                   7774:     my ($url)=@_;
                   7775:     if (!$env{'request.course.id'}) { return; }
                   7776:     my $symb=&symbread($url);
                   7777:     if (!$symb) { return; }
                   7778:     my $key=$env{'request.course.id'}."\0".$symb;
                   7779:     &devalidate_cache_new('title',$key);
                   7780: }
                   7781: 
1.301     www      7782: # ------------------------------------------------- Get the title of a resource
                   7783: 
                   7784: sub gettitle {
                   7785:     my $urlsymb=shift;
                   7786:     my $symb=&symbread($urlsymb);
1.534     albertel 7787:     if ($symb) {
1.620     albertel 7788: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7789: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7790: 	if (defined($cached)) { 
                   7791: 	    return $result;
                   7792: 	}
1.534     albertel 7793: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7794: 	my $title='';
1.907     albertel 7795: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7796: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7797: 	} else {
                   7798: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7799: 		    &GDBM_READER(),0640)) {
                   7800: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7801: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7802: 		untie(%bighash);
                   7803: 	    }
1.534     albertel 7804: 	}
                   7805: 	$title=~s/\&colon\;/\:/gs;
                   7806: 	if ($title) {
1.599     albertel 7807: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7808: 	}
                   7809: 	$urlsymb=$url;
                   7810:     }
                   7811:     my $title=&metadata($urlsymb,'title');
                   7812:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7813:     return $title;
1.301     www      7814: }
1.613     albertel 7815: 
1.614     albertel 7816: sub get_slot {
                   7817:     my ($which,$cnum,$cdom)=@_;
                   7818:     if (!$cnum || !$cdom) {
1.790     albertel 7819: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7820: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7821: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7822:     }
1.703     albertel 7823:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7824:     my %slotinfo;
                   7825:     if (exists($remembered{$key})) {
                   7826: 	$slotinfo{$which} = $remembered{$key};
                   7827:     } else {
                   7828: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7829: 	&Apache::lonhomework::showhash(%slotinfo);
                   7830: 	my ($tmp)=keys(%slotinfo);
                   7831: 	if ($tmp=~/^error:/) { return (); }
                   7832: 	$remembered{$key} = $slotinfo{$which};
                   7833:     }
1.616     albertel 7834:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7835: 	return %{$slotinfo{$which}};
                   7836:     }
                   7837:     return $slotinfo{$which};
1.614     albertel 7838: }
1.31      www      7839: # ------------------------------------------------- Update symbolic store links
                   7840: 
                   7841: sub symblist {
                   7842:     my ($mapname,%newhash)=@_;
1.438     www      7843:     $mapname=&deversion(&declutter($mapname));
1.31      www      7844:     my %hash;
1.620     albertel 7845:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7846:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7847:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  7848: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 7849: 		next if ($url eq 'last_known'
                   7850: 			 && $env{'form.no_update_last_known'});
                   7851: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7852: 						    $newhash{$url}->[1],
                   7853: 						    $newhash{$url}->[0]);
1.191     harris41 7854:             }
1.31      www      7855:             if (untie(%hash)) {
                   7856: 		return 'ok';
                   7857:             }
                   7858:         }
                   7859:     }
                   7860:     return 'error';
1.212     www      7861: }
                   7862: 
                   7863: # --------------------------------------------------------------- Verify a symb
                   7864: 
                   7865: sub symbverify {
1.510     www      7866:     my ($symb,$thisurl)=@_;
                   7867:     my $thisfn=$thisurl;
1.439     www      7868:     $thisfn=&declutter($thisfn);
1.215     www      7869: # direct jump to resource in page or to a sequence - will construct own symbs
                   7870:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7871: # check URL part
1.409     www      7872:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7873: 
1.431     www      7874:     unless ($url eq $thisfn) { return 0; }
1.213     www      7875: 
1.216     www      7876:     $symb=&symbclean($symb);
1.510     www      7877:     $thisurl=&deversion($thisurl);
1.439     www      7878:     $thisfn=&deversion($thisfn);
1.213     www      7879: 
                   7880:     my %bighash;
                   7881:     my $okay=0;
1.431     www      7882: 
1.620     albertel 7883:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7884:                             &GDBM_READER(),0640)) {
1.510     www      7885:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7886:         unless ($ids) { 
1.510     www      7887:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7888:         }
                   7889:         if ($ids) {
                   7890: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7891: 	    foreach my $id (split(/\,/,$ids)) {
                   7892: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7893:                if (
                   7894:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7895:    eq $symb) { 
1.620     albertel 7896: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7897: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7898: 		       $okay=1; 
                   7899: 		   }
                   7900: 	       }
1.216     www      7901: 	   }
                   7902:         }
1.213     www      7903: 	untie(%bighash);
                   7904:     }
                   7905:     return $okay;
1.31      www      7906: }
                   7907: 
1.210     www      7908: # --------------------------------------------------------------- Clean-up symb
                   7909: 
                   7910: sub symbclean {
                   7911:     my $symb=shift;
1.568     albertel 7912:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7913: # remove version from map
                   7914:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7915: 
1.210     www      7916: # remove version from URL
                   7917:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7918: 
1.507     www      7919: # remove wrapper
                   7920: 
1.510     www      7921:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7922:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7923:     return $symb;
1.409     www      7924: }
                   7925: 
                   7926: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7927: 
                   7928: sub encode_symb {
                   7929:     my ($map,$resid,$url)=@_;
                   7930:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7931: }
1.409     www      7932: 
                   7933: sub decode_symb {
1.568     albertel 7934:     my $symb=shift;
                   7935:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7936:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7937:     return (&fixversion($map),$resid,&fixversion($url));
                   7938: }
                   7939: 
                   7940: sub fixversion {
                   7941:     my $fn=shift;
1.609     banghart 7942:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7943:     my %bighash;
                   7944:     my $uri=&clutter($fn);
1.620     albertel 7945:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7946: # is this cached?
1.599     albertel 7947:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7948:     if (defined($cached)) { return $result; }
                   7949: # unfortunately not cached, or expired
1.620     albertel 7950:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7951: 	    &GDBM_READER(),0640)) {
                   7952:  	if ($bighash{'version_'.$uri}) {
                   7953:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7954:  	    unless (($version eq 'mostrecent') || 
                   7955: 		    ($version==&getversion($uri))) {
1.440     www      7956:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7957:  	    }
                   7958:  	}
                   7959:  	untie %bighash;
1.413     www      7960:     }
1.599     albertel 7961:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7962: }
                   7963: 
                   7964: sub deversion {
                   7965:     my $url=shift;
                   7966:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7967:     return $url;
1.210     www      7968: }
                   7969: 
1.31      www      7970: # ------------------------------------------------------ Return symb list entry
                   7971: 
                   7972: sub symbread {
1.249     www      7973:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7974:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7975:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7976: # no filename provided? try from environment
1.44      www      7977:     unless ($thisfn) {
1.620     albertel 7978:         if ($env{'request.symb'}) {
                   7979: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7980: 	}
1.620     albertel 7981: 	$thisfn=$env{'request.filename'};
1.44      www      7982:     }
1.569     albertel 7983:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7984: # is that filename actually a symb? Verify, clean, and return
                   7985:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7986: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7987: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7988: 	}
1.242     www      7989:     }
1.44      www      7990:     $thisfn=declutter($thisfn);
1.31      www      7991:     my %hash;
1.37      www      7992:     my %bighash;
                   7993:     my $syval='';
1.620     albertel 7994:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7995:         my $targetfn = $thisfn;
1.609     banghart 7996:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7997:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7998:         }
1.687     albertel 7999: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   8000: 	    $targetfn=$1;
                   8001: 	}
1.620     albertel 8002:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8003:                       &GDBM_READER(),0640)) {
1.481     raeburn  8004: 	    $syval=$hash{$targetfn};
1.37      www      8005:             untie(%hash);
                   8006:         }
                   8007: # ---------------------------------------------------------- There was an entry
                   8008:         if ($syval) {
1.601     albertel 8009: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 8010: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  8011: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 8012: 		    #return $env{$cache_str}='';
1.601     albertel 8013: 		#}    
                   8014: 		#$syval.=$1;
                   8015: 	    #}
1.37      www      8016:         } else {
                   8017: # ------------------------------------------------------- Was not in symb table
1.620     albertel 8018:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8019:                             &GDBM_READER(),0640)) {
1.37      www      8020: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      8021:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      8022:               unless ($ids) { 
                   8023:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      8024:               }
                   8025:               unless ($ids) {
                   8026: # alias?
                   8027: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      8028:               }
1.37      www      8029:               if ($ids) {
                   8030: # ------------------------------------------------------------------- Has ID(s)
                   8031:                  my @possibilities=split(/\,/,$ids);
1.39      www      8032:                  if ($#possibilities==0) {
                   8033: # ----------------------------------------------- There is only one possibility
1.37      www      8034: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 8035: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   8036: 						    $resid,$thisfn);
1.249     www      8037:                  } elsif (!$donotrecurse) {
1.39      www      8038: # ------------------------------------------ There is more than one possibility
                   8039:                      my $realpossible=0;
1.800     albertel 8040:                      foreach my $id (@possibilities) {
                   8041: 			 my $file=$bighash{'src_'.$id};
1.39      www      8042:                          if (&allowed('bre',$file)) {
1.800     albertel 8043:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      8044:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   8045: 				$realpossible++;
1.626     albertel 8046:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   8047: 						    $resid,$thisfn);
1.39      www      8048:                             }
                   8049: 			 }
1.191     harris41 8050:                      }
1.39      www      8051: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      8052:                  } else {
                   8053:                      $syval='';
1.37      www      8054:                  }
                   8055: 	      }
                   8056:               untie(%bighash)
1.481     raeburn  8057:            }
1.31      www      8058:         }
1.62      www      8059:         if ($syval) {
1.620     albertel 8060: 	    return $env{$cache_str}=$syval;
1.62      www      8061:         }
1.31      www      8062:     }
1.949     raeburn  8063:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 8064:     return $env{$cache_str}='';
1.31      www      8065: }
                   8066: 
                   8067: # ---------------------------------------------------------- Return random seed
                   8068: 
1.32      www      8069: sub numval {
                   8070:     my $txt=shift;
                   8071:     $txt=~tr/A-J/0-9/;
                   8072:     $txt=~tr/a-j/0-9/;
                   8073:     $txt=~tr/K-T/0-9/;
                   8074:     $txt=~tr/k-t/0-9/;
                   8075:     $txt=~tr/U-Z/0-5/;
                   8076:     $txt=~tr/u-z/0-5/;
                   8077:     $txt=~s/\D//g;
1.564     albertel 8078:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      8079:     return int($txt);
1.368     albertel 8080: }
                   8081: 
1.484     albertel 8082: sub numval2 {
                   8083:     my $txt=shift;
                   8084:     $txt=~tr/A-J/0-9/;
                   8085:     $txt=~tr/a-j/0-9/;
                   8086:     $txt=~tr/K-T/0-9/;
                   8087:     $txt=~tr/k-t/0-9/;
                   8088:     $txt=~tr/U-Z/0-5/;
                   8089:     $txt=~tr/u-z/0-5/;
                   8090:     $txt=~s/\D//g;
                   8091:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   8092:     my $total;
                   8093:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 8094:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 8095:     return int($total);
                   8096: }
                   8097: 
1.575     albertel 8098: sub numval3 {
                   8099:     use integer;
                   8100:     my $txt=shift;
                   8101:     $txt=~tr/A-J/0-9/;
                   8102:     $txt=~tr/a-j/0-9/;
                   8103:     $txt=~tr/K-T/0-9/;
                   8104:     $txt=~tr/k-t/0-9/;
                   8105:     $txt=~tr/U-Z/0-5/;
                   8106:     $txt=~tr/u-z/0-5/;
                   8107:     $txt=~s/\D//g;
                   8108:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   8109:     my $total;
                   8110:     foreach my $val (@txts) { $total+=$val; }
                   8111:     if ($_64bit) { $total=(($total<<32)>>32); }
                   8112:     return $total;
                   8113: }
                   8114: 
1.675     albertel 8115: sub digest {
                   8116:     my ($data)=@_;
                   8117:     my $digest=&Digest::MD5::md5($data);
                   8118:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   8119:     my ($e,$f);
                   8120:     {
                   8121:         use integer;
                   8122:         $e=($a+$b);
                   8123:         $f=($c+$d);
                   8124:         if ($_64bit) {
                   8125:             $e=(($e<<32)>>32);
                   8126:             $f=(($f<<32)>>32);
                   8127:         }
                   8128:     }
                   8129:     if (wantarray) {
                   8130: 	return ($e,$f);
                   8131:     } else {
                   8132: 	my $g;
                   8133: 	{
                   8134: 	    use integer;
                   8135: 	    $g=($e+$f);
                   8136: 	    if ($_64bit) {
                   8137: 		$g=(($g<<32)>>32);
                   8138: 	    }
                   8139: 	}
                   8140: 	return $g;
                   8141:     }
                   8142: }
                   8143: 
1.368     albertel 8144: sub latest_rnd_algorithm_id {
1.675     albertel 8145:     return '64bit5';
1.366     albertel 8146: }
1.32      www      8147: 
1.503     albertel 8148: sub get_rand_alg {
                   8149:     my ($courseid)=@_;
1.790     albertel 8150:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 8151:     if ($courseid) {
1.620     albertel 8152: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 8153:     }
                   8154:     return &latest_rnd_algorithm_id();
                   8155: }
                   8156: 
1.562     albertel 8157: sub validCODE {
                   8158:     my ($CODE)=@_;
                   8159:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   8160:     return 0;
                   8161: }
                   8162: 
1.491     albertel 8163: sub getCODE {
1.620     albertel 8164:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 8165:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   8166: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   8167: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 8168: 	return $Apache::lonhomework::history{'resource.CODE'};
                   8169:     }
                   8170:     return undef;
                   8171: }
                   8172: 
1.31      www      8173: sub rndseed {
1.155     albertel 8174:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 8175:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 8176:     if (!defined($symb)) {
1.366     albertel 8177: 	unless ($symb=$wsymb) { return time; }
                   8178:     }
                   8179:     if (!$courseid) { $courseid=$wcourseid; }
                   8180:     if (!$domain) { $domain=$wdomain; }
                   8181:     if (!$username) { $username=$wusername }
1.503     albertel 8182:     my $which=&get_rand_alg();
1.803     albertel 8183: 
1.491     albertel 8184:     if (defined(&getCODE())) {
1.675     albertel 8185: 	if ($which eq '64bit5') {
                   8186: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   8187: 	} elsif ($which eq '64bit4') {
1.575     albertel 8188: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   8189: 	} else {
                   8190: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   8191: 	}
1.675     albertel 8192:     } elsif ($which eq '64bit5') {
                   8193: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 8194:     } elsif ($which eq '64bit4') {
                   8195: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 8196:     } elsif ($which eq '64bit3') {
                   8197: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 8198:     } elsif ($which eq '64bit2') {
                   8199: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 8200:     } elsif ($which eq '64bit') {
                   8201: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   8202:     }
                   8203:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   8204: }
                   8205: 
                   8206: sub rndseed_32bit {
                   8207:     my ($symb,$courseid,$domain,$username)=@_;
                   8208:     {
                   8209: 	use integer;
                   8210: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   8211: 	my $symbseed=numval($symb) << 22;
                   8212: 	my $namechck=unpack("%32C*",$username) << 17;
                   8213: 	my $nameseed=numval($username) << 12;
                   8214: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   8215: 	my $courseseed=unpack("%32C*",$courseid);
                   8216: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 8217: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8218: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8219: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 8220: 	return $num;
                   8221:     }
                   8222: }
                   8223: 
                   8224: sub rndseed_64bit {
                   8225:     my ($symb,$courseid,$domain,$username)=@_;
                   8226:     {
                   8227: 	use integer;
                   8228: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   8229: 	my $symbseed=numval($symb) << 10;
                   8230: 	my $namechck=unpack("%32S*",$username);
                   8231: 	
                   8232: 	my $nameseed=numval($username) << 21;
                   8233: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   8234: 	my $courseseed=unpack("%32S*",$courseid);
                   8235: 	
                   8236: 	my $num1=$symbchck+$symbseed+$namechck;
                   8237: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8238: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8239: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8240: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 8241: 	return "$num1,$num2";
1.155     albertel 8242:     }
1.366     albertel 8243: }
                   8244: 
1.443     albertel 8245: sub rndseed_64bit2 {
                   8246:     my ($symb,$courseid,$domain,$username)=@_;
                   8247:     {
                   8248: 	use integer;
                   8249: 	# strings need to be an even # of cahracters long, it it is odd the
                   8250:         # last characters gets thrown away
                   8251: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8252: 	my $symbseed=numval($symb) << 10;
                   8253: 	my $namechck=unpack("%32S*",$username.' ');
                   8254: 	
                   8255: 	my $nameseed=numval($username) << 21;
1.501     albertel 8256: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8257: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8258: 	
                   8259: 	my $num1=$symbchck+$symbseed+$namechck;
                   8260: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8261: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8262: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 8263: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 8264: 	return "$num1,$num2";
                   8265:     }
                   8266: }
                   8267: 
                   8268: sub rndseed_64bit3 {
                   8269:     my ($symb,$courseid,$domain,$username)=@_;
                   8270:     {
                   8271: 	use integer;
                   8272: 	# strings need to be an even # of cahracters long, it it is odd the
                   8273:         # last characters gets thrown away
                   8274: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8275: 	my $symbseed=numval2($symb) << 10;
                   8276: 	my $namechck=unpack("%32S*",$username.' ');
                   8277: 	
                   8278: 	my $nameseed=numval2($username) << 21;
1.443     albertel 8279: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8280: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8281: 	
                   8282: 	my $num1=$symbchck+$symbseed+$namechck;
                   8283: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8284: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8285: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 8286: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8287: 	
1.503     albertel 8288: 	return "$num1:$num2";
1.443     albertel 8289:     }
                   8290: }
                   8291: 
1.575     albertel 8292: sub rndseed_64bit4 {
                   8293:     my ($symb,$courseid,$domain,$username)=@_;
                   8294:     {
                   8295: 	use integer;
                   8296: 	# strings need to be an even # of cahracters long, it it is odd the
                   8297:         # last characters gets thrown away
                   8298: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8299: 	my $symbseed=numval3($symb) << 10;
                   8300: 	my $namechck=unpack("%32S*",$username.' ');
                   8301: 	
                   8302: 	my $nameseed=numval3($username) << 21;
                   8303: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8304: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8305: 	
                   8306: 	my $num1=$symbchck+$symbseed+$namechck;
                   8307: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8308: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8309: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 8310: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8311: 	
                   8312: 	return "$num1:$num2";
                   8313:     }
                   8314: }
                   8315: 
1.675     albertel 8316: sub rndseed_64bit5 {
                   8317:     my ($symb,$courseid,$domain,$username)=@_;
                   8318:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   8319:     return "$num1:$num2";
                   8320: }
                   8321: 
1.366     albertel 8322: sub rndseed_CODE_64bit {
                   8323:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 8324:     {
1.366     albertel 8325: 	use integer;
1.443     albertel 8326: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 8327: 	my $symbseed=numval2($symb);
1.491     albertel 8328: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8329: 	my $CODEseed=numval(&getCODE());
1.443     albertel 8330: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 8331: 	my $num1=$symbseed+$CODEchck;
                   8332: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8333: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8334: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 8335: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8336: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 8337: 	return "$num1:$num2";
1.366     albertel 8338:     }
                   8339: }
                   8340: 
1.575     albertel 8341: sub rndseed_CODE_64bit4 {
                   8342:     my ($symb,$courseid,$domain,$username)=@_;
                   8343:     {
                   8344: 	use integer;
                   8345: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   8346: 	my $symbseed=numval3($symb);
                   8347: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8348: 	my $CODEseed=numval3(&getCODE());
                   8349: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8350: 	my $num1=$symbseed+$CODEchck;
                   8351: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8352: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8353: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 8354: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8355: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   8356: 	return "$num1:$num2";
                   8357:     }
                   8358: }
                   8359: 
1.675     albertel 8360: sub rndseed_CODE_64bit5 {
                   8361:     my ($symb,$courseid,$domain,$username)=@_;
                   8362:     my $code = &getCODE();
                   8363:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   8364:     return "$num1:$num2";
                   8365: }
                   8366: 
1.366     albertel 8367: sub setup_random_from_rndseed {
                   8368:     my ($rndseed)=@_;
1.503     albertel 8369:     if ($rndseed =~/([,:])/) {
                   8370: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 8371: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   8372:     } else {
                   8373: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 8374:     }
1.36      albertel 8375: }
                   8376: 
1.474     albertel 8377: sub latest_receipt_algorithm_id {
1.835     albertel 8378:     return 'receipt3';
1.474     albertel 8379: }
                   8380: 
1.480     www      8381: sub recunique {
                   8382:     my $fucourseid=shift;
                   8383:     my $unique;
1.835     albertel 8384:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   8385: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8386: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      8387:     } else {
                   8388: 	$unique=$perlvar{'lonReceipt'};
                   8389:     }
                   8390:     return unpack("%32C*",$unique);
                   8391: }
                   8392: 
                   8393: sub recprefix {
                   8394:     my $fucourseid=shift;
                   8395:     my $prefix;
1.835     albertel 8396:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   8397: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8398: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      8399:     } else {
                   8400: 	$prefix=$perlvar{'lonHostID'};
                   8401:     }
                   8402:     return unpack("%32C*",$prefix);
                   8403: }
                   8404: 
1.76      www      8405: sub ireceipt {
1.474     albertel 8406:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 8407: 
                   8408:     my $return =&recprefix($fucourseid).'-';
                   8409: 
                   8410:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   8411: 	$env{'request.state'} eq 'construct') {
                   8412: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   8413: 	return $return;
                   8414:     }
                   8415: 
1.76      www      8416:     my $cuname=unpack("%32C*",$funame);
                   8417:     my $cudom=unpack("%32C*",$fudom);
                   8418:     my $cucourseid=unpack("%32C*",$fucourseid);
                   8419:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      8420:     my $cunique=&recunique($fucourseid);
1.474     albertel 8421:     my $cpart=unpack("%32S*",$part);
1.835     albertel 8422:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   8423: 
1.790     albertel 8424: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 8425: 			       
                   8426: 	$return.= ($cunique%$cuname+
                   8427: 		   $cunique%$cudom+
                   8428: 		   $cusymb%$cuname+
                   8429: 		   $cusymb%$cudom+
                   8430: 		   $cucourseid%$cuname+
                   8431: 		   $cucourseid%$cudom+
                   8432: 		   $cpart%$cuname+
                   8433: 		   $cpart%$cudom);
                   8434:     } else {
                   8435: 	$return.= ($cunique%$cuname+
                   8436: 		   $cunique%$cudom+
                   8437: 		   $cusymb%$cuname+
                   8438: 		   $cusymb%$cudom+
                   8439: 		   $cucourseid%$cuname+
                   8440: 		   $cucourseid%$cudom);
                   8441:     }
                   8442:     return $return;
1.76      www      8443: }
                   8444: 
                   8445: sub receipt {
1.474     albertel 8446:     my ($part)=@_;
1.790     albertel 8447:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 8448:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      8449: }
1.260     ng       8450: 
1.790     albertel 8451: sub whichuser {
                   8452:     my ($passedsymb)=@_;
                   8453:     my ($symb,$courseid,$domain,$name,$publicuser);
                   8454:     if (defined($env{'form.grade_symb'})) {
                   8455: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   8456: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   8457: 	if (!$allowed &&
                   8458: 	    exists($env{'request.course.sec'}) &&
                   8459: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   8460: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   8461: 			      '/'.$env{'request.course.sec'});
                   8462: 	}
                   8463: 	if ($allowed) {
                   8464: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   8465: 	    $courseid=$tmp_courseid;
                   8466: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   8467: 	    ($name)=&get_env_multiple('form.grade_username');
                   8468: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   8469: 	}
                   8470:     }
                   8471:     if (!$passedsymb) {
                   8472: 	$symb=&symbread();
                   8473:     } else {
                   8474: 	$symb=$passedsymb;
                   8475:     }
                   8476:     $courseid=$env{'request.course.id'};
                   8477:     $domain=$env{'user.domain'};
                   8478:     $name=$env{'user.name'};
                   8479:     if ($name eq 'public' && $domain eq 'public') {
                   8480: 	if (!defined($env{'form.username'})) {
                   8481: 	    $env{'form.username'}.=time.rand(10000000);
                   8482: 	}
                   8483: 	$name.=$env{'form.username'};
                   8484:     }
                   8485:     return ($symb,$courseid,$domain,$name,$publicuser);
                   8486: 
                   8487: }
                   8488: 
1.36      albertel 8489: # ------------------------------------------------------------ Serves up a file
1.472     albertel 8490: # returns either the contents of the file or 
                   8491: # -1 if the file doesn't exist
1.481     raeburn  8492: #
                   8493: # if the target is a file that was uploaded via DOCS, 
                   8494: # a check will be made to see if a current copy exists on the local server,
                   8495: # if it does this will be served, otherwise a copy will be retrieved from
                   8496: # the home server for the course and stored in /home/httpd/html/userfiles on
                   8497: # the local server.   
1.472     albertel 8498: 
1.36      albertel 8499: sub getfile {
1.538     albertel 8500:     my ($file) = @_;
1.609     banghart 8501:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 8502:     &repcopy($file);
                   8503:     return &readfile($file);
                   8504: }
                   8505: 
                   8506: sub repcopy_userfile {
                   8507:     my ($file)=@_;
1.609     banghart 8508:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 8509:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 8510:     my ($cdom,$cnum,$filename) = 
1.811     albertel 8511: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 8512:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   8513:     if (-e "$file") {
1.828     www      8514: # we already have a local copy, check it out
1.538     albertel 8515: 	my @fileinfo = stat($file);
1.828     www      8516: 	my $rtncode;
                   8517: 	my $info;
1.538     albertel 8518: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 8519: 	if ($lwpresp ne 'ok') {
1.828     www      8520: # there is no such file anymore, even though we had a local copy
1.482     albertel 8521: 	    if ($rtncode eq '404') {
1.538     albertel 8522: 		unlink($file);
1.482     albertel 8523: 	    }
                   8524: 	    return -1;
                   8525: 	}
                   8526: 	if ($info < $fileinfo[9]) {
1.828     www      8527: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  8528: 	    return 'ok';
1.828     www      8529: 	} else {
                   8530: # the file is outdated, get rid of it
                   8531: 	    unlink($file);
1.482     albertel 8532: 	}
1.828     www      8533:     }
                   8534: # one way or the other, at this point, we don't have the file
                   8535: # construct the correct path for the file
                   8536:     my @parts = ($cdom,$cnum); 
                   8537:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   8538: 	push @parts, split(/\//,$1);
                   8539:     }
                   8540:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   8541:     foreach my $part (@parts) {
                   8542: 	$path .= '/'.$part;
                   8543: 	if (!-e $path) {
                   8544: 	    mkdir($path,0770);
1.482     albertel 8545: 	}
                   8546:     }
1.828     www      8547: # now the path exists for sure
                   8548: # get a user agent
                   8549:     my $ua=new LWP::UserAgent;
                   8550:     my $transferfile=$file.'.in.transfer';
                   8551: # FIXME: this should flock
                   8552:     if (-e $transferfile) { return 'ok'; }
                   8553:     my $request;
                   8554:     $uri=~s/^\///;
1.980     raeburn  8555:     my $homeserver = &homeserver($cnum,$cdom);
                   8556:     my $protocol = $protocol{$homeserver};
                   8557:     $protocol = 'http' if ($protocol ne 'https');
                   8558:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      8559:     my $response=$ua->request($request,$transferfile);
                   8560: # did it work?
                   8561:     if ($response->is_error()) {
                   8562: 	unlink($transferfile);
                   8563: 	&logthis("Userfile repcopy failed for $uri");
                   8564: 	return -1;
                   8565:     }
                   8566: # worked, rename the transfer file
                   8567:     rename($transferfile,$file);
1.607     raeburn  8568:     return 'ok';
1.481     raeburn  8569: }
                   8570: 
1.517     albertel 8571: sub tokenwrapper {
                   8572:     my $uri=shift;
1.980     raeburn  8573:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 8574:     $uri=~s|^/||;
1.620     albertel 8575:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8576:     my $token=$1;
1.552     albertel 8577:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8578:     if ($udom && $uname && $file) {
                   8579: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8580:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  8581:         my $homeserver = &homeserver($uname,$udom);
                   8582:         my $protocol = $protocol{$homeserver};
                   8583:         $protocol = 'http' if ($protocol ne 'https');
                   8584:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 8585:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8586:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8587:     } else {
                   8588:         return '/adm/notfound.html';
                   8589:     }
                   8590: }
                   8591: 
1.828     www      8592: # call with reqtype HEAD: get last modification time
                   8593: # call with reqtype GET: get the file contents
                   8594: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8595: #
1.481     raeburn  8596: sub getuploaded {
                   8597:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8598:     $uri=~s/^\///;
1.980     raeburn  8599:     my $homeserver = &homeserver($cnum,$cdom);
                   8600:     my $protocol = $protocol{$homeserver};
                   8601:     $protocol = 'http' if ($protocol ne 'https');
                   8602:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  8603:     my $ua=new LWP::UserAgent;
                   8604:     my $request=new HTTP::Request($reqtype,$uri);
                   8605:     my $response=$ua->request($request);
                   8606:     $$rtncode = $response->code;
1.482     albertel 8607:     if (! $response->is_success()) {
                   8608: 	return 'failed';
                   8609:     }      
                   8610:     if ($reqtype eq 'HEAD') {
1.486     www      8611: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8612:     } elsif ($reqtype eq 'GET') {
                   8613: 	$$info = $response->content;
1.472     albertel 8614:     }
1.482     albertel 8615:     return 'ok';
1.36      albertel 8616: }
                   8617: 
1.481     raeburn  8618: sub readfile {
                   8619:     my $file = shift;
                   8620:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8621:     my $fh;
                   8622:     open($fh,"<$file");
                   8623:     my $a='';
1.800     albertel 8624:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8625:     return $a;
                   8626: }
                   8627: 
1.36      albertel 8628: sub filelocation {
1.590     banghart 8629:     my ($dir,$file) = @_;
                   8630:     my $location;
                   8631:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8632: 
                   8633:     if ($file =~ m-^/adm/-) {
                   8634: 	$file=~s-^/adm/wrapper/-/-;
                   8635: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8636:     }
1.882     albertel 8637: 
1.590     banghart 8638:     if ($file=~m:^/~:) { # is a contruction space reference
                   8639:         $location = $file;
                   8640:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8641:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8642: 	# is a correct contruction space reference
                   8643:         $location = $file;
1.956     raeburn  8644:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   8645:         $location = $file;
1.609     banghart 8646:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8647:         my ($udom,$uname,$filename)=
1.811     albertel 8648:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8649:         my $home=&homeserver($uname,$udom);
                   8650:         my $is_me=0;
                   8651:         my @ids=&current_machine_ids();
                   8652:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8653:         if ($is_me) {
1.955     raeburn  8654:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 8655:         } else {
                   8656:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8657:   	      $udom.'/'.$uname.'/'.$filename;
                   8658:         }
1.882     albertel 8659:     } elsif ($file =~ m-^/adm/-) {
                   8660: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8661:     } else {
                   8662:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8663:         $file=~s:^/res/:/:;
                   8664:         if ( !( $file =~ m:^/:) ) {
                   8665:             $location = $dir. '/'.$file;
                   8666:         } else {
                   8667:             $location = '/home/httpd/html/res'.$file;
                   8668:         }
1.59      albertel 8669:     }
1.590     banghart 8670:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8671:     while ($location=~m{/\.\./}) {
                   8672: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8673: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8674: 	} else {
                   8675: 	    $location=~ s{/\.\./}{/}g;
                   8676: 	}
                   8677:     } #remove dir/..
1.590     banghart 8678:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8679:     return $location;
1.46      www      8680: }
1.36      albertel 8681: 
1.46      www      8682: sub hreflocation {
                   8683:     my ($dir,$file)=@_;
1.980     raeburn  8684:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 8685: 	$file=filelocation($dir,$file);
1.700     albertel 8686:     } elsif ($file=~m-^/adm/-) {
                   8687: 	$file=~s-^/adm/wrapper/-/-;
                   8688: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8689:     }
                   8690:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8691: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8692:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8693: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8694:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8695: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8696: 	    -/uploaded/$1/$2/-x;
1.46      www      8697:     }
1.913     albertel 8698:     if ($file=~ m{^/userfiles/}) {
                   8699: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8700:     }
1.462     albertel 8701:     return $file;
1.465     albertel 8702: }
                   8703: 
                   8704: sub current_machine_domains {
1.853     albertel 8705:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8706: }
                   8707: 
                   8708: sub machine_domains {
                   8709:     my ($hostname) = @_;
1.465     albertel 8710:     my @domains;
1.838     albertel 8711:     my %hostname = &all_hostnames();
1.465     albertel 8712:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8713: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8714: 	if ($hostname eq $name) {
1.844     albertel 8715: 	    push(@domains,&host_domain($id));
1.465     albertel 8716: 	}
                   8717:     }
                   8718:     return @domains;
                   8719: }
                   8720: 
                   8721: sub current_machine_ids {
1.853     albertel 8722:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8723: }
                   8724: 
                   8725: sub machine_ids {
                   8726:     my ($hostname) = @_;
                   8727:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8728:     my @ids;
1.888     albertel 8729:     my %name_to_host = &all_names();
1.889     albertel 8730:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8731: 	return @{ $name_to_host{$hostname} };
                   8732:     }
                   8733:     return;
1.31      www      8734: }
                   8735: 
1.824     raeburn  8736: sub additional_machine_domains {
                   8737:     my @domains;
                   8738:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8739:     while( my $line = <$fh>) {
                   8740:         $line =~ s/\s//g;
                   8741:         push(@domains,$line);
                   8742:     }
                   8743:     return @domains;
                   8744: }
                   8745: 
                   8746: sub default_login_domain {
                   8747:     my $domain = $perlvar{'lonDefDomain'};
                   8748:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8749:     foreach my $posdom (&current_machine_domains(),
                   8750:                         &additional_machine_domains()) {
                   8751:         if (lc($posdom) eq lc($testdomain)) {
                   8752:             $domain=$posdom;
                   8753:             last;
                   8754:         }
                   8755:     }
                   8756:     return $domain;
                   8757: }
                   8758: 
1.31      www      8759: # ------------------------------------------------------------- Declutters URLs
                   8760: 
                   8761: sub declutter {
                   8762:     my $thisfn=shift;
1.569     albertel 8763:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8764:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8765:     $thisfn=~s/^\///;
1.697     albertel 8766:     $thisfn=~s|^adm/wrapper/||;
                   8767:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8768:     $thisfn=~s/^res\///;
1.235     www      8769:     $thisfn=~s/\?.+$//;
1.268     www      8770:     return $thisfn;
                   8771: }
                   8772: 
                   8773: # ------------------------------------------------------------- Clutter up URLs
                   8774: 
                   8775: sub clutter {
                   8776:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8777:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8778: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8779:        $thisfn='/res'.$thisfn; 
                   8780:     }
1.694     albertel 8781:     if ($thisfn !~m|/adm|) {
1.695     albertel 8782: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8783: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8784: 	} else {
                   8785: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8786: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8787: 	    if ($embstyle eq 'ssi'
                   8788: 		|| ($embstyle eq 'hdn')
                   8789: 		|| ($embstyle eq 'rat')
                   8790: 		|| ($embstyle eq 'prv')
                   8791: 		|| ($embstyle eq 'ign')) {
                   8792: 		#do nothing with these
                   8793: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8794: 		|| ($embstyle eq 'emb')
                   8795: 		|| ($embstyle eq 'wrp')) {
                   8796: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8797: 	    } elsif ($embstyle eq 'unk'
                   8798: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8799: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8800: 	    } else {
1.718     www      8801: #		&logthis("Got a blank emb style");
1.695     albertel 8802: 	    }
1.694     albertel 8803: 	}
                   8804:     }
1.31      www      8805:     return $thisfn;
1.12      www      8806: }
                   8807: 
1.787     albertel 8808: sub clutter_with_no_wrapper {
                   8809:     my $uri = &clutter(shift);
                   8810:     if ($uri =~ m-^/adm/-) {
                   8811: 	$uri =~ s-^/adm/wrapper/-/-;
                   8812: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8813:     }
                   8814:     return $uri;
                   8815: }
                   8816: 
1.557     albertel 8817: sub freeze_escape {
                   8818:     my ($value)=@_;
                   8819:     if (ref($value)) {
                   8820: 	$value=&nfreeze($value);
                   8821: 	return '__FROZEN__'.&escape($value);
                   8822:     }
                   8823:     return &escape($value);
                   8824: }
                   8825: 
1.11      www      8826: 
1.557     albertel 8827: sub thaw_unescape {
                   8828:     my ($value)=@_;
                   8829:     if ($value =~ /^__FROZEN__/) {
                   8830: 	substr($value,0,10,undef);
                   8831: 	$value=&unescape($value);
                   8832: 	return &thaw($value);
                   8833:     }
                   8834:     return &unescape($value);
                   8835: }
                   8836: 
1.436     albertel 8837: sub correct_line_ends {
                   8838:     my ($result)=@_;
                   8839:     $$result =~s/\r\n/\n/mg;
                   8840:     $$result =~s/\r/\n/mg;
1.415     albertel 8841: }
1.1       albertel 8842: # ================================================================ Main Program
                   8843: 
1.184     www      8844: sub goodbye {
1.204     albertel 8845:    &logthis("Starting Shut down");
1.443     albertel 8846: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8847:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8848: #converted
1.599     albertel 8849: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8850:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8851: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8852: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8853: #1.1 only
1.870     albertel 8854: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8855: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8856: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8857: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8858:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8859:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8860:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8861:    &flushcourselogs();
                   8862:    &logthis("Shutting down");
                   8863: }
                   8864: 
1.852     albertel 8865: sub get_dns {
1.869     albertel 8866:     my ($url,$func,$ignore_cache) = @_;
                   8867:     if (!$ignore_cache) {
                   8868: 	my ($content,$cached)=
                   8869: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8870: 	if ($cached) {
                   8871: 	    &$func($content);
                   8872: 	    return;
                   8873: 	}
                   8874:     }
                   8875: 
                   8876:     my %alldns;
1.852     albertel 8877:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8878:     foreach my $dns (<$config>) {
                   8879: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  8880:         my $line = $1;
                   8881:         my ($host,$protocol) = split(/:/,$line);
                   8882:         if ($protocol ne 'https') {
                   8883:             $protocol = 'http';
                   8884:         }
                   8885: 	$alldns{$host} = $protocol;
1.869     albertel 8886:     }
                   8887:     while (%alldns) {
                   8888: 	my ($dns) = keys(%alldns);
1.852     albertel 8889: 	my $ua=new LWP::UserAgent;
1.979     raeburn  8890: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 8891: 	my $response=$ua->request($request);
1.979     raeburn  8892:         delete($alldns{$dns});
1.852     albertel 8893: 	next if ($response->is_error());
                   8894: 	my @content = split("\n",$response->content);
1.869     albertel 8895: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8896: 	&$func(\@content);
1.869     albertel 8897: 	return;
1.852     albertel 8898:     }
                   8899:     close($config);
1.871     albertel 8900:     my $which = (split('/',$url))[3];
                   8901:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8902:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8903:     my @content = <$config>;
                   8904:     &$func(\@content);
                   8905:     return;
1.852     albertel 8906: }
1.327     albertel 8907: # ------------------------------------------------------------ Read domain file
                   8908: {
1.852     albertel 8909:     my $loaded;
1.846     albertel 8910:     my %domain;
                   8911: 
1.852     albertel 8912:     sub parse_domain_tab {
                   8913: 	my ($lines) = @_;
                   8914: 	foreach my $line (@$lines) {
                   8915: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8916: 
1.846     albertel 8917: 	    chomp($line);
1.852     albertel 8918: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8919: 	    my %this_domain;
                   8920: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8921: 			       'lang_def', 'city', 'longi', 'lati',
                   8922: 			       'primary') {
                   8923: 		$this_domain{$field} = shift(@elements);
                   8924: 	    }
                   8925: 	    $domain{$name} = \%this_domain;
1.852     albertel 8926: 	}
                   8927:     }
1.864     albertel 8928: 
                   8929:     sub reset_domain_info {
                   8930: 	undef($loaded);
                   8931: 	undef(%domain);
                   8932:     }
                   8933: 
1.852     albertel 8934:     sub load_domain_tab {
1.869     albertel 8935: 	my ($ignore_cache) = @_;
                   8936: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8937: 	my $fh;
                   8938: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8939: 	    my @lines = <$fh>;
                   8940: 	    &parse_domain_tab(\@lines);
1.448     albertel 8941: 	}
1.852     albertel 8942: 	close($fh);
                   8943: 	$loaded = 1;
1.327     albertel 8944:     }
1.846     albertel 8945: 
                   8946:     sub domain {
1.852     albertel 8947: 	&load_domain_tab() if (!$loaded);
                   8948: 
1.846     albertel 8949: 	my ($name,$what) = @_;
                   8950: 	return if ( !exists($domain{$name}) );
                   8951: 
                   8952: 	if (!$what) {
                   8953: 	    return $domain{$name}{'description'};
                   8954: 	}
                   8955: 	return $domain{$name}{$what};
                   8956:     }
1.974     raeburn  8957: 
                   8958:     sub domain_info {
                   8959:         &load_domain_tab() if (!$loaded);
                   8960:         return %domain;
                   8961:     }
                   8962: 
1.327     albertel 8963: }
                   8964: 
                   8965: 
1.1       albertel 8966: # ------------------------------------------------------------- Read hosts file
                   8967: {
1.838     albertel 8968:     my %hostname;
1.844     albertel 8969:     my %hostdom;
1.845     albertel 8970:     my %libserv;
1.852     albertel 8971:     my $loaded;
1.888     albertel 8972:     my %name_to_host;
1.852     albertel 8973: 
                   8974:     sub parse_hosts_tab {
                   8975: 	my ($file) = @_;
                   8976: 	foreach my $configline (@$file) {
                   8977: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8978: 	    next if ($configline =~ /^\^/);
                   8979: 	    chomp($configline);
1.968     raeburn  8980: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852     albertel 8981: 	    $name=~s/\s//g;
                   8982: 	    if ($id && $domain && $role && $name) {
                   8983: 		$hostname{$id}=$name;
1.888     albertel 8984: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8985: 		$hostdom{$id}=$domain;
                   8986: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  8987:                 if (defined($protocol)) {
                   8988:                     if ($protocol eq 'https') {
                   8989:                         $protocol{$id} = $protocol;
                   8990:                     } else {
                   8991:                         $protocol{$id} = 'http'; 
                   8992:                     }
1.968     raeburn  8993:                 } else {
1.969     raeburn  8994:                     $protocol{$id} = 'http';
1.968     raeburn  8995:                 }
1.852     albertel 8996: 	    }
                   8997: 	}
                   8998:     }
1.864     albertel 8999:     
                   9000:     sub reset_hosts_info {
1.897     albertel 9001: 	&purge_remembered();
1.864     albertel 9002: 	&reset_domain_info();
                   9003: 	&reset_hosts_ip_info();
1.892     albertel 9004: 	undef(%name_to_host);
1.864     albertel 9005: 	undef(%hostname);
                   9006: 	undef(%hostdom);
                   9007: 	undef(%libserv);
                   9008: 	undef($loaded);
                   9009:     }
1.1       albertel 9010: 
1.852     albertel 9011:     sub load_hosts_tab {
1.869     albertel 9012: 	my ($ignore_cache) = @_;
                   9013: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 9014: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9015: 	my @config = <$config>;
                   9016: 	&parse_hosts_tab(\@config);
                   9017: 	close($config);
                   9018: 	$loaded=1;
1.1       albertel 9019:     }
1.852     albertel 9020: 
1.838     albertel 9021:     sub hostname {
1.852     albertel 9022: 	&load_hosts_tab() if (!$loaded);
                   9023: 
1.838     albertel 9024: 	my ($lonid) = @_;
                   9025: 	return $hostname{$lonid};
                   9026:     }
1.845     albertel 9027: 
1.838     albertel 9028:     sub all_hostnames {
1.852     albertel 9029: 	&load_hosts_tab() if (!$loaded);
                   9030: 
1.838     albertel 9031: 	return %hostname;
                   9032:     }
1.845     albertel 9033: 
1.888     albertel 9034:     sub all_names {
                   9035: 	&load_hosts_tab() if (!$loaded);
                   9036: 
                   9037: 	return %name_to_host;
                   9038:     }
                   9039: 
1.974     raeburn  9040:     sub all_host_domain {
                   9041:         &load_hosts_tab() if (!$loaded);
                   9042:         return %hostdom;
                   9043:     }
                   9044: 
1.845     albertel 9045:     sub is_library {
1.852     albertel 9046: 	&load_hosts_tab() if (!$loaded);
                   9047: 
1.845     albertel 9048: 	return exists($libserv{$_[0]});
                   9049:     }
                   9050: 
                   9051:     sub all_library {
1.852     albertel 9052: 	&load_hosts_tab() if (!$loaded);
                   9053: 
1.845     albertel 9054: 	return %libserv;
                   9055:     }
                   9056: 
1.841     albertel 9057:     sub get_servers {
1.852     albertel 9058: 	&load_hosts_tab() if (!$loaded);
                   9059: 
1.841     albertel 9060: 	my ($domain,$type) = @_;
                   9061: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   9062: 	                                          : %hostname;
                   9063: 	my %result;
1.842     albertel 9064: 	if (ref($domain) eq 'ARRAY') {
                   9065: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 9066: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 9067: 		    $result{$host} = $hostname;
                   9068: 		}
                   9069: 	    }
                   9070: 	} else {
                   9071: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   9072: 		if ($hostdom{$host} eq $domain) {
                   9073: 		    $result{$host} = $hostname;
                   9074: 		}
1.841     albertel 9075: 	    }
                   9076: 	}
                   9077: 	return %result;
                   9078:     }
1.845     albertel 9079: 
1.844     albertel 9080:     sub host_domain {
1.852     albertel 9081: 	&load_hosts_tab() if (!$loaded);
                   9082: 
1.844     albertel 9083: 	my ($lonid) = @_;
                   9084: 	return $hostdom{$lonid};
                   9085:     }
                   9086: 
1.841     albertel 9087:     sub all_domains {
1.852     albertel 9088: 	&load_hosts_tab() if (!$loaded);
                   9089: 
1.841     albertel 9090: 	my %seen;
                   9091: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   9092: 	return @uniq;
                   9093:     }
1.1       albertel 9094: }
                   9095: 
1.847     albertel 9096: { 
                   9097:     my %iphost;
1.856     albertel 9098:     my %name_to_ip;
                   9099:     my %lonid_to_ip;
1.869     albertel 9100: 
1.847     albertel 9101:     sub get_hosts_from_ip {
                   9102: 	my ($ip) = @_;
                   9103: 	my %iphosts = &get_iphost();
                   9104: 	if (ref($iphosts{$ip})) {
                   9105: 	    return @{$iphosts{$ip}};
                   9106: 	}
                   9107: 	return;
1.839     albertel 9108:     }
1.864     albertel 9109:     
                   9110:     sub reset_hosts_ip_info {
                   9111: 	undef(%iphost);
                   9112: 	undef(%name_to_ip);
                   9113: 	undef(%lonid_to_ip);
                   9114:     }
1.856     albertel 9115: 
                   9116:     sub get_host_ip {
                   9117: 	my ($lonid) = @_;
                   9118: 	if (exists($lonid_to_ip{$lonid})) {
                   9119: 	    return $lonid_to_ip{$lonid};
                   9120: 	}
                   9121: 	my $name=&hostname($lonid);
                   9122:    	my $ip = gethostbyname($name);
                   9123: 	return if (!$ip || length($ip) ne 4);
                   9124: 	$ip=inet_ntoa($ip);
                   9125: 	$name_to_ip{$name}   = $ip;
                   9126: 	$lonid_to_ip{$lonid} = $ip;
                   9127: 	return $ip;
                   9128:     }
1.847     albertel 9129:     
                   9130:     sub get_iphost {
1.869     albertel 9131: 	my ($ignore_cache) = @_;
1.894     albertel 9132: 
1.869     albertel 9133: 	if (!$ignore_cache) {
                   9134: 	    if (%iphost) {
                   9135: 		return %iphost;
                   9136: 	    }
                   9137: 	    my ($ip_info,$cached)=
                   9138: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   9139: 	    if ($cached) {
                   9140: 		%iphost      = %{$ip_info->[0]};
                   9141: 		%name_to_ip  = %{$ip_info->[1]};
                   9142: 		%lonid_to_ip = %{$ip_info->[2]};
                   9143: 		return %iphost;
                   9144: 	    }
                   9145: 	}
1.894     albertel 9146: 
                   9147: 	# get yesterday's info for fallback
                   9148: 	my %old_name_to_ip;
                   9149: 	my ($ip_info,$cached)=
                   9150: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   9151: 	if ($cached) {
                   9152: 	    %old_name_to_ip = %{$ip_info->[1]};
                   9153: 	}
                   9154: 
1.888     albertel 9155: 	my %name_to_host = &all_names();
                   9156: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 9157: 	    my $ip;
                   9158: 	    if (!exists($name_to_ip{$name})) {
                   9159: 		$ip = gethostbyname($name);
                   9160: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 9161: 		    if (defined($old_name_to_ip{$name})) {
                   9162: 			$ip = $old_name_to_ip{$name};
                   9163: 			&logthis("Can't find $name defaulting to old $ip");
                   9164: 		    } else {
                   9165: 			&logthis("Name $name no IP found");
                   9166: 			next;
                   9167: 		    }
                   9168: 		} else {
                   9169: 		    $ip=inet_ntoa($ip);
1.847     albertel 9170: 		}
                   9171: 		$name_to_ip{$name} = $ip;
                   9172: 	    } else {
                   9173: 		$ip = $name_to_ip{$name};
1.653     albertel 9174: 	    }
1.888     albertel 9175: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   9176: 		$lonid_to_ip{$id} = $ip;
                   9177: 	    }
                   9178: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 9179: 	}
1.869     albertel 9180: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   9181: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 9182: 				      48*60*60);
1.869     albertel 9183: 
1.847     albertel 9184: 	return %iphost;
1.598     albertel 9185:     }
                   9186: 
1.992     raeburn  9187:     #
                   9188:     #  Given a DNS returns the loncapa host name for that DNS 
                   9189:     # 
                   9190:     sub host_from_dns {
                   9191:         my ($dns) = @_;
                   9192:         my @hosts;
                   9193:         my $ip;
                   9194: 
1.993     raeburn  9195:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  9196:             $ip = $name_to_ip{$dns};
                   9197:         }
                   9198:         if (!$ip) {
                   9199:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   9200:             if (length($ip) == 4) { 
                   9201: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   9202:             }
                   9203:         }
                   9204:         if ($ip) {
                   9205: 	    @hosts = get_hosts_from_ip($ip);
                   9206: 	    return $hosts[0];
                   9207:         }
                   9208:         return undef;
1.986     foxr     9209:     }
1.992     raeburn  9210: 
1.986     foxr     9211: }
                   9212: 
1.862     albertel 9213: BEGIN {
                   9214: 
                   9215: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   9216:     unless ($readit) {
                   9217: {
                   9218:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   9219:     %perlvar = (%perlvar,%{$configvars});
                   9220: }
                   9221: 
                   9222: 
1.1       albertel 9223: # ------------------------------------------------------ Read spare server file
                   9224: {
1.448     albertel 9225:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 9226: 
                   9227:     while (my $configline=<$config>) {
                   9228:        chomp($configline);
1.284     matthew  9229:        if ($configline) {
1.784     albertel 9230: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 9231: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 9232: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 9233:        }
                   9234:     }
1.448     albertel 9235:     close($config);
1.1       albertel 9236: }
1.11      www      9237: # ------------------------------------------------------------ Read permissions
                   9238: {
1.448     albertel 9239:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      9240: 
                   9241:     while (my $configline=<$config>) {
1.448     albertel 9242: 	chomp($configline);
                   9243: 	if ($configline) {
                   9244: 	    my ($role,$perm)=split(/ /,$configline);
                   9245: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   9246: 	}
1.11      www      9247:     }
1.448     albertel 9248:     close($config);
1.11      www      9249: }
                   9250: 
                   9251: # -------------------------------------------- Read plain texts for permissions
                   9252: {
1.448     albertel 9253:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      9254: 
                   9255:     while (my $configline=<$config>) {
1.448     albertel 9256: 	chomp($configline);
                   9257: 	if ($configline) {
1.742     raeburn  9258: 	    my ($short,@plain)=split(/:/,$configline);
                   9259:             %{$prp{$short}} = ();
                   9260: 	    if (@plain > 0) {
                   9261:                 $prp{$short}{'std'} = $plain[0];
                   9262:                 for (my $i=1; $i<@plain; $i++) {
                   9263:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   9264:                 }
                   9265:             }
1.448     albertel 9266: 	}
1.135     www      9267:     }
1.448     albertel 9268:     close($config);
1.135     www      9269: }
                   9270: 
                   9271: # ---------------------------------------------------------- Read package table
                   9272: {
1.448     albertel 9273:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      9274: 
                   9275:     while (my $configline=<$config>) {
1.483     albertel 9276: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 9277: 	chomp($configline);
                   9278: 	my ($short,$plain)=split(/:/,$configline);
                   9279: 	my ($pack,$name)=split(/\&/,$short);
                   9280: 	if ($plain ne '') {
                   9281: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   9282: 	    $packagetab{$short}=$plain; 
                   9283: 	}
1.11      www      9284:     }
1.448     albertel 9285:     close($config);
1.329     matthew  9286: }
                   9287: 
                   9288: # ------------- set up temporary directory
                   9289: {
                   9290:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   9291: 
1.11      www      9292: }
                   9293: 
1.794     albertel 9294: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   9295: 				'compress_threshold'=> 20_000,
                   9296:  			        });
1.185     www      9297: 
1.281     www      9298: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      9299: $dumpcount=0;
1.958     www      9300: $locknum=0;
1.22      www      9301: 
1.163     harris41 9302: &logtouch();
1.672     albertel 9303: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      9304: $readit=1;
1.564     albertel 9305:     {
                   9306: 	use integer;
                   9307: 	my $test=(2**32)+1;
1.568     albertel 9308: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 9309: 	&logthis(" Detected 64bit platform ($_64bit)");
                   9310:     }
1.195     www      9311: }
1.1       albertel 9312: }
1.179     www      9313: 
1.1       albertel 9314: 1;
1.191     harris41 9315: __END__
                   9316: 
1.243     albertel 9317: =pod
                   9318: 
1.191     harris41 9319: =head1 NAME
                   9320: 
1.243     albertel 9321: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 9322: 
                   9323: =head1 SYNOPSIS
                   9324: 
1.243     albertel 9325: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 9326: 
                   9327:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   9328: 
1.243     albertel 9329: Common parameters:
                   9330: 
                   9331: =over 4
                   9332: 
                   9333: =item *
                   9334: 
                   9335: $uname : an internal username (if $cname expecting a course Id specifically)
                   9336: 
                   9337: =item *
                   9338: 
                   9339: $udom : a domain (if $cdom expecting a course's domain specifically)
                   9340: 
                   9341: =item *
                   9342: 
                   9343: $symb : a resource instance identifier
                   9344: 
                   9345: =item *
                   9346: 
                   9347: $namespace : the name of a .db file that contains the data needed or
                   9348: being set.
                   9349: 
                   9350: =back
                   9351: 
1.394     bowersj2 9352: =head1 OVERVIEW
1.191     harris41 9353: 
1.394     bowersj2 9354: lonnet provides subroutines which interact with the
                   9355: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   9356: about classes, users, and resources.
1.243     albertel 9357: 
                   9358: For many of these objects you can also use this to store data about
                   9359: them or modify them in various ways.
1.191     harris41 9360: 
1.394     bowersj2 9361: =head2 Symbs
1.191     harris41 9362: 
1.394     bowersj2 9363: To identify a specific instance of a resource, LON-CAPA uses symbols
                   9364: or "symbs"X<symb>. These identifiers are built from the URL of the
                   9365: map, the resource number of the resource in the map, and the URL of
                   9366: the resource itself. The latter is somewhat redundant, but might help
                   9367: if maps change.
                   9368: 
                   9369: An example is
                   9370: 
                   9371:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   9372: 
                   9373: The respective map entry is
                   9374: 
                   9375:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   9376:   title="Problem 2">
                   9377:  </resource>
                   9378: 
                   9379: Symbs are used by the random number generator, as well as to store and
                   9380: restore data specific to a certain instance of for example a problem.
                   9381: 
                   9382: =head2 Storing And Retrieving Data
                   9383: 
                   9384: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   9385: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   9386: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   9387: is is the non-critical message twin of cstore. These functions are for
                   9388: handlers to store a perl hash to a user's permanent data space in an
                   9389: easy manner, and to retrieve it again on another call. It is expected
                   9390: that a handler would use this once at the beginning to retrieve data,
                   9391: and then again once at the end to send only the new data back.
                   9392: 
                   9393: The data is stored in the user's data directory on the user's
                   9394: homeserver under the ID of the course.
                   9395: 
                   9396: The hash that is returned by restore will have all of the previous
                   9397: value for all of the elements of the hash.
                   9398: 
                   9399: Example:
                   9400: 
                   9401:  #creating a hash
                   9402:  my %hash;
                   9403:  $hash{'foo'}='bar';
                   9404: 
                   9405:  #storing it
                   9406:  &Apache::lonnet::cstore(\%hash);
                   9407: 
                   9408:  #changing a value
                   9409:  $hash{'foo'}='notbar';
                   9410: 
                   9411:  #adding a new value
                   9412:  $hash{'bar'}='foo';
                   9413:  &Apache::lonnet::cstore(\%hash);
                   9414: 
                   9415:  #retrieving the hash
                   9416:  my %history=&Apache::lonnet::restore();
                   9417: 
                   9418:  #print the hash
                   9419:  foreach my $key (sort(keys(%history))) {
                   9420:    print("\%history{$key} = $history{$key}");
                   9421:  }
                   9422: 
                   9423: Will print out:
1.191     harris41 9424: 
1.394     bowersj2 9425:  %history{1:foo} = bar
                   9426:  %history{1:keys} = foo:timestamp
                   9427:  %history{1:timestamp} = 990455579
                   9428:  %history{2:bar} = foo
                   9429:  %history{2:foo} = notbar
                   9430:  %history{2:keys} = foo:bar:timestamp
                   9431:  %history{2:timestamp} = 990455580
                   9432:  %history{bar} = foo
                   9433:  %history{foo} = notbar
                   9434:  %history{timestamp} = 990455580
                   9435:  %history{version} = 2
                   9436: 
                   9437: Note that the special hash entries C<keys>, C<version> and
                   9438: C<timestamp> were added to the hash. C<version> will be equal to the
                   9439: total number of versions of the data that have been stored. The
                   9440: C<timestamp> attribute will be the UNIX time the hash was
                   9441: stored. C<keys> is available in every historical section to list which
                   9442: keys were added or changed at a specific historical revision of a
                   9443: hash.
                   9444: 
                   9445: B<Warning>: do not store the hash that restore returns directly. This
                   9446: will cause a mess since it will restore the historical keys as if the
                   9447: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 9448: 
1.394     bowersj2 9449: Calling convention:
1.191     harris41 9450: 
1.394     bowersj2 9451:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   9452:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 9453: 
1.394     bowersj2 9454: For more detailed information, see lonnet specific documentation.
1.191     harris41 9455: 
1.394     bowersj2 9456: =head1 RETURN MESSAGES
1.191     harris41 9457: 
1.394     bowersj2 9458: =over 4
1.191     harris41 9459: 
1.394     bowersj2 9460: =item * B<con_lost>: unable to contact remote host
1.191     harris41 9461: 
1.394     bowersj2 9462: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   9463: when the connection is brought back up
1.191     harris41 9464: 
1.394     bowersj2 9465: =item * B<con_failed>: unable to contact remote host and unable to save message
                   9466: for later delivery
1.191     harris41 9467: 
1.967     bisitz   9468: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 9469: 
1.394     bowersj2 9470: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 9471: that was requested
1.191     harris41 9472: 
1.243     albertel 9473: =back
1.191     harris41 9474: 
1.243     albertel 9475: =head1 PUBLIC SUBROUTINES
1.191     harris41 9476: 
1.243     albertel 9477: =head2 Session Environment Functions
1.191     harris41 9478: 
1.243     albertel 9479: =over 4
1.191     harris41 9480: 
1.394     bowersj2 9481: =item * 
                   9482: X<appenv()>
1.949     raeburn  9483: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 9484: the user envirnoment file, and will be restored for each access this
1.620     albertel 9485: user makes during this session, also modifies the %env for the current
1.949     raeburn  9486: process. Optional rolesarrayref - if defined contains a reference to an array
                   9487: of roles which are exempt from the restriction on modifying user.role entries 
                   9488: in the user's environment.db and in %env.    
1.191     harris41 9489: 
                   9490: =item *
1.394     bowersj2 9491: X<delenv()>
1.987     raeburn  9492: B<delenv($delthis,$regexp)>: removes all items from the session
                   9493: environment file that begin with $delthis. If the 
                   9494: optional second arg - $regexp - is true, $delthis is treated as a 
                   9495: regular expression, otherwise \Q$delthis\E is used. 
                   9496: The values are also deleted from the current processes %env.
1.191     harris41 9497: 
1.795     albertel 9498: =item * get_env_multiple($name) 
                   9499: 
                   9500: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   9501: values may be defined and end up as an array ref.
                   9502: 
                   9503: returns an array of values
                   9504: 
1.243     albertel 9505: =back
                   9506: 
                   9507: =head2 User Information
1.191     harris41 9508: 
1.243     albertel 9509: =over 4
1.191     harris41 9510: 
                   9511: =item *
1.394     bowersj2 9512: X<queryauthenticate()>
                   9513: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 9514: authentication scheme
                   9515: 
                   9516: =item *
1.394     bowersj2 9517: X<authenticate()>
                   9518: B<authenticate($uname,$upass,$udom)>: try to
                   9519: authenticate user from domain's lib servers (first use the current
                   9520: one). C<$upass> should be the users password.
1.191     harris41 9521: 
                   9522: =item *
1.394     bowersj2 9523: X<homeserver()>
                   9524: B<homeserver($uname,$udom)>: find the server which has
                   9525: the user's directory and files (there must be only one), this caches
                   9526: the answer, and also caches if there is a borken connection.
1.191     harris41 9527: 
                   9528: =item *
1.394     bowersj2 9529: X<idget()>
                   9530: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   9531: (IDs are a unique resource in a domain, there must be only 1 ID per
                   9532: username, and only 1 username per ID in a specific domain) (returns
                   9533: hash: id=>name,id=>name)
1.191     harris41 9534: 
                   9535: =item *
1.394     bowersj2 9536: X<idrget()>
                   9537: B<idrget($udom,@unames)>: find the IDs behind a list of
                   9538: usernames (returns hash: name=>id,name=>id)
1.191     harris41 9539: 
                   9540: =item *
1.394     bowersj2 9541: X<idput()>
                   9542: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 9543: 
                   9544: =item *
1.394     bowersj2 9545: X<rolesinit()>
                   9546: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 9547: 
                   9548: =item *
1.551     albertel 9549: X<getsection()>
                   9550: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 9551: course $cname, return section name/number or '' for "not in course"
                   9552: and '-1' for "no section"
                   9553: 
                   9554: =item *
1.394     bowersj2 9555: X<userenvironment()>
                   9556: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 9557: passed in @what from the requested user's environment, returns a hash
                   9558: 
1.858     raeburn  9559: =item * 
                   9560: X<userlog_query()>
1.859     albertel 9561: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   9562: activity.log file. %filters defines filters applied when parsing the
                   9563: log file. These can be start or end timestamps, or the type of action
                   9564: - log to look for Login or Logout events, check for Checkin or
                   9565: Checkout, role for role selection. The response is in the form
                   9566: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   9567: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  9568: 
1.243     albertel 9569: =back
                   9570: 
                   9571: =head2 User Roles
                   9572: 
                   9573: =over 4
                   9574: 
                   9575: =item *
                   9576: 
1.810     raeburn  9577: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 9578:  F: full access
                   9579:  U,I,K: authentication modes (cxx only)
                   9580:  '': forbidden
                   9581:  1: user needs to choose course
                   9582:  2: browse allowed
1.766     albertel 9583:  A: passphrase authentication needed
1.243     albertel 9584: 
                   9585: =item *
                   9586: 
                   9587: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   9588: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   9589: and course level
                   9590: 
                   9591: =item *
                   9592: 
1.988     raeburn  9593: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   9594: (rolesplain.tab); plain text explanation of a user role term.
                   9595: $type is Course (default) or Group.
                   9596: If $forcedefault evaluates to true, text returned will be default 
                   9597: text for $type. Otherwise, if this is a course, the text returned 
                   9598: will be a custom name for the role (if defined in the course's 
                   9599: environment).  If no custom name is defined the default is returned.
                   9600:    
1.832     raeburn  9601: =item *
                   9602: 
1.935     raeburn  9603: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  9604: All arguments are optional. Returns a hash of a roles, either for
                   9605: co-author/assistant author roles for a user's Construction Space
1.906     albertel 9606: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  9607: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   9608: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   9609: For each key, value is set to colon-separated start and end times for
                   9610: the role.  If no username and domain are specified, will default to
1.934     raeburn  9611: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  9612: of role statuses (active, future or previous), roles 
                   9613: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   9614: to restrict the list of roles reported. If no array ref is 
                   9615: provided for types, will default to return only active roles.
1.834     albertel 9616: 
1.243     albertel 9617: =back
                   9618: 
                   9619: =head2 User Modification
                   9620: 
                   9621: =over 4
                   9622: 
                   9623: =item *
                   9624: 
1.957     raeburn  9625: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 9626: user for the level given by URL.  Optional start and end dates (leave empty
                   9627: string or zero for "no date")
1.191     harris41 9628: 
                   9629: =item *
                   9630: 
1.243     albertel 9631: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   9632: change a users, password, possible return values are: ok,
                   9633: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   9634: refused
1.191     harris41 9635: 
                   9636: =item *
                   9637: 
1.243     albertel 9638: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9639: 
                   9640: =item *
                   9641: 
1.963     raeburn  9642: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
                   9643:            $forceid,$desiredhome,$email,$inststatus) : 
1.243     albertel 9644: modify user
1.191     harris41 9645: 
                   9646: =item *
                   9647: 
1.286     matthew  9648: modifystudent
                   9649: 
1.957     raeburn  9650: modify a student's enrollment and identification information.
1.286     matthew  9651: The course id is resolved based on the current users environment.  
                   9652: This means the envoking user must be a course coordinator or otherwise
                   9653: associated with a course.
                   9654: 
1.297     matthew  9655: This call is essentially a wrapper for lonnet::modifyuser and
                   9656: lonnet::modify_student_enrollment
1.286     matthew  9657: 
                   9658: Inputs: 
                   9659: 
                   9660: =over 4
                   9661: 
1.957     raeburn  9662: =item B<$udom> Student's loncapa domain
1.286     matthew  9663: 
1.957     raeburn  9664: =item B<$uname> Student's loncapa login name
1.286     matthew  9665: 
1.964     bisitz   9666: =item B<$uid> Student/Employee ID
1.286     matthew  9667: 
1.957     raeburn  9668: =item B<$umode> Student's authentication mode
1.286     matthew  9669: 
1.957     raeburn  9670: =item B<$upass> Student's password
1.286     matthew  9671: 
1.957     raeburn  9672: =item B<$first> Student's first name
1.286     matthew  9673: 
1.957     raeburn  9674: =item B<$middle> Student's middle name
1.286     matthew  9675: 
1.957     raeburn  9676: =item B<$last> Student's last name
1.286     matthew  9677: 
1.957     raeburn  9678: =item B<$gene> Student's generation
1.286     matthew  9679: 
1.957     raeburn  9680: =item B<$usec> Student's section in course
1.286     matthew  9681: 
                   9682: =item B<$end> Unix time of the roles expiration
                   9683: 
                   9684: =item B<$start> Unix time of the roles start date
                   9685: 
                   9686: =item B<$forceid> If defined, allow $uid to be changed
                   9687: 
                   9688: =item B<$desiredhome> server to use as home server for student
                   9689: 
1.957     raeburn  9690: =item B<$email> Student's permanent e-mail address
                   9691: 
                   9692: =item B<$type> Type of enrollment (auto or manual)
                   9693: 
1.963     raeburn  9694: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   9695: 
                   9696: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  9697: 
1.963     raeburn  9698: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  9699: 
1.963     raeburn  9700: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  9701: 
1.963     raeburn  9702: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  9703: 
1.286     matthew  9704: =back
1.297     matthew  9705: 
                   9706: =item *
                   9707: 
                   9708: modify_student_enrollment
                   9709: 
                   9710: Change a students enrollment status in a class.  The environment variable
                   9711: 'role.request.course' must be defined for this function to proceed.
                   9712: 
                   9713: Inputs:
                   9714: 
                   9715: =over 4
                   9716: 
                   9717: =item $udom, students domain
                   9718: 
                   9719: =item $uname, students name
                   9720: 
                   9721: =item $uid, students user id
                   9722: 
                   9723: =item $first, students first name
                   9724: 
                   9725: =item $middle
                   9726: 
                   9727: =item $last
                   9728: 
                   9729: =item $gene
                   9730: 
                   9731: =item $usec
                   9732: 
                   9733: =item $end
                   9734: 
                   9735: =item $start
                   9736: 
1.957     raeburn  9737: =item $type
                   9738: 
                   9739: =item $locktype
                   9740: 
                   9741: =item $cid
                   9742: 
                   9743: =item $selfenroll
                   9744: 
                   9745: =item $context
                   9746: 
1.297     matthew  9747: =back
                   9748: 
1.191     harris41 9749: 
                   9750: =item *
                   9751: 
1.243     albertel 9752: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9753: custom role; give a custom role to a user for the level given by URL.  Specify
                   9754: name and domain of role author, and role name
1.191     harris41 9755: 
                   9756: =item *
                   9757: 
1.243     albertel 9758: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9759: 
                   9760: =item *
                   9761: 
1.243     albertel 9762: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9763: 
                   9764: =back
                   9765: 
                   9766: =head2 Course Infomation
                   9767: 
                   9768: =over 4
1.191     harris41 9769: 
                   9770: =item *
                   9771: 
1.631     albertel 9772: coursedescription($courseid) : returns a hash of information about the
                   9773: specified course id, including all environment settings for the
                   9774: course, the description of the course will be in the hash under the
                   9775: key 'description'
1.191     harris41 9776: 
                   9777: =item *
                   9778: 
1.624     albertel 9779: resdata($name,$domain,$type,@which) : request for current parameter
                   9780: setting for a specific $type, where $type is either 'course' or 'user',
                   9781: @what should be a list of parameters to ask about. This routine caches
                   9782: answers for 5 minutes.
1.243     albertel 9783: 
1.877     foxr     9784: =item *
                   9785: 
                   9786: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9787: data base, returning a hash that is keyed by the resource name and has
                   9788: values that are the resource value.  I believe that the timestamps and
                   9789: versions are also returned.
                   9790: 
                   9791: 
1.243     albertel 9792: =back
                   9793: 
                   9794: =head2 Course Modification
                   9795: 
                   9796: =over 4
1.191     harris41 9797: 
                   9798: =item *
                   9799: 
1.243     albertel 9800: writecoursepref($courseid,%prefs) : write preferences (environment
                   9801: database) for a course
1.191     harris41 9802: 
                   9803: =item *
                   9804: 
1.243     albertel 9805: createcourse($udom,$description,$url) : make/modify course
                   9806: 
                   9807: =back
                   9808: 
                   9809: =head2 Resource Subroutines
                   9810: 
                   9811: =over 4
1.191     harris41 9812: 
                   9813: =item *
                   9814: 
1.243     albertel 9815: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9816: 
                   9817: =item *
                   9818: 
1.243     albertel 9819: repcopy($filename) : subscribes to the requested file, and attempts to
                   9820: replicate from the owning library server, Might return
1.607     raeburn  9821: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9822: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9823: resource. Expects the local filesystem pathname
                   9824: (/home/httpd/html/res/....)
                   9825: 
                   9826: =back
                   9827: 
                   9828: =head2 Resource Information
                   9829: 
                   9830: =over 4
1.191     harris41 9831: 
                   9832: =item *
                   9833: 
1.243     albertel 9834: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9835: a vairety of different possible values, $varname should be a request
                   9836: string, and the other parameters can be used to specify who and what
                   9837: one is asking about.
                   9838: 
                   9839: Possible values for $varname are environment.lastname (or other item
                   9840: from the envirnment hash), user.name (or someother aspect about the
                   9841: user), resource.0.maxtries (or some other part and parameter of a
                   9842: resource)
1.204     albertel 9843: 
                   9844: =item *
                   9845: 
1.243     albertel 9846: directcondval($number) : get current value of a condition; reads from a state
                   9847: string
1.204     albertel 9848: 
                   9849: =item *
                   9850: 
1.243     albertel 9851: condval($condidx) : value of condition index based on state
1.204     albertel 9852: 
                   9853: =item *
                   9854: 
1.243     albertel 9855: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9856: resource's metadata, $what should be either a specific key, or either
                   9857: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9858: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9859: 
                   9860: this function automatically caches all requests
1.191     harris41 9861: 
                   9862: =item *
                   9863: 
1.243     albertel 9864: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9865: network of library servers; returns file handle of where SQL and regex results
                   9866: will be stored for query
1.191     harris41 9867: 
                   9868: =item *
                   9869: 
1.243     albertel 9870: symbread($filename) : return symbolic list entry (filename argument optional);
                   9871: returns the data handle
1.191     harris41 9872: 
                   9873: =item *
                   9874: 
1.243     albertel 9875: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9876: a possible symb for the URL in $thisfn, and if is an encryypted
                   9877: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9878: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9879: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9880: 
1.191     harris41 9881: 
                   9882: =item *
                   9883: 
1.243     albertel 9884: symbclean($symb) : removes versions numbers from a symb, returns the
                   9885: cleaned symb
1.191     harris41 9886: 
                   9887: =item *
                   9888: 
1.243     albertel 9889: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9890: course map, user must be in a course for it to work.
1.191     harris41 9891: 
                   9892: =item *
                   9893: 
1.243     albertel 9894: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9895: 
                   9896: =item *
                   9897: 
1.243     albertel 9898: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9899: a random seed, all arguments are optional, if they aren't sent it uses the
                   9900: environment to derive them. Note: if symb isn't sent and it can't get one
                   9901: from &symbread it will use the current time as its return value
1.191     harris41 9902: 
                   9903: =item *
                   9904: 
1.243     albertel 9905: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9906: unfakeable, receipt
1.191     harris41 9907: 
                   9908: =item *
                   9909: 
1.620     albertel 9910: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9911: 
                   9912: =item *
                   9913: 
1.243     albertel 9914: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9915: 
                   9916: =item *
                   9917: 
1.243     albertel 9918: 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 9919: 
                   9920: =item *
                   9921: 
1.243     albertel 9922: 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 9923: 
                   9924: =item *
                   9925: 
1.243     albertel 9926: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9927: 
                   9928: =item *
                   9929: 
1.243     albertel 9930: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9931: forcing spreadsheet to reevaluate the resource scores next time.
                   9932: 
                   9933: =back
                   9934: 
                   9935: =head2 Storing/Retreiving Data
                   9936: 
                   9937: =over 4
1.191     harris41 9938: 
                   9939: =item *
                   9940: 
1.243     albertel 9941: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9942: for this url; hashref needs to be given and should be a \%hashname; the
                   9943: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9944: be derived from the env
1.191     harris41 9945: 
                   9946: =item *
                   9947: 
1.243     albertel 9948: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9949: uses critical subroutine
1.191     harris41 9950: 
                   9951: =item *
                   9952: 
1.243     albertel 9953: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9954: all args are optional
1.191     harris41 9955: 
                   9956: =item *
                   9957: 
1.717     albertel 9958: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9959: dumps the complete (or key matching regexp) namespace into a hash
                   9960: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9961: normally &store()ed into
                   9962: 
                   9963: $range should be either an integer '100' (give me the first 100
                   9964:                                            matching records)
                   9965:               or be  two integers sperated by a - with no spaces
                   9966:                  '30-50' (give me the 30th through the 50th matching
                   9967:                           records)
                   9968: 
                   9969: 
                   9970: =item *
                   9971: 
                   9972: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9973: replaces a &store() version of data with a replacement set of data
                   9974: for a particular resource in a namespace passed in the $storehash hash 
                   9975: reference
                   9976: 
                   9977: =item *
                   9978: 
1.243     albertel 9979: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9980: works very similar to store/cstore, but all data is stored in a
                   9981: temporary location and can be reset using tmpreset, $storehash should
                   9982: be a hash reference, returns nothing on success
1.191     harris41 9983: 
                   9984: =item *
                   9985: 
1.243     albertel 9986: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9987: similar to restore, but all data is stored in a temporary location and
                   9988: can be reset using tmpreset. Returns a hash of values on success,
                   9989: error string otherwise.
1.191     harris41 9990: 
                   9991: =item *
                   9992: 
1.243     albertel 9993: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9994: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9995: 
                   9996: =item *
                   9997: 
1.243     albertel 9998: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9999: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 10000: 
                   10001: =item *
                   10002: 
1.243     albertel 10003: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   10004: namesp ($udom and $uname are optional)
1.191     harris41 10005: 
                   10006: =item *
                   10007: 
1.702     albertel 10008: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 10009: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 10010: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  10011: 
1.702     albertel 10012: $range should be either an integer '100' (give me the first 100
                   10013:                                            matching records)
                   10014:               or be  two integers sperated by a - with no spaces
                   10015:                  '30-50' (give me the 30th through the 50th matching
                   10016:                           records)
1.449     matthew  10017: =item *
                   10018: 
                   10019: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   10020: $store can be a scalar, an array reference, or if the amount to be 
                   10021: incremented is > 1, a hash reference.
                   10022: 
                   10023: ($udom and $uname are optional)
1.191     harris41 10024: 
                   10025: =item *
                   10026: 
1.243     albertel 10027: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   10028: ($udom and $uname are optional)
1.191     harris41 10029: 
                   10030: =item *
                   10031: 
1.243     albertel 10032: cput($namespace,$storehash,$udom,$uname) : critical put
                   10033: ($udom and $uname are optional)
1.191     harris41 10034: 
                   10035: =item *
                   10036: 
1.748     albertel 10037: newput($namespace,$storehash,$udom,$uname) :
                   10038: 
                   10039: Attempts to store the items in the $storehash, but only if they don't
                   10040: currently exist, if this succeeds you can be certain that you have 
                   10041: successfully created a new key value pair in the $namespace db.
                   10042: 
                   10043: 
                   10044: Args:
                   10045:  $namespace: name of database to store values to
                   10046:  $storehash: hashref to store to the db
                   10047:  $udom: (optional) domain of user containing the db
                   10048:  $uname: (optional) name of user caontaining the db
                   10049: 
                   10050: Returns:
                   10051:  'ok' -> succeeded in storing all keys of $storehash
                   10052:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   10053:                         least <key> already existed in the db (other
                   10054:                         requested keys may also already exist)
1.967     bisitz   10055:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 10056:  'con_lost' -> unable to contact request server
                   10057:  'refused' -> action was not allowed by remote machine
                   10058: 
                   10059: 
                   10060: =item *
                   10061: 
1.243     albertel 10062: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   10063: reference filled in from namesp (encrypts the return communication)
                   10064: ($udom and $uname are optional)
1.191     harris41 10065: 
                   10066: =item *
                   10067: 
1.243     albertel 10068: log($udom,$name,$home,$message) : write to permanent log for user; use
                   10069: critical subroutine
                   10070: 
1.806     raeburn  10071: =item *
                   10072: 
1.860     raeburn  10073: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   10074: array reference filled in from namespace found in domain level on either
                   10075: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  10076: 
                   10077: =item *
                   10078: 
1.860     raeburn  10079: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   10080: domain level either on specified domain server ($uhome) or primary domain 
                   10081: server ($udom and $uhome are optional)
1.806     raeburn  10082: 
1.943     raeburn  10083: =item * 
                   10084: 
                   10085: get_domain_defaults($target_domain) : returns hash with defaults for
                   10086: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   10087: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   10088: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   10089: Values are retrieved from cache (if current), or from domain's configuration.db
                   10090: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   10091: or lonTabs/domain.tab. 
                   10092: 
                   10093: %domdefaults = &get_auth_defaults($target_domain);
                   10094: 
1.243     albertel 10095: =back
                   10096: 
                   10097: =head2 Network Status Functions
                   10098: 
                   10099: =over 4
1.191     harris41 10100: 
                   10101: =item *
                   10102: 
                   10103: dirlist($uri) : return directory list based on URI
                   10104: 
                   10105: =item *
                   10106: 
1.243     albertel 10107: spareserver() : find server with least workload from spare.tab
                   10108: 
1.986     foxr     10109: 
                   10110: =item *
                   10111: 
                   10112: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   10113: if there is no corresponding loncapa host.
                   10114: 
1.243     albertel 10115: =back
                   10116: 
1.986     foxr     10117: 
1.243     albertel 10118: =head2 Apache Request
                   10119: 
                   10120: =over 4
1.191     harris41 10121: 
                   10122: =item *
                   10123: 
1.243     albertel 10124: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   10125: localhost, posts hash
                   10126: 
                   10127: =back
                   10128: 
                   10129: =head2 Data to String to Data
                   10130: 
                   10131: =over 4
1.191     harris41 10132: 
                   10133: =item *
                   10134: 
1.243     albertel 10135: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   10136: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 10137: 
                   10138: =item *
                   10139: 
1.243     albertel 10140: hashref2str($hashref) : convert a hashref into a string complete with
                   10141: escaping and '=' and '&' separators, supports elements that are
                   10142: arrayrefs and hashrefs
1.191     harris41 10143: 
                   10144: =item *
                   10145: 
1.243     albertel 10146: arrayref2str($arrayref) : convert an arrayref into a string complete
                   10147: with escaping and '&' separators, supports elements that are arrayrefs
                   10148: and hashrefs
1.191     harris41 10149: 
                   10150: =item *
                   10151: 
1.243     albertel 10152: str2hash($string) : convert string to hash using unescaping and
                   10153: splitting on '=' and '&', supports elements that are arrayrefs and
                   10154: hashrefs
1.191     harris41 10155: 
                   10156: =item *
                   10157: 
1.243     albertel 10158: str2array($string) : convert string to hash using unescaping and
                   10159: splitting on '&', supports elements that are arrayrefs and hashrefs
                   10160: 
                   10161: =back
                   10162: 
                   10163: =head2 Logging Routines
                   10164: 
                   10165: =over 4
                   10166: 
                   10167: These routines allow one to make log messages in the lonnet.log and
                   10168: lonnet.perm logfiles.
1.191     harris41 10169: 
                   10170: =item *
                   10171: 
1.243     albertel 10172: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 10173: 
                   10174: =item *
                   10175: 
1.243     albertel 10176: logthis() : append message to the normal lonnet.log file, it gets
                   10177: preiodically rolled over and deleted.
1.191     harris41 10178: 
                   10179: =item *
                   10180: 
1.243     albertel 10181: logperm() : append a permanent message to lonnet.perm.log, this log
                   10182: file never gets deleted by any automated portion of the system, only
                   10183: messages of critical importance should go in here.
                   10184: 
                   10185: =back
                   10186: 
                   10187: =head2 General File Helper Routines
                   10188: 
                   10189: =over 4
1.191     harris41 10190: 
                   10191: =item *
                   10192: 
1.481     raeburn  10193: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   10194: (a) files in /uploaded
                   10195:   (i) If a local copy of the file exists - 
                   10196:       compares modification date of local copy with last-modified date for 
                   10197:       definitive version stored on home server for course. If local copy is 
                   10198:       stale, requests a new version from the home server and stores it. 
                   10199:       If the original has been removed from the home server, then local copy 
                   10200:       is unlinked.
                   10201:   (ii) If local copy does not exist -
                   10202:       requests the file from the home server and stores it. 
                   10203:   
                   10204:   If $caller is 'uploadrep':  
                   10205:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   10206:     for request for files originally uploaded via DOCS. 
                   10207:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   10208:   
                   10209:   Otherwise:
                   10210:      This indicates a call from the content generation phase of the request.
                   10211:      -  returns the entire contents of the file or -1.
                   10212:      
                   10213: (b) files in /res
                   10214:    - returns the entire contents of a file or -1; 
                   10215:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 10216: 
1.712     albertel 10217: 
                   10218: =item *
                   10219: 
                   10220: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   10221:                   reference
                   10222: 
                   10223: returns either a stat() list of data about the file or an empty list
                   10224: if the file doesn't exist or couldn't find out about it (connection
                   10225: problems or user unknown)
                   10226: 
1.191     harris41 10227: =item *
                   10228: 
1.243     albertel 10229: filelocation($dir,$file) : returns file system location of a file
                   10230: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   10231: directory that relative $file lookups are to looked in ($dir of /a/dir
                   10232: and a file of ../bob will become /a/bob)
1.191     harris41 10233: 
                   10234: =item *
                   10235: 
                   10236: hreflocation($dir,$file) : returns file system location or a URL; same as
                   10237: filelocation except for hrefs
                   10238: 
                   10239: =item *
                   10240: 
                   10241: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   10242: 
1.243     albertel 10243: =back
                   10244: 
1.608     albertel 10245: =head2 Usererfile file routines (/uploaded*)
                   10246: 
                   10247: =over 4
                   10248: 
                   10249: =item *
                   10250: 
                   10251: userfileupload(): main rotine for putting a file in a user or course's
                   10252:                   filespace, arguments are,
                   10253: 
1.620     albertel 10254:  formname - required - this is the name of the element in $env where the
1.608     albertel 10255:            filename, and the contents of the file to create/modifed exist
1.620     albertel 10256:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   10257:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 10258:  coursedoc - if true, store the file in the course of the active role
                   10259:              of the current user
                   10260:  subdir - required - subdirectory to put the file in under ../userfiles/
                   10261:          if undefined, it will be placed in "unknown"
                   10262: 
                   10263:  (This routine calls clean_filename() to remove any dangerous
                   10264:  characters from the filename, and then calls finuserfileupload() to
                   10265:  complete the transaction)
                   10266: 
                   10267:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10268:  and /adm/notfound.html if unsuccessful
                   10269: 
                   10270: =item *
                   10271: 
                   10272: clean_filename(): routine for cleaing a filename up for storage in
                   10273:                  userfile space, argument is:
                   10274: 
                   10275:  filename - proposed filename
                   10276: 
                   10277: returns: the new clean filename
                   10278: 
                   10279: =item *
                   10280: 
                   10281: finishuserfileupload(): routine that creaes and sends the file to
                   10282: userspace, probably shouldn't be called directly
                   10283: 
                   10284:   docuname: username or courseid of destination for the file
                   10285:   docudom: domain of user/course of destination for the file
                   10286:   formname: same as for userfileupload()
                   10287:   fname: filename (inculding subdirectories) for the file
                   10288: 
                   10289:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10290:  and /adm/notfound.html if unsuccessful
                   10291: 
                   10292: =item *
                   10293: 
                   10294: renameuserfile(): renames an existing userfile to a new name
                   10295: 
                   10296:   Args:
                   10297:    docuname: username or courseid of destination for the file
                   10298:    docudom: domain of user/course of destination for the file
                   10299:    old: current file name (including any subdirs under userfiles)
                   10300:    new: desired file name (including any subdirs under userfiles)
                   10301: 
                   10302: =item *
                   10303: 
                   10304: mkdiruserfile(): creates a directory is a userfiles dir
                   10305: 
                   10306:   Args:
                   10307:    docuname: username or courseid of destination for the file
                   10308:    docudom: domain of user/course of destination for the file
                   10309:    dir: dir to create (including any subdirs under userfiles)
                   10310: 
                   10311: =item *
                   10312: 
                   10313: removeuserfile(): removes a file that exists in userfiles
                   10314: 
                   10315:   Args:
                   10316:    docuname: username or courseid of destination for the file
                   10317:    docudom: domain of user/course of destination for the file
                   10318:    fname: filname to delete (including any subdirs under userfiles)
                   10319: 
                   10320: =item *
                   10321: 
                   10322: removeuploadedurl(): convience function for removeuserfile()
                   10323: 
                   10324:   Args:
                   10325:    url:  a full /uploaded/... url to delete
                   10326: 
1.747     albertel 10327: =item * 
                   10328: 
                   10329: get_portfile_permissions():
                   10330:   Args:
                   10331:     domain: domain of user or course contain the portfolio files
                   10332:     user: name of user or num of course contain the portfolio files
                   10333:   Returns:
                   10334:     hashref of a dump of the proper file_permissions.db
                   10335:    
                   10336: 
                   10337: =item * 
                   10338: 
                   10339: get_access_controls():
                   10340: 
                   10341: Args:
                   10342:   current_permissions: the hash ref returned from get_portfile_permissions()
                   10343:   group: (optional) the group you want the files associated with
                   10344:   file: (optional) the file you want access info on
                   10345: 
                   10346: Returns:
1.749     raeburn  10347:     a hash (keys are file names) of hashes containing
                   10348:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   10349:         values are XML containing access control settings (see below) 
1.747     albertel 10350: 
                   10351: Internal notes:
                   10352: 
1.749     raeburn  10353:  access controls are stored in file_permissions.db as key=value pairs.
                   10354:     key -> path to file/file_name\0uniqueID:scope_end_start
                   10355:         where scope -> public,guest,course,group,domains or users.
                   10356:               end -> UNIX time for end of access (0 -> no end date)
                   10357:               start -> UNIX time for start of access
                   10358: 
                   10359:     value -> XML description of access control
                   10360:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   10361:             <start></start>
                   10362:             <end></end>
                   10363: 
                   10364:             <password></password>  for scope type = guest
                   10365: 
                   10366:             <domain></domain>     for scope type = course or group
                   10367:             <number></number>
                   10368:             <roles id="">
                   10369:              <role></role>
                   10370:              <access></access>
                   10371:              <section></section>
                   10372:              <group></group>
                   10373:             </roles>
                   10374: 
                   10375:             <dom></dom>         for scope type = domains
                   10376: 
                   10377:             <users>             for scope type = users
                   10378:              <user>
                   10379:               <uname></uname>
                   10380:               <udom></udom>
                   10381:              </user>
                   10382:             </users>
                   10383:            </scope> 
                   10384:               
                   10385:  Access data is also aggregated for each file in an additional key=value pair:
                   10386:  key -> path to file/file_name\0accesscontrol 
                   10387:  value -> reference to hash
                   10388:           hash contains key = value pairs
                   10389:           where key = uniqueID:scope_end_start
                   10390:                 value = UNIX time record was last updated
                   10391: 
                   10392:           Used to improve speed of look-ups of access controls for each file.  
                   10393:  
                   10394:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   10395: 
                   10396: modify_access_controls():
                   10397: 
                   10398: Modifies access controls for a portfolio file
                   10399: Args
                   10400: 1. file name
                   10401: 2. reference to hash of required changes,
                   10402: 3. domain
                   10403: 4. username
                   10404:   where domain,username are the domain of the portfolio owner 
                   10405:   (either a user or a course) 
                   10406: 
                   10407: Returns:
                   10408: 1. result of additions or updates ('ok' or 'error', with error message). 
                   10409: 2. result of deletions ('ok' or 'error', with error message).
                   10410: 3. reference to hash of any new or updated access controls.
                   10411: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   10412:    key = integer (inbound ID)
                   10413:    value = uniqueID  
1.747     albertel 10414: 
1.608     albertel 10415: =back
                   10416: 
1.243     albertel 10417: =head2 HTTP Helper Routines
                   10418: 
                   10419: =over 4
                   10420: 
1.191     harris41 10421: =item *
                   10422: 
                   10423: escape() : unpack non-word characters into CGI-compatible hex codes
                   10424: 
                   10425: =item *
                   10426: 
                   10427: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   10428: 
1.243     albertel 10429: =back
                   10430: 
                   10431: =head1 PRIVATE SUBROUTINES
                   10432: 
                   10433: =head2 Underlying communication routines (Shouldn't call)
                   10434: 
                   10435: =over 4
                   10436: 
                   10437: =item *
                   10438: 
                   10439: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   10440: 
                   10441: =item *
                   10442: 
                   10443: reply() : uses subreply to send a message to remote machine, logs all failures
                   10444: 
                   10445: =item *
                   10446: 
                   10447: critical() : passes a critical message to another server; if cannot
                   10448: get through then place message in connection buffer directory and
                   10449: returns con_delayed, if incapable of saving message, returns
                   10450: con_failed
                   10451: 
                   10452: =item *
                   10453: 
                   10454: reconlonc() : tries to reconnect lonc client processes.
                   10455: 
                   10456: =back
                   10457: 
                   10458: =head2 Resource Access Logging
                   10459: 
                   10460: =over 4
                   10461: 
                   10462: =item *
                   10463: 
                   10464: flushcourselogs() : flush (save) buffer logs and access logs
                   10465: 
                   10466: =item *
                   10467: 
                   10468: courselog($what) : save message for course in hash
                   10469: 
                   10470: =item *
                   10471: 
                   10472: courseacclog($what) : save message for course using &courselog().  Perform
                   10473: special processing for specific resource types (problems, exams, quizzes, etc).
                   10474: 
1.191     harris41 10475: =item *
                   10476: 
                   10477: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   10478: as a PerlChildExitHandler
1.243     albertel 10479: 
                   10480: =back
                   10481: 
                   10482: =head2 Other
                   10483: 
                   10484: =over 4
                   10485: 
                   10486: =item *
                   10487: 
                   10488: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 10489: 
                   10490: =back
                   10491: 
                   10492: =cut
1.877     foxr     10493: 

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