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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1023  ! raeburn     4: # $Id: lonnet.pm,v 1.1022 2009/08/23 03:57:20 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.1023  ! raeburn   961: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn   962: sub dump_dom {
1.1023  ! raeburn   963:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn   964:     if (!$udom) {
                    965:         $udom=$env{'user.domain'};
                    966:     }
                    967:     my %returnhash;
1.1023  ! raeburn   968:     if ($udom) {
        !           969:         my $uname = &get_domainconfiguser($udom);
        !           970:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn   971:     }
                    972:     return %returnhash;
                    973: }
                    974: 
1.1023  ! raeburn   975: # ------------------------------------------ get items from domain db files   
1.806     raeburn   976: 
                    977: sub get_dom {
1.860     raeburn   978:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   979:     my $items='';
                    980:     foreach my $item (@$storearr) {
                    981:         $items.=&escape($item).'&';
                    982:     }
                    983:     $items=~s/\&$//;
1.860     raeburn   984:     if (!$udom) {
                    985:         $udom=$env{'user.domain'};
                    986:         if (defined(&domain($udom,'primary'))) {
                    987:             $uhome=&domain($udom,'primary');
                    988:         } else {
1.874     albertel  989:             undef($uhome);
1.860     raeburn   990:         }
                    991:     } else {
                    992:         if (!$uhome) {
                    993:             if (defined(&domain($udom,'primary'))) {
                    994:                 $uhome=&domain($udom,'primary');
                    995:             }
                    996:         }
                    997:     }
                    998:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   999:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1000:         my %returnhash;
1.875     albertel 1001:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1002:             return %returnhash;
                   1003:         }
1.806     raeburn  1004:         my @pairs=split(/\&/,$rep);
                   1005:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1006:             return @pairs;
                   1007:         }
                   1008:         my $i=0;
                   1009:         foreach my $item (@$storearr) {
                   1010:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1011:             $i++;
                   1012:         }
                   1013:         return %returnhash;
                   1014:     } else {
1.880     banghart 1015:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1016:     }
                   1017: }
                   1018: 
                   1019: # -------------------------------------------- put items in domain db files 
                   1020: 
                   1021: sub put_dom {
1.860     raeburn  1022:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1023:     if (!$udom) {
                   1024:         $udom=$env{'user.domain'};
                   1025:         if (defined(&domain($udom,'primary'))) {
                   1026:             $uhome=&domain($udom,'primary');
                   1027:         } else {
1.874     albertel 1028:             undef($uhome);
1.860     raeburn  1029:         }
                   1030:     } else {
                   1031:         if (!$uhome) {
                   1032:             if (defined(&domain($udom,'primary'))) {
                   1033:                 $uhome=&domain($udom,'primary');
                   1034:             }
                   1035:         }
                   1036:     } 
                   1037:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1038:         my $items='';
                   1039:         foreach my $item (keys(%$storehash)) {
                   1040:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1041:         }
                   1042:         $items=~s/\&$//;
                   1043:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1044:     } else {
1.860     raeburn  1045:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1046:     }
                   1047: }
                   1048: 
1.1023  ! raeburn  1049: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1050: sub newput_dom {
1.1023  ! raeburn  1051:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1052:     my $result;
                   1053:     if (!$udom) {
                   1054:         $udom=$env{'user.domain'};
                   1055:     }
1.1023  ! raeburn  1056:     if ($udom) {
        !          1057:         my $uname = &get_domainconfiguser($udom);
        !          1058:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1059:     }
                   1060:     return $result;
                   1061: }
                   1062: 
1.1023  ! raeburn  1063: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1064: sub del_dom {
1.1023  ! raeburn  1065:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1066:     if (ref($storearr) eq 'ARRAY') {
                   1067:         if (!$udom) {
                   1068:             $udom=$env{'user.domain'};
                   1069:         }
1.1023  ! raeburn  1070:         if ($udom) {
        !          1071:             my $uname = &get_domainconfiguser($udom); 
        !          1072:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1073:         }
                   1074:     }
                   1075: }
                   1076: 
1.1023  ! raeburn  1077: # ----------------------------------construct domainconfig user for a domain 
        !          1078: sub get_domainconfiguser {
        !          1079:     my ($udom) = @_;
        !          1080:     return $udom.'-domainconfig';
        !          1081: }
        !          1082: 
1.837     raeburn  1083: sub retrieve_inst_usertypes {
                   1084:     my ($udom) = @_;
                   1085:     my (%returnhash,@order);
1.989     raeburn  1086:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1087:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1088:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1089:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1090:         @order = @{$domdefs{'inststatusorder'}};
                   1091:     } else {
                   1092:         if (defined(&domain($udom,'primary'))) {
                   1093:             my $uhome=&domain($udom,'primary');
                   1094:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1095:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1096:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1097:                 return (\%returnhash,\@order);
                   1098:             }
                   1099:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1100:             my @pairs=split(/\&/,$hashitems);
                   1101:             foreach my $item (@pairs) {
                   1102:                 my ($key,$value)=split(/=/,$item,2);
                   1103:                 $key = &unescape($key);
                   1104:                 next if ($key =~ /^error: 2 /);
                   1105:                 $returnhash{$key}=&thaw_unescape($value);
                   1106:             }
                   1107:             my @esc_order = split(/\&/,$orderitems);
                   1108:             foreach my $item (@esc_order) {
                   1109:                 push(@order,&unescape($item));
                   1110:             }
                   1111:         } else {
                   1112:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1113:         }
                   1114:     }
                   1115:     return (\%returnhash,\@order);
                   1116: }
                   1117: 
1.868     raeburn  1118: sub is_domainimage {
                   1119:     my ($url) = @_;
                   1120:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1121:         if (&domain($1) ne '') {
                   1122:             return '1';
                   1123:         }
                   1124:     }
                   1125:     return;
                   1126: }
                   1127: 
1.899     raeburn  1128: sub inst_directory_query {
                   1129:     my ($srch) = @_;
                   1130:     my $udom = $srch->{'srchdomain'};
                   1131:     my %results;
                   1132:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1133:     my $outcome;
1.899     raeburn  1134:     if ($homeserver ne '') {
1.904     albertel 1135: 	my $queryid=&reply("querysend:instdirsearch:".
                   1136: 			   &escape($srch->{'srchby'}).':'.
                   1137: 			   &escape($srch->{'srchterm'}).':'.
                   1138: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1139: 	my $host=&hostname($homeserver);
                   1140: 	if ($queryid !~/^\Q$host\E\_/) {
                   1141: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1142: 	    return;
                   1143: 	}
                   1144: 	my $response = &get_query_reply($queryid);
                   1145: 	my $maxtries = 5;
                   1146: 	my $tries = 1;
                   1147: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1148: 	    $response = &get_query_reply($queryid);
                   1149: 	    $tries ++;
                   1150: 	}
                   1151: 
                   1152:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1153:             if ($response eq 'unavailable') {
                   1154:                 $outcome = $response;
                   1155:             } else {
                   1156:                 $outcome = 'ok';
                   1157:                 my @matches = split(/\n/,$response);
                   1158:                 foreach my $match (@matches) {
                   1159:                     my ($key,$value) = split(/=/,$match);
                   1160:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1161:                 }
1.899     raeburn  1162:             }
                   1163:         }
                   1164:     }
1.909     raeburn  1165:     return ($outcome,%results);
1.899     raeburn  1166: }
                   1167: 
                   1168: sub usersearch {
                   1169:     my ($srch) = @_;
                   1170:     my $dom = $srch->{'srchdomain'};
                   1171:     my %results;
                   1172:     my %libserv = &all_library();
                   1173:     my $query = 'usersearch';
                   1174:     foreach my $tryserver (keys(%libserv)) {
                   1175:         if (&host_domain($tryserver) eq $dom) {
                   1176:             my $host=&hostname($tryserver);
                   1177:             my $queryid=
1.911     raeburn  1178:                 &reply("querysend:".&escape($query).':'.
                   1179:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1180:                        &escape($srch->{'srchtype'}).':'.
                   1181:                        &escape($srch->{'srchterm'}),$tryserver);
                   1182:             if ($queryid !~/^\Q$host\E\_/) {
                   1183:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1184:                 next;
1.899     raeburn  1185:             }
                   1186:             my $reply = &get_query_reply($queryid);
                   1187:             my $maxtries = 1;
                   1188:             my $tries = 1;
                   1189:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1190:                 $reply = &get_query_reply($queryid);
                   1191:                 $tries ++;
                   1192:             }
                   1193:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1194:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1195:             } else {
1.911     raeburn  1196:                 my @matches;
                   1197:                 if ($reply =~ /\n/) {
                   1198:                     @matches = split(/\n/,$reply);
                   1199:                 } else {
                   1200:                     @matches = split(/\&/,$reply);
                   1201:                 }
1.899     raeburn  1202:                 foreach my $match (@matches) {
                   1203:                     my ($uname,$udom,%userhash);
1.911     raeburn  1204:                     foreach my $entry (split(/:/,$match)) {
                   1205:                         my ($key,$value) =
                   1206:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1207:                         $userhash{$key} = $value;
                   1208:                         if ($key eq 'username') {
                   1209:                             $uname = $value;
                   1210:                         } elsif ($key eq 'domain') {
                   1211:                             $udom = $value;
1.911     raeburn  1212:                         }
1.899     raeburn  1213:                     }
                   1214:                     $results{$uname.':'.$udom} = \%userhash;
                   1215:                 }
                   1216:             }
                   1217:         }
                   1218:     }
                   1219:     return %results;
                   1220: }
                   1221: 
1.912     raeburn  1222: sub get_instuser {
                   1223:     my ($udom,$uname,$id) = @_;
                   1224:     my $homeserver = &domain($udom,'primary');
                   1225:     my ($outcome,%results);
                   1226:     if ($homeserver ne '') {
                   1227:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1228:                            &escape($id).':'.&escape($udom),$homeserver);
                   1229:         my $host=&hostname($homeserver);
                   1230:         if ($queryid !~/^\Q$host\E\_/) {
                   1231:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1232:             return;
                   1233:         }
                   1234:         my $response = &get_query_reply($queryid);
                   1235:         my $maxtries = 5;
                   1236:         my $tries = 1;
                   1237:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1238:             $response = &get_query_reply($queryid);
                   1239:             $tries ++;
                   1240:         }
                   1241:         if (!&error($response) && $response ne 'refused') {
                   1242:             if ($response eq 'unavailable') {
                   1243:                 $outcome = $response;
                   1244:             } else {
                   1245:                 $outcome = 'ok';
                   1246:                 my @matches = split(/\n/,$response);
                   1247:                 foreach my $match (@matches) {
                   1248:                     my ($key,$value) = split(/=/,$match);
                   1249:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1250:                 }
                   1251:             }
                   1252:         }
                   1253:     }
                   1254:     my %userinfo;
                   1255:     if (ref($results{$uname}) eq 'HASH') {
                   1256:         %userinfo = %{$results{$uname}};
                   1257:     } 
                   1258:     return ($outcome,%userinfo);
                   1259: }
                   1260: 
                   1261: sub inst_rulecheck {
1.923     raeburn  1262:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1263:     my %returnhash;
                   1264:     if ($udom ne '') {
                   1265:         if (ref($rules) eq 'ARRAY') {
                   1266:             @{$rules} = map {&escape($_);} (@{$rules});
                   1267:             my $rulestr = join(':',@{$rules});
                   1268:             my $homeserver=&domain($udom,'primary');
                   1269:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1270:                 my $response;
                   1271:                 if ($item eq 'username') {                
                   1272:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1273:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1274:                                               $homeserver));
1.923     raeburn  1275:                 } elsif ($item eq 'id') {
                   1276:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1277:                                               ':'.&escape($id).':'.$rulestr,
                   1278:                                               $homeserver));
1.945     raeburn  1279:                 } elsif ($item eq 'selfcreate') {
                   1280:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1281:                                                &escape($udom).':'.&escape($uname).
                   1282:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1283:                 }
1.912     raeburn  1284:                 if ($response ne 'refused') {
                   1285:                     my @pairs=split(/\&/,$response);
                   1286:                     foreach my $item (@pairs) {
                   1287:                         my ($key,$value)=split(/=/,$item,2);
                   1288:                         $key = &unescape($key);
                   1289:                         next if ($key =~ /^error: 2 /);
                   1290:                         $returnhash{$key}=&thaw_unescape($value);
                   1291:                     }
                   1292:                 }
                   1293:             }
                   1294:         }
                   1295:     }
                   1296:     return %returnhash;
                   1297: }
                   1298: 
                   1299: sub inst_userrules {
1.923     raeburn  1300:     my ($udom,$check) = @_;
1.912     raeburn  1301:     my (%ruleshash,@ruleorder);
                   1302:     if ($udom ne '') {
                   1303:         my $homeserver=&domain($udom,'primary');
                   1304:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1305:             my $response;
                   1306:             if ($check eq 'id') {
                   1307:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1308:                                  $homeserver);
1.943     raeburn  1309:             } elsif ($check eq 'email') {
                   1310:                 $response=&reply('instemailrules:'.&escape($udom),
                   1311:                                  $homeserver);
1.923     raeburn  1312:             } else {
                   1313:                 $response=&reply('instuserrules:'.&escape($udom),
                   1314:                                  $homeserver);
                   1315:             }
1.912     raeburn  1316:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1317:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1318:                 ($response ne 'no_such_host')) {
                   1319:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1320:                 my @pairs=split(/\&/,$hashitems);
                   1321:                 foreach my $item (@pairs) {
                   1322:                     my ($key,$value)=split(/=/,$item,2);
                   1323:                     $key = &unescape($key);
                   1324:                     next if ($key =~ /^error: 2 /);
                   1325:                     $ruleshash{$key}=&thaw_unescape($value);
                   1326:                 }
                   1327:                 my @esc_order = split(/\&/,$orderitems);
                   1328:                 foreach my $item (@esc_order) {
                   1329:                     push(@ruleorder,&unescape($item));
                   1330:                 }
                   1331:             }
                   1332:         }
                   1333:     }
                   1334:     return (\%ruleshash,\@ruleorder);
                   1335: }
                   1336: 
1.976     raeburn  1337: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1338: 
                   1339: sub get_domain_defaults {
                   1340:     my ($domain) = @_;
                   1341:     my $cachetime = 60*60*24;
                   1342:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1343:     if (defined($cached)) {
                   1344:         if (ref($result) eq 'HASH') {
                   1345:             return %{$result};
                   1346:         }
                   1347:     }
                   1348:     my %domdefaults;
                   1349:     my %domconfig =
1.989     raeburn  1350:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
                   1351:                                   'requestcourses','inststatus'],$domain);
1.943     raeburn  1352:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1353:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1354:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1355:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1356:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1357:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1358:     } else {
                   1359:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1360:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1361:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1362:     }
1.976     raeburn  1363:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1364:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1365:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1366:         } else {
                   1367:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1368:         } 
                   1369:         my @usertools = ('aboutme','blog','portfolio');
                   1370:         foreach my $item (@usertools) {
                   1371:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1372:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1373:             }
                   1374:         }
                   1375:     }
1.985     raeburn  1376:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1377:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1378:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1379:         }
                   1380:     }
1.989     raeburn  1381:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1382:         foreach my $item ('inststatustypes','inststatusorder') {
                   1383:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1384:         }
                   1385:     }
1.943     raeburn  1386:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1387:                                   $cachetime);
                   1388:     return %domdefaults;
                   1389: }
                   1390: 
1.344     www      1391: # --------------------------------------------------- Assign a key to a student
                   1392: 
                   1393: sub assign_access_key {
1.364     www      1394: #
                   1395: # a valid key looks like uname:udom#comments
                   1396: # comments are being appended
                   1397: #
1.498     www      1398:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1399:     $kdom=
1.620     albertel 1400:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1401:     $knum=
1.620     albertel 1402:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1403:     $cdom=
1.620     albertel 1404:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1405:     $cnum=
1.620     albertel 1406:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1407:     $udom=$env{'user.name'} unless (defined($udom));
                   1408:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1409:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1410:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1411:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1412:                                                   # assigned to this person
                   1413:                                                   # - this should not happen,
1.345     www      1414:                                                   # unless something went wrong
                   1415:                                                   # the first time around
                   1416: # ready to assign
1.364     www      1417:         $logentry=$1.'; '.$logentry;
1.496     www      1418:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1419:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1420: # key now belongs to user
1.346     www      1421: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1422:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1423:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1424:                 return 'ok';
                   1425:             } else {
                   1426:                 return 
                   1427:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1428: 	    }
                   1429:         } else {
                   1430:             return 'error: Could not assign key, try again later.';
                   1431:         }
1.364     www      1432:     } elsif (!$existing{$ckey}) {
1.345     www      1433: # the key does not exist
                   1434: 	return 'error: The key does not exist';
                   1435:     } else {
                   1436: # the key is somebody else's
                   1437: 	return 'error: The key is already in use';
                   1438:     }
1.344     www      1439: }
                   1440: 
1.364     www      1441: # ------------------------------------------ put an additional comment on a key
                   1442: 
                   1443: sub comment_access_key {
                   1444: #
                   1445: # a valid key looks like uname:udom#comments
                   1446: # comments are being appended
                   1447: #
                   1448:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1449:     $cdom=
1.620     albertel 1450:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1451:     $cnum=
1.620     albertel 1452:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1453:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1454:     if ($existing{$ckey}) {
                   1455:         $existing{$ckey}.='; '.$logentry;
                   1456: # ready to assign
1.367     www      1457:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1458:                                                  $cdom,$cnum) eq 'ok') {
                   1459: 	    return 'ok';
                   1460:         } else {
                   1461: 	    return 'error: Count not store comment.';
                   1462:         }
                   1463:     } else {
                   1464: # the key does not exist
                   1465: 	return 'error: The key does not exist';
                   1466:     }
                   1467: }
                   1468: 
1.344     www      1469: # ------------------------------------------------------ Generate a set of keys
                   1470: 
                   1471: sub generate_access_keys {
1.364     www      1472:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1473:     $cdom=
1.620     albertel 1474:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1475:     $cnum=
1.620     albertel 1476:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1477:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1478:     unless (($cdom) && ($cnum)) { return 0; }
                   1479:     if ($number>10000) { return 0; }
                   1480:     sleep(2); # make sure don't get same seed twice
                   1481:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1482:     my $total=0;
                   1483:     for (my $i=1;$i<=$number;$i++) {
                   1484:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1485:                   sprintf("%lx",int(100000*rand)).'-'.
                   1486:                   sprintf("%lx",int(100000*rand));
                   1487:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1488:        $newkey=~s/0/h/g; # and also 0 and O
                   1489:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1490:        if ($existing{$newkey}) {
                   1491:            $i--;
                   1492:        } else {
1.364     www      1493: 	  if (&put('accesskeys',
                   1494:               { $newkey => '# generated '.localtime().
1.620     albertel 1495:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1496:                            '; '.$logentry },
                   1497: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1498:               $total++;
                   1499: 	  }
                   1500:        }
                   1501:     }
1.620     albertel 1502:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1503:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1504:     return $total;
                   1505: }
                   1506: 
                   1507: # ------------------------------------------------------- Validate an accesskey
                   1508: 
                   1509: sub validate_access_key {
                   1510:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1511:     $cdom=
1.620     albertel 1512:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1513:     $cnum=
1.620     albertel 1514:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1515:     $udom=$env{'user.domain'} unless (defined($udom));
                   1516:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1517:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1518:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1519: }
                   1520: 
                   1521: # ------------------------------------- Find the section of student in a course
1.652     albertel 1522: sub devalidate_getsection_cache {
                   1523:     my ($udom,$unam,$courseid)=@_;
                   1524:     my $hashid="$udom:$unam:$courseid";
                   1525:     &devalidate_cache_new('getsection',$hashid);
                   1526: }
1.298     matthew  1527: 
1.815     albertel 1528: sub courseid_to_courseurl {
                   1529:     my ($courseid) = @_;
                   1530:     #already url style courseid
                   1531:     return $courseid if ($courseid =~ m{^/});
                   1532: 
                   1533:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1534: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1535: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1536: 	return "/$cdom/$cnum";
                   1537:     }
                   1538: 
                   1539:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1540:     if (exists($courseinfo{'num'})) {
                   1541: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1542:     }
                   1543: 
                   1544:     return undef;
                   1545: }
                   1546: 
1.298     matthew  1547: sub getsection {
                   1548:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1549:     my $cachetime=1800;
1.551     albertel 1550: 
                   1551:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1552:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1553:     if (defined($cached)) { return $result; }
                   1554: 
1.298     matthew  1555:     my %Pending; 
                   1556:     my %Expired;
                   1557:     #
                   1558:     # Each role can either have not started yet (pending), be active, 
                   1559:     #    or have expired.
                   1560:     #
                   1561:     # If there is an active role, we are done.
                   1562:     #
                   1563:     # If there is more than one role which has not started yet, 
                   1564:     #     choose the one which will start sooner
                   1565:     # If there is one role which has not started yet, return it.
                   1566:     #
                   1567:     # If there is more than one expired role, choose the one which ended last.
                   1568:     # If there is a role which has expired, return it.
                   1569:     #
1.815     albertel 1570:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1571:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1572:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1573:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1574:         my $section=$1;
                   1575:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1576:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1577:         my $now=time;
1.548     albertel 1578:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1579:             $Expired{$end}=$section;
                   1580:             next;
                   1581:         }
1.548     albertel 1582:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1583:             $Pending{$start}=$section;
                   1584:             next;
                   1585:         }
1.599     albertel 1586:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1587:     }
                   1588:     #
                   1589:     # Presumedly there will be few matching roles from the above
                   1590:     # loop and the sorting time will be negligible.
                   1591:     if (scalar(keys(%Pending))) {
                   1592:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1593:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1594:     } 
                   1595:     if (scalar(keys(%Expired))) {
                   1596:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1597:         my $time = pop(@sorted);
1.599     albertel 1598:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1599:     }
1.599     albertel 1600:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1601: }
1.70      www      1602: 
1.599     albertel 1603: sub save_cache {
                   1604:     &purge_remembered();
1.722     albertel 1605:     #&Apache::loncommon::validate_page();
1.620     albertel 1606:     undef(%env);
1.780     albertel 1607:     undef($env_loaded);
1.599     albertel 1608: }
1.452     albertel 1609: 
1.599     albertel 1610: my $to_remember=-1;
                   1611: my %remembered;
                   1612: my %accessed;
                   1613: my $kicks=0;
                   1614: my $hits=0;
1.849     albertel 1615: sub make_key {
                   1616:     my ($name,$id) = @_;
1.872     albertel 1617:     if (length($id) > 65 
                   1618: 	&& length(&escape($id)) > 200) {
                   1619: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1620:     }
1.849     albertel 1621:     return &escape($name.':'.$id);
                   1622: }
                   1623: 
1.599     albertel 1624: sub devalidate_cache_new {
                   1625:     my ($name,$id,$debug) = @_;
                   1626:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1627:     $id=&make_key($name,$id);
1.599     albertel 1628:     $memcache->delete($id);
                   1629:     delete($remembered{$id});
                   1630:     delete($accessed{$id});
                   1631: }
                   1632: 
                   1633: sub is_cached_new {
                   1634:     my ($name,$id,$debug) = @_;
1.849     albertel 1635:     $id=&make_key($name,$id);
1.599     albertel 1636:     if (exists($remembered{$id})) {
                   1637: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1638: 	$accessed{$id}=[&gettimeofday()];
                   1639: 	$hits++;
                   1640: 	return ($remembered{$id},1);
                   1641:     }
                   1642:     my $value = $memcache->get($id);
                   1643:     if (!(defined($value))) {
                   1644: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1645: 	return (undef,undef);
1.416     albertel 1646:     }
1.599     albertel 1647:     if ($value eq '__undef__') {
                   1648: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1649: 	$value=undef;
                   1650:     }
                   1651:     &make_room($id,$value,$debug);
                   1652:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1653:     return ($value,1);
                   1654: }
                   1655: 
                   1656: sub do_cache_new {
                   1657:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1658:     $id=&make_key($name,$id);
1.599     albertel 1659:     my $setvalue=$value;
                   1660:     if (!defined($setvalue)) {
                   1661: 	$setvalue='__undef__';
                   1662:     }
1.623     albertel 1663:     if (!defined($time) ) {
                   1664: 	$time=600;
                   1665:     }
1.599     albertel 1666:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1667:     my $result = $memcache->set($id,$setvalue,$time);
                   1668:     if (! $result) {
1.872     albertel 1669: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1670: 	$memcache->disconnect_all();
1.872     albertel 1671:     }
1.600     albertel 1672:     # need to make a copy of $value
1.919     albertel 1673:     &make_room($id,$value,$debug);
1.599     albertel 1674:     return $value;
                   1675: }
                   1676: 
                   1677: sub make_room {
                   1678:     my ($id,$value,$debug)=@_;
1.919     albertel 1679: 
                   1680:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1681:                                     : $value;
1.599     albertel 1682:     if ($to_remember<0) { return; }
                   1683:     $accessed{$id}=[&gettimeofday()];
                   1684:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1685:     my $to_kick;
                   1686:     my $max_time=0;
                   1687:     foreach my $other (keys(%accessed)) {
                   1688: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1689: 	    $to_kick=$other;
                   1690: 	    $max_time=&tv_interval($accessed{$other});
                   1691: 	}
                   1692:     }
                   1693:     delete($remembered{$to_kick});
                   1694:     delete($accessed{$to_kick});
                   1695:     $kicks++;
                   1696:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1697:     return;
                   1698: }
                   1699: 
1.599     albertel 1700: sub purge_remembered {
1.604     albertel 1701:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1702:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1703:     undef(%remembered);
                   1704:     undef(%accessed);
1.428     albertel 1705: }
1.70      www      1706: # ------------------------------------- Read an entry from a user's environment
                   1707: 
                   1708: sub userenvironment {
                   1709:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1710:     my $items;
                   1711:     foreach my $item (@what) {
                   1712:         $items.=&escape($item).'&';
                   1713:     }
                   1714:     $items=~s/\&$//;
1.70      www      1715:     my %returnhash=();
1.1009    raeburn  1716:     my $uhome = &homeserver($unam,$udom);
                   1717:     unless ($uhome eq 'no_host') {
                   1718:         my @answer=split(/\&/, 
                   1719:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
                   1720:         my $i;
                   1721:         for ($i=0;$i<=$#what;$i++) {
                   1722: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   1723:         }
1.70      www      1724:     }
                   1725:     return %returnhash;
1.1       albertel 1726: }
                   1727: 
1.617     albertel 1728: # ---------------------------------------------------------- Get a studentphoto
                   1729: sub studentphoto {
                   1730:     my ($udom,$unam,$ext) = @_;
                   1731:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1732:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1733:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1734:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1735:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1736:             } else {
                   1737:                 my ($result,$perm_reqd)=
1.707     albertel 1738: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1739:                 if ($result eq 'ok') {
                   1740:                     if (!($perm_reqd eq 'yes')) {
                   1741:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1742:                     }
                   1743:                 }
                   1744:             }
                   1745:         }
                   1746:     } else {
                   1747:         my ($result,$perm_reqd) = 
1.707     albertel 1748: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1749:         if ($result eq 'ok') {
                   1750:             if (!($perm_reqd eq 'yes')) {
                   1751:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1752:             }
                   1753:         }
                   1754:     }
                   1755:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1756: }
                   1757: 
                   1758: sub retrievestudentphoto {
                   1759:     my ($udom,$unam,$ext,$type) = @_;
                   1760:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1761:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1762:     if ($ret eq 'ok') {
                   1763:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1764:         if ($type eq 'thumbnail') {
                   1765:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1766:         }
                   1767:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1768:         return $tokenurl;
                   1769:     } else {
                   1770:         if ($type eq 'thumbnail') {
                   1771:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1772:         } else { 
                   1773:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1774:         }
1.617     albertel 1775:     }
                   1776: }
                   1777: 
1.263     www      1778: # -------------------------------------------------------------------- New chat
                   1779: 
                   1780: sub chatsend {
1.724     raeburn  1781:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1782:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1783:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1784:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1785:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1786: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1787: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1788: }
                   1789: 
                   1790: # ------------------------------------------ Find current version of a resource
                   1791: 
                   1792: sub getversion {
                   1793:     my $fname=&clutter(shift);
                   1794:     unless ($fname=~/^\/res\//) { return -1; }
                   1795:     return &currentversion(&filelocation('',$fname));
                   1796: }
                   1797: 
                   1798: sub currentversion {
                   1799:     my $fname=shift;
1.599     albertel 1800:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1801:     if (defined($cached)) { return $result; }
1.292     www      1802:     my $author=$fname;
                   1803:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1804:     my ($udom,$uname)=split(/\//,$author);
                   1805:     my $home=homeserver($uname,$udom);
                   1806:     if ($home eq 'no_host') { 
                   1807:         return -1; 
                   1808:     }
                   1809:     my $answer=reply("currentversion:$fname",$home);
                   1810:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1811: 	return -1;
                   1812:     }
1.599     albertel 1813:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1814: }
                   1815: 
1.1       albertel 1816: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1817: 
1.1       albertel 1818: sub subscribe {
                   1819:     my $fname=shift;
1.761     raeburn  1820:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1821:     $fname=~s/[\n\r]//g;
1.1       albertel 1822:     my $author=$fname;
                   1823:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1824:     my ($udom,$uname)=split(/\//,$author);
                   1825:     my $home=homeserver($uname,$udom);
1.335     albertel 1826:     if ($home eq 'no_host') {
                   1827:         return 'not_found';
1.1       albertel 1828:     }
                   1829:     my $answer=reply("sub:$fname",$home);
1.64      www      1830:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1831: 	$answer.=' by '.$home;
                   1832:     }
1.1       albertel 1833:     return $answer;
                   1834: }
                   1835:     
1.8       www      1836: # -------------------------------------------------------------- Replicate file
                   1837: 
                   1838: sub repcopy {
                   1839:     my $filename=shift;
1.23      www      1840:     $filename=~s/\/+/\//g;
1.607     raeburn  1841:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1842:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1843:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1844: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1845: 	return &repcopy_userfile($filename);
                   1846:     }
1.532     albertel 1847:     $filename=~s/[\n\r]//g;
1.8       www      1848:     my $transname="$filename.in.transfer";
1.828     www      1849: # FIXME: this should flock
1.607     raeburn  1850:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1851:     my $remoteurl=subscribe($filename);
1.64      www      1852:     if ($remoteurl =~ /^con_lost by/) {
                   1853: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1854:            return 'unavailable';
1.8       www      1855:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1856: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1857: 	   return 'not_found';
1.64      www      1858:     } elsif ($remoteurl =~ /^rejected by/) {
                   1859: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1860:            return 'forbidden';
1.20      www      1861:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1862:            return 'ok';
1.8       www      1863:     } else {
1.290     www      1864:         my $author=$filename;
                   1865:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1866:         my ($udom,$uname)=split(/\//,$author);
                   1867:         my $home=homeserver($uname,$udom);
                   1868:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1869:            my @parts=split(/\//,$filename);
                   1870:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1871:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1872:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1873: 	       return 'bad_request';
1.8       www      1874:            }
                   1875:            my $count;
                   1876:            for ($count=5;$count<$#parts;$count++) {
                   1877:                $path.="/$parts[$count]";
                   1878:                if ((-e $path)!=1) {
                   1879: 		   mkdir($path,0777);
                   1880:                }
                   1881:            }
                   1882:            my $ua=new LWP::UserAgent;
                   1883:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1884:            my $response=$ua->request($request,$transname);
                   1885:            if ($response->is_error()) {
                   1886: 	       unlink($transname);
                   1887:                my $message=$response->status_line;
1.672     albertel 1888:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1889:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1890:                return 'unavailable';
1.8       www      1891:            } else {
1.16      www      1892: 	       if ($remoteurl!~/\.meta$/) {
                   1893:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1894:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1895:                   if ($mresponse->is_error()) {
                   1896: 		      unlink($filename.'.meta');
                   1897:                       &logthis(
1.672     albertel 1898:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1899:                   }
                   1900: 	       }
1.8       www      1901:                rename($transname,$filename);
1.607     raeburn  1902:                return 'ok';
1.8       www      1903:            }
1.290     www      1904:        }
1.8       www      1905:     }
1.330     www      1906: }
                   1907: 
                   1908: # ------------------------------------------------ Get server side include body
                   1909: sub ssi_body {
1.381     albertel 1910:     my ($filelink,%form)=@_;
1.606     matthew  1911:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1912:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1913:     }
1.953     www      1914:     my $output='';
                   1915:     my $response;
1.980     raeburn  1916:     if ($filelink=~/^https?\:/) {
1.954     raeburn  1917:        ($output,$response)=&externalssi($filelink);
1.953     www      1918:     } else {
1.1004    droeschl 1919:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   1920:        $filelink .= 'inhibitmenu=yes';
1.953     www      1921:        ($output,$response)=&ssi($filelink,%form);
                   1922:     }
1.778     albertel 1923:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1924:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 1925:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      1926:     if (wantarray) {
                   1927:         return ($output, $response);
                   1928:     } else {
                   1929:         return $output;
                   1930:     }
1.8       www      1931: }
                   1932: 
1.15      www      1933: # --------------------------------------------------------- Server Side Include
                   1934: 
1.782     albertel 1935: sub absolute_url {
                   1936:     my ($host_name) = @_;
                   1937:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1938:     if ($host_name eq '') {
                   1939: 	$host_name = $ENV{'SERVER_NAME'};
                   1940:     }
                   1941:     return $protocol.$host_name;
                   1942: }
                   1943: 
1.942     foxr     1944: #
                   1945: #   Server side include.
                   1946: # Parameters:
                   1947: #  fn     Possibly encrypted resource name/id.
                   1948: #  form   Hash that describes how the rendering should be done
                   1949: #         and other things.
1.944     foxr     1950: # Returns:
1.950     raeburn  1951: #   Scalar context: The content of the response.
                   1952: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     1953: #     
1.15      www      1954: sub ssi {
                   1955: 
1.944     foxr     1956:     my ($fn,%form)=@_;
1.15      www      1957:     my $ua=new LWP::UserAgent;
1.23      www      1958:     my $request;
1.711     albertel 1959: 
                   1960:     $form{'no_update_last_known'}=1;
1.895     albertel 1961:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1962:     if (%form) {
1.782     albertel 1963:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  1964:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      1965:     } else {
1.782     albertel 1966:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1967:     }
                   1968: 
1.15      www      1969:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1970:     my $response=$ua->request($request);
                   1971: 
1.944     foxr     1972:     if (wantarray) {
                   1973: 	return ($response->content, $response);
                   1974:     } else {
                   1975: 	return $response->content;
1.942     foxr     1976:     }
1.324     www      1977: }
                   1978: 
                   1979: sub externalssi {
                   1980:     my ($url)=@_;
                   1981:     my $ua=new LWP::UserAgent;
                   1982:     my $request=new HTTP::Request('GET',$url);
                   1983:     my $response=$ua->request($request);
1.954     raeburn  1984:     if (wantarray) {
                   1985:         return ($response->content, $response);
                   1986:     } else {
                   1987:         return $response->content;
                   1988:     }
1.15      www      1989: }
1.254     www      1990: 
1.492     albertel 1991: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1992: 
                   1993: sub allowuploaded {
                   1994:     my ($srcurl,$url)=@_;
                   1995:     $url=&clutter(&declutter($url));
                   1996:     my $dir=$url;
                   1997:     $dir=~s/\/[^\/]+$//;
                   1998:     my %httpref=();
                   1999:     my $httpurl=&hreflocation('',$url);
                   2000:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2001:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2002: }
1.477     raeburn  2003: 
1.478     albertel 2004: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2005: # input: action, courseID, current domain, intended
1.637     raeburn  2006: #        path to file, source of file, instruction to parse file for objects,
                   2007: #        ref to hash for embedded objects,
                   2008: #        ref to hash for codebase of java objects.
                   2009: #
1.485     raeburn  2010: # output: url to file (if action was uploaddoc), 
                   2011: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2012: #
1.478     albertel 2013: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2014: # course.
1.477     raeburn  2015: #
1.478     albertel 2016: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2017: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2018: #          course's home server.
1.477     raeburn  2019: #
1.478     albertel 2020: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2021: #          be copied from $source (current location) to 
                   2022: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2023: #         and will then be copied to
                   2024: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2025: #         course's home server.
1.485     raeburn  2026: #
1.481     raeburn  2027: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2028: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2029: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2030: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2031: #         in course's home server.
1.637     raeburn  2032: #
1.477     raeburn  2033: 
                   2034: sub process_coursefile {
1.638     albertel 2035:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  2036:     my $fetchresult;
1.638     albertel 2037:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2038:     if ($action eq 'propagate') {
1.638     albertel 2039:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2040: 			     $home);
1.481     raeburn  2041:     } else {
1.477     raeburn  2042:         my $fpath = '';
                   2043:         my $fname = $file;
1.478     albertel 2044:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2045:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2046:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2047:         if ($action eq 'copy') {
                   2048:             if ($source eq '') {
                   2049:                 $fetchresult = 'no source file';
                   2050:                 return $fetchresult;
                   2051:             } else {
                   2052:                 my $destination = $filepath.'/'.$fname;
                   2053:                 rename($source,$destination);
                   2054:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2055:                                  $home);
1.481     raeburn  2056:             }
                   2057:         } elsif ($action eq 'uploaddoc') {
                   2058:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2059:             print $fh $env{'form.'.$source};
1.481     raeburn  2060:             close($fh);
1.637     raeburn  2061:             if ($parser eq 'parse') {
1.961     raeburn  2062:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
1.637     raeburn  2063:                 unless ($parse_result eq 'ok') {
                   2064:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2065:                 }
                   2066:             }
1.477     raeburn  2067:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2068:                                  $home);
1.481     raeburn  2069:             if ($fetchresult eq 'ok') {
                   2070:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2071:             } else {
                   2072:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2073:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2074:                 return '/adm/notfound.html';
                   2075:             }
1.477     raeburn  2076:         }
                   2077:     }
1.485     raeburn  2078:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2079:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2080:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2081:     }
                   2082:     return $fetchresult;
                   2083: }
                   2084: 
1.637     raeburn  2085: sub build_filepath {
                   2086:     my ($fpath) = @_;
                   2087:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2088:     unless ($fpath eq '') {
                   2089:         my @parts=split('/',$fpath);
                   2090:         foreach my $part (@parts) {
                   2091:             $filepath.= '/'.$part;
                   2092:             if ((-e $filepath)!=1) {
                   2093:                 mkdir($filepath,0777);
                   2094:             }
                   2095:         }
                   2096:     }
                   2097:     return $filepath;
                   2098: }
                   2099: 
                   2100: sub store_edited_file {
1.638     albertel 2101:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2102:     my $file = $primary_url;
                   2103:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2104:     my $fpath = '';
                   2105:     my $fname = $file;
                   2106:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2107:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2108:     my $filepath = &build_filepath($fpath);
                   2109:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2110:     print $fh $content;
                   2111:     close($fh);
1.638     albertel 2112:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2113:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2114: 			  $home);
1.637     raeburn  2115:     if ($$fetchresult eq 'ok') {
                   2116:         return '/uploaded/'.$fpath.'/'.$fname;
                   2117:     } else {
1.638     albertel 2118:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2119: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2120:         return '/adm/notfound.html';
                   2121:     }
                   2122: }
                   2123: 
1.531     albertel 2124: sub clean_filename {
1.831     albertel 2125:     my ($fname,$args)=@_;
1.315     www      2126: # Replace Windows backslashes by forward slashes
1.257     www      2127:     $fname=~s/\\/\//g;
1.831     albertel 2128:     if (!$args->{'keep_path'}) {
                   2129:         # Get rid of everything but the actual filename
                   2130: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2131:     }
1.315     www      2132: # Replace spaces by underscores
                   2133:     $fname=~s/\s+/\_/g;
                   2134: # Replace all other weird characters by nothing
1.831     albertel 2135:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2136: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2137: # numbers
                   2138:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2139:     return $fname;
                   2140: }
1.984     neumanie 2141: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
                   2142: sub resizeImage {
                   2143: 	my($img_url) = @_;	
                   2144: 	my $ima = Image::Magick->new;                       
                   2145:         $ima->Read($img_url);
                   2146: 	if($ima->Get('width') > 400)
                   2147: 	{
                   2148: 		my $factor = $ima->Get('width')/400;
                   2149:              	$ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
                   2150: 	}
                   2151: 	if($ima->Get('height') > 500)
                   2152:         {
                   2153:         	my $factor = $ima->Get('height')/500;
                   2154:                 $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
                   2155:         } 
                   2156: 		
                   2157: 	$ima->Write($img_url);
                   2158: }
1.531     albertel 2159: 
1.977     amueller 2160: #Wrapper function for userphotoupload
                   2161: sub userphotoupload
                   2162: {
                   2163: 	my($formname,$subdir) = @_;
                   2164: 	$upload_photo_form = 1;
                   2165: 	return &userfileupload($formname,undef,$subdir);
                   2166: }
                   2167: 
1.608     albertel 2168: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2169: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 2170: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 2171: #        $coursedoc - if true up to the current course
                   2172: #                     if false
                   2173: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2174: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2175: #        $allfiles - reference to hash for embedded objects
                   2176: #        $codebase - reference to hash for codebase of java objects
                   2177: #        $desuname - username for permanent storage of uploaded file
                   2178: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2179: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2180: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  2181: # 
1.686     albertel 2182: # output: url of file in userspace, or error: <message> 
                   2183: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2184: 
                   2185: 
1.531     albertel 2186: sub userfileupload {
1.860     raeburn  2187:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   2188:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 2189:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2190:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2191:     $fname=&clean_filename($fname);
1.315     www      2192: # See if there is anything left
1.257     www      2193:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2194:     chop($env{'form.'.$formname});
1.523     raeburn  2195:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2196:         my $now = time;
                   2197:         my $filepath = 'tmp/helprequests/'.$now;
                   2198:         my @parts=split(/\//,$filepath);
                   2199:         my $fullpath = $perlvar{'lonDaemons'};
                   2200:         for (my $i=0;$i<@parts;$i++) {
                   2201:             $fullpath .= '/'.$parts[$i];
                   2202:             if ((-e $fullpath)!=1) {
                   2203:                 mkdir($fullpath,0777);
                   2204:             }
                   2205:         }
                   2206:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2207:         print $fh $env{'form.'.$formname};
1.523     raeburn  2208:         close($fh);
1.741     raeburn  2209:         return $fullpath.'/'.$fname;
                   2210:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2211:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2212:                        '_'.$env{'user.domain'}.'/pending';
                   2213:         my @parts=split(/\//,$filepath);
                   2214:         my $fullpath = $perlvar{'lonDaemons'};
                   2215:         for (my $i=0;$i<@parts;$i++) {
                   2216:             $fullpath .= '/'.$parts[$i];
                   2217:             if ((-e $fullpath)!=1) {
                   2218:                 mkdir($fullpath,0777);
                   2219:             }
                   2220:         }
                   2221:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2222:         print $fh $env{'form.'.$formname};
                   2223:         close($fh);
                   2224:         return $fullpath.'/'.$fname;
1.523     raeburn  2225:     }
1.995     raeburn  2226:     if ($subdir eq 'scantron') {
                   2227:         $fname = 'scantron_orig_'.$fname;
                   2228:     } else {   
1.258     www      2229: # Create the directory if not present
1.995     raeburn  2230:         $fname="$subdir/$fname";
                   2231:     }
1.259     www      2232:     if ($coursedoc) {
1.638     albertel 2233: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2234: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2235:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2236:             return &finishuserfileupload($docuname,$docudom,
                   2237: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  2238: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  2239:         } else {
1.620     albertel 2240:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2241:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2242: 				       $fname,$formname,$parser,
                   2243: 				       $allfiles,$codebase);
1.481     raeburn  2244:         }
1.719     banghart 2245:     } elsif (defined($destuname)) {
                   2246:         my $docuname=$destuname;
                   2247:         my $docudom=$destudom;
1.860     raeburn  2248: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2249: 				     $parser,$allfiles,$codebase,
                   2250:                                      $thumbwidth,$thumbheight);
1.719     banghart 2251:         
1.259     www      2252:     } else {
1.638     albertel 2253:         my $docuname=$env{'user.name'};
                   2254:         my $docudom=$env{'user.domain'};
1.714     raeburn  2255:         if (exists($env{'form.group'})) {
                   2256:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2257:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2258:         }
1.860     raeburn  2259: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2260: 				     $parser,$allfiles,$codebase,
                   2261:                                      $thumbwidth,$thumbheight);
1.259     www      2262:     }
1.271     www      2263: }
                   2264: 
                   2265: sub finishuserfileupload {
1.860     raeburn  2266:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   2267:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  2268:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2269:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2270:   
1.860     raeburn  2271:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2272:     $file=$fname;
                   2273:     if ($fname=~m|/|) {
                   2274:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2275: 	$path.=$fnamepath.'/';
                   2276:     }
1.259     www      2277:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2278:     my $count;
                   2279:     for ($count=4;$count<=$#parts;$count++) {
                   2280:         $filepath.="/$parts[$count]";
                   2281:         if ((-e $filepath)!=1) {
                   2282: 	    mkdir($filepath,0777);
                   2283:         }
                   2284:     }
1.984     neumanie 2285: 
1.258     www      2286: # Save the file
                   2287:     {
1.701     albertel 2288: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2289: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2290: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2291: 	    return '/adm/notfound.html';
                   2292: 	}
                   2293: 	if (!print FH ($env{'form.'.$formname})) {
                   2294: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2295: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2296: 	    return '/adm/notfound.html';
                   2297: 	}
1.570     albertel 2298: 	close(FH);
1.977     amueller 2299: 	if($upload_photo_form==1)
                   2300: 	{
1.984     neumanie 2301: 		resizeImage($filepath.'/'.$file);		
1.977     amueller 2302: 		$upload_photo_form = 0;
                   2303: 	}
1.258     www      2304:     }
1.637     raeburn  2305:     if ($parser eq 'parse') {
1.961     raeburn  2306:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
1.638     albertel 2307: 						   $codebase);
1.637     raeburn  2308:         unless ($parse_result eq 'ok') {
1.638     albertel 2309:             &logthis('Failed to parse '.$filepath.$file.
                   2310: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  2311:         }
                   2312:     }
1.860     raeburn  2313:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2314:         my $input = $filepath.'/'.$file;
                   2315:         my $output = $filepath.'/'.'tn-'.$file;
                   2316:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2317:         system("convert -sample $thumbsize $input $output");
                   2318:         if (-e $filepath.'/'.'tn-'.$file) {
                   2319:             $fetchthumb  = 1; 
                   2320:         }
                   2321:     }
1.858     raeburn  2322:  
1.259     www      2323: # Notify homeserver to grep it
                   2324: #
1.984     neumanie 2325:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2326:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2327:     if ($fetchresult eq 'ok') {
1.860     raeburn  2328:         if ($fetchthumb) {
                   2329:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2330:             if ($thumbresult ne 'ok') {
                   2331:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2332:                          $docuhome.': '.$thumbresult);
                   2333:             }
                   2334:         }
1.259     www      2335: #
1.258     www      2336: # Return the URL to it
1.494     albertel 2337:         return '/uploaded/'.$path.$file;
1.263     www      2338:     } else {
1.494     albertel 2339:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2340: 		 ': '.$fetchresult);
1.263     www      2341:         return '/adm/notfound.html';
1.858     raeburn  2342:     }
1.493     albertel 2343: }
                   2344: 
1.637     raeburn  2345: sub extract_embedded_items {
1.961     raeburn  2346:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2347:     my @state = ();
                   2348:     my %javafiles = (
                   2349:                       codebase => '',
                   2350:                       code => '',
                   2351:                       archive => ''
                   2352:                     );
                   2353:     my %mediafiles = (
                   2354:                       src => '',
                   2355:                       movie => '',
                   2356:                      );
1.648     raeburn  2357:     my $p;
                   2358:     if ($content) {
                   2359:         $p = HTML::LCParser->new($content);
                   2360:     } else {
1.961     raeburn  2361:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2362:     }
1.641     albertel 2363:     while (my $t=$p->get_token()) {
1.640     albertel 2364: 	if ($t->[0] eq 'S') {
                   2365: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2366: 	    push(@state, $tagname);
1.648     raeburn  2367:             if (lc($tagname) eq 'allow') {
                   2368:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2369:             }
1.640     albertel 2370: 	    if (lc($tagname) eq 'img') {
                   2371: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2372: 	    }
1.886     albertel 2373: 	    if (lc($tagname) eq 'a') {
                   2374: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2375: 	    }
1.645     raeburn  2376:             if (lc($tagname) eq 'script') {
                   2377:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2378:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2379:                 } else {
                   2380:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2381:                 }
                   2382:             }
                   2383:             if (lc($tagname) eq 'link') {
                   2384:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2385:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2386:                 }
                   2387:             }
1.640     albertel 2388: 	    if (lc($tagname) eq 'object' ||
                   2389: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2390: 		foreach my $item (keys(%javafiles)) {
                   2391: 		    $javafiles{$item} = '';
                   2392: 		}
                   2393: 	    }
                   2394: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2395: 		my $name = lc($attr->{'name'});
                   2396: 		foreach my $item (keys(%javafiles)) {
                   2397: 		    if ($name eq $item) {
                   2398: 			$javafiles{$item} = $attr->{'value'};
                   2399: 			last;
                   2400: 		    }
                   2401: 		}
                   2402: 		foreach my $item (keys(%mediafiles)) {
                   2403: 		    if ($name eq $item) {
                   2404: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2405: 			last;
                   2406: 		    }
                   2407: 		}
                   2408: 	    }
                   2409: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2410: 		foreach my $item (keys(%javafiles)) {
                   2411: 		    if ($attr->{$item}) {
                   2412: 			$javafiles{$item} = $attr->{$item};
                   2413: 			last;
                   2414: 		    }
                   2415: 		}
                   2416: 		foreach my $item (keys(%mediafiles)) {
                   2417: 		    if ($attr->{$item}) {
                   2418: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2419: 			last;
                   2420: 		    }
                   2421: 		}
                   2422: 	    }
                   2423: 	} elsif ($t->[0] eq 'E') {
                   2424: 	    my ($tagname) = ($t->[1]);
                   2425: 	    if ($javafiles{'codebase'} ne '') {
                   2426: 		$javafiles{'codebase'} .= '/';
                   2427: 	    }  
                   2428: 	    if (lc($tagname) eq 'applet' ||
                   2429: 		lc($tagname) eq 'object' ||
                   2430: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2431: 		) {
                   2432: 		foreach my $item (keys(%javafiles)) {
                   2433: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2434: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2435: 			&add_filetype($allfiles,$file,$item);
                   2436: 		    }
                   2437: 		}
                   2438: 	    } 
                   2439: 	    pop @state;
                   2440: 	}
                   2441:     }
1.637     raeburn  2442:     return 'ok';
                   2443: }
                   2444: 
1.639     albertel 2445: sub add_filetype {
                   2446:     my ($allfiles,$file,$type)=@_;
                   2447:     if (exists($allfiles->{$file})) {
                   2448: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2449: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2450: 	}
                   2451:     } else {
                   2452: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2453:     }
                   2454: }
                   2455: 
1.493     albertel 2456: sub removeuploadedurl {
1.984     neumanie 2457:     my ($url)=@_;	
                   2458:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2459:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2460: }
                   2461: 
                   2462: sub removeuserfile {
                   2463:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2464:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2465:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2466:     if ($result eq 'ok') {	
1.798     raeburn  2467:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2468:             my $metafile = $fname.'.meta';
                   2469:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2470: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2471:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2472:             my $sqlresult = 
1.823     albertel 2473:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2474:                                         'portfolio_metadata',$group,
                   2475:                                         'delete');
1.798     raeburn  2476:         }
                   2477:     }
                   2478:     return $result;
1.257     www      2479: }
1.15      www      2480: 
1.530     albertel 2481: sub mkdiruserfile {
                   2482:     my ($docuname,$docudom,$dir)=@_;
                   2483:     my $home=&homeserver($docuname,$docudom);
                   2484:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2485: }
                   2486: 
1.531     albertel 2487: sub renameuserfile {
                   2488:     my ($docuname,$docudom,$old,$new)=@_;
                   2489:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2490:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2491:                         &escape("$old").':'.&escape("$new"),$home);
                   2492:     if ($result eq 'ok') {
                   2493:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2494:             my $oldmeta = $old.'.meta';
                   2495:             my $newmeta = $new.'.meta';
                   2496:             my $metaresult = 
                   2497:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2498: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2499:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2500:             my $sqlresult = 
1.823     albertel 2501:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2502:                                         'portfolio_metadata',$group,
                   2503:                                         'delete');
1.798     raeburn  2504:         }
                   2505:     }
                   2506:     return $result;
1.531     albertel 2507: }
                   2508: 
1.14      www      2509: # ------------------------------------------------------------------------- Log
                   2510: 
                   2511: sub log {
                   2512:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2513:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2514: }
                   2515: 
                   2516: # ------------------------------------------------------------------ Course Log
1.352     www      2517: #
                   2518: # This routine flushes several buffers of non-mission-critical nature
                   2519: #
1.157     www      2520: 
                   2521: sub flushcourselogs {
1.352     www      2522:     &logthis('Flushing log buffers');
                   2523: #
                   2524: # course logs
                   2525: # This is a log of all transactions in a course, which can be used
                   2526: # for data mining purposes
                   2527: #
                   2528: # It also collects the courseid database, which lists last transaction
                   2529: # times and course titles for all courseids
                   2530: #
                   2531:     my %courseidbuffer=();
1.921     raeburn  2532:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2533:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2534: 		          &escape($courselogs{$crsid}),
                   2535: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2536: 	    delete $courselogs{$crsid};
                   2537:         } else {
                   2538:             &logthis('Failed to flush log buffer for '.$crsid);
                   2539:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2540:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2541:                         " exceeded maximum size, deleting.</font>");
                   2542:                delete $courselogs{$crsid};
                   2543:             }
1.352     www      2544:         }
1.920     raeburn  2545:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2546:             'description' => $coursedescrbuf{$crsid},
                   2547:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2548:             'type'        => $coursetypebuf{$crsid},
                   2549:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2550:         };
1.191     harris41 2551:     }
1.352     www      2552: #
                   2553: # Write course id database (reverse lookup) to homeserver of courses 
                   2554: # Is used in pickcourse
                   2555: #
1.840     albertel 2556:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2557:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2558:                                     $courseidbuffer{$crs_home},
                   2559:                                     $crs_home,'timeonly');
1.352     www      2560:     }
                   2561: #
                   2562: # File accesses
                   2563: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2564: #
1.449     matthew  2565:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2566:         if ($entry =~ /___count$/) {
                   2567:             my ($dom,$name);
1.807     albertel 2568:             ($dom,$name,undef)=
1.811     albertel 2569: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2570:             if (! defined($dom) || $dom eq '' || 
                   2571:                 ! defined($name) || $name eq '') {
1.620     albertel 2572:                 my $cid = $env{'request.course.id'};
                   2573:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2574:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2575:             }
1.450     matthew  2576:             my $value = $accesshash{$entry};
                   2577:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2578:             my %temphash=($url => $value);
1.449     matthew  2579:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2580:             if ($result eq 'ok') {
                   2581:                 delete $accesshash{$entry};
                   2582:             } elsif ($result eq 'unknown_cmd') {
                   2583:                 # Target server has old code running on it.
1.450     matthew  2584:                 my %temphash=($entry => $value);
1.449     matthew  2585:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2586:                     delete $accesshash{$entry};
                   2587:                 }
                   2588:             }
                   2589:         } else {
1.811     albertel 2590:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2591:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2592:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2593:                 delete $accesshash{$entry};
                   2594:             }
1.185     www      2595:         }
1.191     harris41 2596:     }
1.352     www      2597: #
                   2598: # Roles
                   2599: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2600: #
1.800     albertel 2601:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2602:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2603: 	    split(/\:/,$entry);
                   2604:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2605:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2606:                 $rudom,$runame) eq 'ok') {
                   2607: 	    delete $userrolehash{$entry};
                   2608:         }
                   2609:     }
1.662     raeburn  2610: #
                   2611: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2612: #
                   2613:     my %domrolebuffer = ();
1.1000    raeburn  2614:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 2615:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2616:         if ($domrolebuffer{$rudom}) {
                   2617:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2618:                       '='.&escape($domainrolehash{$entry});
                   2619:         } else {
                   2620:             $domrolebuffer{$rudom}.=&escape($entry).
                   2621:                       '='.&escape($domainrolehash{$entry});
                   2622:         }
                   2623:         delete $domainrolehash{$entry};
                   2624:     }
                   2625:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2626: 	my %servers = &get_servers($dom,'library');
                   2627: 	foreach my $tryserver (keys(%servers)) {
                   2628: 	    unless (&reply('domroleput:'.$dom.':'.
                   2629: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2630: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2631: 	    }
1.662     raeburn  2632:         }
                   2633:     }
1.186     www      2634:     $dumpcount++;
1.157     www      2635: }
                   2636: 
                   2637: sub courselog {
                   2638:     my $what=shift;
1.158     www      2639:     $what=time.':'.$what;
1.620     albertel 2640:     unless ($env{'request.course.id'}) { return ''; }
                   2641:     $coursedombuf{$env{'request.course.id'}}=
                   2642:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2643:     $coursenumbuf{$env{'request.course.id'}}=
                   2644:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2645:     $coursehombuf{$env{'request.course.id'}}=
                   2646:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2647:     $coursedescrbuf{$env{'request.course.id'}}=
                   2648:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2649:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2650:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2651:     $courseownerbuf{$env{'request.course.id'}}=
                   2652:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2653:     $coursetypebuf{$env{'request.course.id'}}=
                   2654:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2655:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2656: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2657:     } else {
1.620     albertel 2658: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2659:     }
1.620     albertel 2660:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2661: 	&flushcourselogs();
                   2662:     }
1.158     www      2663: }
                   2664: 
                   2665: sub courseacclog {
                   2666:     my $fnsymb=shift;
1.620     albertel 2667:     unless ($env{'request.course.id'}) { return ''; }
                   2668:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2669:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2670:         $what.=':POST';
1.583     matthew  2671:         # FIXME: Probably ought to escape things....
1.800     albertel 2672: 	foreach my $key (keys(%env)) {
                   2673:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2674:                 my $formitem = $1;
                   2675:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2676:                     $what.=':'.$formitem.'='.$env{$key};
                   2677:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2678:                     $what.=':'.$formitem.'='.$env{$key};
                   2679:                 }
1.158     www      2680:             }
1.191     harris41 2681:         }
1.583     matthew  2682:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2683:         # FIXME: We should not be depending on a form parameter that someone
                   2684:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2685:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2686:             $what.= ':POST';
                   2687:             # FIXME: Probably ought to escape things....
                   2688:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2689:                                  'crsdiscuss') {
1.620     albertel 2690:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2691:             }
                   2692:         }
1.158     www      2693:     }
                   2694:     &courselog($what);
1.149     www      2695: }
                   2696: 
1.185     www      2697: sub countacc {
                   2698:     my $url=&declutter(shift);
1.458     matthew  2699:     return if (! defined($url) || $url eq '');
1.620     albertel 2700:     unless ($env{'request.course.id'}) { return ''; }
                   2701:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2702:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2703:     $accesshash{$key}++;
1.185     www      2704: }
1.349     www      2705: 
1.361     www      2706: sub linklog {
                   2707:     my ($from,$to)=@_;
                   2708:     $from=&declutter($from);
                   2709:     $to=&declutter($to);
                   2710:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2711:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2712: }
                   2713:   
1.349     www      2714: sub userrolelog {
                   2715:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2716:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2717:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2718:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2719:         ($trole=~/^ta/)) {
1.350     www      2720:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2721:        $userrolehash
                   2722:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2723:                     =$tend.':'.$tstart;
1.662     raeburn  2724:     }
1.898     albertel 2725:     if (($env{'request.role'} =~ /dc\./) &&
                   2726: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2727: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2728: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2729:        $userrolehash
                   2730:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2731:                     =$tend.':'.$tstart;
                   2732:     }
1.662     raeburn  2733:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2734:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2735:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2736:         ($trole=~/^sc/)) {
                   2737:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2738:        $domainrolehash
                   2739:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2740:                     = $tend.':'.$tstart;
                   2741:     }
1.351     www      2742: }
                   2743: 
1.957     raeburn  2744: sub courserolelog {
                   2745:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2746:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2747:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2748:         ($trole eq 'ta') || ($trole eq 'st') ||
                   2749:         ($trole=~/^cr/) || ($trole eq 'gr')) {
                   2750:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2751:             my $cdom = $1;
                   2752:             my $cnum = $2;
                   2753:             my $sec = $3;
                   2754:             my $namespace = 'rolelog';
                   2755:             my %storehash = (
                   2756:                                role    => $trole,
                   2757:                                start   => $tstart,
                   2758:                                end     => $tend,
                   2759:                                selfenroll => $selfenroll,
                   2760:                                context    => $context,
                   2761:                             );
                   2762:             if ($trole eq 'gr') {
                   2763:                 $namespace = 'groupslog';
                   2764:                 $storehash{'group'} = $sec;
                   2765:             } else {
                   2766:                 $storehash{'section'} = $sec;
                   2767:             }
                   2768:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  2769:             if (($trole ne 'st') || ($sec ne '')) {
                   2770:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   2771:             }
1.957     raeburn  2772:         }
                   2773:     }
                   2774:     return;
                   2775: }
                   2776: 
1.351     www      2777: sub get_course_adv_roles {
1.948     raeburn  2778:     my ($cid,$codes) = @_;
1.620     albertel 2779:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2780:     my %coursehash=&coursedescription($cid);
1.988     raeburn  2781:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      2782:     my %nothide=();
1.800     albertel 2783:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2784:         if ($user !~ /:/) {
                   2785: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2786:         } else {
                   2787:             $nothide{$user}=1;
                   2788:         }
1.470     www      2789:     }
1.351     www      2790:     my %returnhash=();
                   2791:     my %dumphash=
                   2792:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2793:     my $now=time;
1.997     raeburn  2794:     my %privileged;
1.1000    raeburn  2795:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 2796: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2797:         if (($tstart) && ($tstart<0)) { next; }
                   2798:         if (($tend) && ($tend<$now)) { next; }
                   2799:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2800:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2801: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  2802:         unless (ref($privileged{$domain}) eq 'HASH') {
                   2803:             my %dompersonnel =
1.998     raeburn  2804:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  2805:             $privileged{$domain} = {};
                   2806:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  2807:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  2808:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   2809:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   2810:                         $privileged{$udom}{$uname} = 1;
                   2811:                     }
                   2812:                 }
                   2813:             }
                   2814:         }
                   2815:         if ((exists($privileged{$domain}{$username})) && 
                   2816:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2817: 	if ($role eq 'cr') { next; }
1.948     raeburn  2818:         if ($codes) {
                   2819:             if ($section) { $role .= ':'.$section; }
                   2820:             if ($returnhash{$role}) {
                   2821:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2822:             } else {
                   2823:                 $returnhash{$role}=$username.':'.$domain;
                   2824:             }
1.351     www      2825:         } else {
1.988     raeburn  2826:             my $key=&plaintext($role,$crstype);
1.973     bisitz   2827:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  2828:             if ($returnhash{$key}) {
                   2829: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2830:             } else {
                   2831:                 $returnhash{$key}=$username.':'.$domain;
                   2832:             }
1.351     www      2833:         }
1.948     raeburn  2834:     }
1.400     www      2835:     return %returnhash;
                   2836: }
                   2837: 
                   2838: sub get_my_roles {
1.937     raeburn  2839:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2840:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2841:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2842:     my (%dumphash,%nothide);
1.858     raeburn  2843:     if ($context eq 'userroles') { 
                   2844:         %dumphash = &dump('roles',$udom,$uname);
                   2845:     } else {
                   2846:         %dumphash=
1.400     www      2847:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2848:         if ($hidepriv) {
                   2849:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2850:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2851:                 if ($user !~ /:/) {
                   2852:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2853:                 } else {
                   2854:                     $nothide{$user} = 1;
                   2855:                 }
                   2856:             }
                   2857:         }
1.858     raeburn  2858:     }
1.400     www      2859:     my %returnhash=();
                   2860:     my $now=time;
1.999     raeburn  2861:     my %privileged;
1.800     albertel 2862:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2863:         my ($role,$tend,$tstart);
                   2864:         if ($context eq 'userroles') {
                   2865: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2866:         } else {
                   2867:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2868:         }
1.400     www      2869:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2870:         my $status = 'active';
1.939     raeburn  2871:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2872:             $status = 'previous';
                   2873:         } 
                   2874:         if (($tstart) && ($now<$tstart)) {
                   2875:             $status = 'future';
                   2876:         }
                   2877:         if (ref($types) eq 'ARRAY') {
                   2878:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2879:                 next;
                   2880:             } 
                   2881:         } else {
                   2882:             if ($status ne 'active') {
                   2883:                 next;
                   2884:             }
                   2885:         }
1.867     raeburn  2886:         my ($rolecode,$username,$domain,$section,$area);
                   2887:         if ($context eq 'userroles') {
                   2888:             ($area,$rolecode) = split(/_/,$entry);
                   2889:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2890:         } else {
                   2891:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2892:         }
1.832     raeburn  2893:         if (ref($roledoms) eq 'ARRAY') {
                   2894:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2895:                 next;
                   2896:             }
                   2897:         }
                   2898:         if (ref($roles) eq 'ARRAY') {
                   2899:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2900:                 if ($role =~ /^cr\//) {
                   2901:                     if (!grep(/^cr$/,@{$roles})) {
                   2902:                         next;
                   2903:                     }
                   2904:                 } else {
                   2905:                     next;
                   2906:                 }
1.832     raeburn  2907:             }
1.867     raeburn  2908:         }
1.937     raeburn  2909:         if ($hidepriv) {
1.999     raeburn  2910:             if ($context eq 'userroles') {
                   2911:                 if ((&privileged($username,$domain)) &&
                   2912:                     (!$nothide{$username.':'.$domain})) {
                   2913:                     next;
                   2914:                 }
                   2915:             } else {
                   2916:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   2917:                     my %dompersonnel =
                   2918:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   2919:                     $privileged{$domain} = {};
                   2920:                     if (keys(%dompersonnel)) {
                   2921:                         foreach my $server (keys(%dompersonnel)) {
                   2922:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   2923:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   2924:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   2925:                                     $privileged{$udom}{$uname} = $trole;
                   2926:                                 }
                   2927:                             }
                   2928:                         }
                   2929:                     }
                   2930:                 }
                   2931:                 if (exists($privileged{$domain}{$username})) {
                   2932:                     if (!$nothide{$username.':'.$domain}) {
                   2933:                         next;
                   2934:                     }
                   2935:                 }
1.937     raeburn  2936:             }
                   2937:         }
1.933     raeburn  2938:         if ($withsec) {
                   2939:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2940:                 $tstart.':'.$tend;
                   2941:         } else {
                   2942:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2943:         }
1.832     raeburn  2944:     }
1.373     www      2945:     return %returnhash;
1.399     www      2946: }
                   2947: 
                   2948: # ----------------------------------------------------- Frontpage Announcements
                   2949: #
                   2950: #
                   2951: 
                   2952: sub postannounce {
                   2953:     my ($server,$text)=@_;
1.844     albertel 2954:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2955:     unless ($text=~/\w/) { $text=''; }
                   2956:     return &reply('setannounce:'.&escape($text),$server);
                   2957: }
                   2958: 
                   2959: sub getannounce {
1.448     albertel 2960: 
                   2961:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2962: 	my $announcement='';
1.800     albertel 2963: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2964: 	close($fh);
1.399     www      2965: 	if ($announcement=~/\w/) { 
                   2966: 	    return 
                   2967:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2968:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2969: 	} else {
                   2970: 	    return '';
                   2971: 	}
                   2972:     } else {
                   2973: 	return '';
                   2974:     }
1.351     www      2975: }
1.353     www      2976: 
                   2977: # ---------------------------------------------------------- Course ID routines
                   2978: # Deal with domain's nohist_courseid.db files
                   2979: #
                   2980: 
                   2981: sub courseidput {
1.921     raeburn  2982:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2983:     my $outcome;
                   2984:     if ($caller eq 'timeonly') {
                   2985:         my $cids = '';
                   2986:         foreach my $item (keys(%$storehash)) {
                   2987:             $cids.=&escape($item).'&';
                   2988:         }
                   2989:         $cids=~s/\&$//;
                   2990:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2991:                           $coursehome);       
                   2992:     } else {
                   2993:         my $items = '';
                   2994:         foreach my $item (keys(%$storehash)) {
                   2995:             $items.= &escape($item).'='.
                   2996:                      &freeze_escape($$storehash{$item}).'&';
                   2997:         }
                   2998:         $items=~s/\&$//;
                   2999:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3000:                           $coursehome);
1.918     raeburn  3001:     }
                   3002:     if ($outcome eq 'unknown_cmd') {
                   3003:         my $what;
                   3004:         foreach my $cid (keys(%$storehash)) {
                   3005:             $what .= &escape($cid).'=';
1.921     raeburn  3006:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3007:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3008:             }
                   3009:             $what =~ s/\:$/&/;
                   3010:         }
                   3011:         $what =~ s/\&$//;  
                   3012:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3013:     } else {
                   3014:         return $outcome;
                   3015:     }
1.353     www      3016: }
                   3017: 
                   3018: sub courseiddump {
1.921     raeburn  3019:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3020:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1008    raeburn  3021:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,$cloneonly)=@_;
1.918     raeburn  3022:     my $as_hash = 1;
                   3023:     my %returnhash;
                   3024:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3025:     my %libserv = &all_library();
                   3026:     foreach my $tryserver (keys(%libserv)) {
                   3027:         if ( (  $hostidflag == 1 
                   3028: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3029: 	     || (!defined($hostidflag)) ) {
                   3030: 
1.918     raeburn  3031: 	    if (($domfilter eq '') ||
                   3032: 		(&host_domain($tryserver) eq $domfilter)) {
                   3033:                 my $rep = 
                   3034:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3035:                          $sincefilter.':'.&escape($descfilter).':'.
                   3036:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3037:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3038:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3039:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3040:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   3041:                          &escape($cc_clone).':'.$cloneonly,$tryserver);
1.918     raeburn  3042:                 my @pairs=split(/\&/,$rep);
                   3043:                 foreach my $item (@pairs) {
                   3044:                     my ($key,$value)=split(/\=/,$item,2);
                   3045:                     $key = &unescape($key);
                   3046:                     next if ($key =~ /^error: 2 /);
                   3047:                     my $result = &thaw_unescape($value);
                   3048:                     if (ref($result) eq 'HASH') {
                   3049:                         $returnhash{$key}=$result;
                   3050:                     } else {
1.921     raeburn  3051:                         my @responses = split(/:/,$value);
                   3052:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3053:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3054:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3055:                         }
1.1008    raeburn  3056:                     }
1.353     www      3057:                 }
                   3058:             }
                   3059:         }
                   3060:     }
                   3061:     return %returnhash;
                   3062: }
                   3063: 
1.658     raeburn  3064: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3065: 
                   3066: sub dcmailput {
1.685     raeburn  3067:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3068:     my $status = &Apache::lonnet::critical(
1.740     www      3069:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3070:        &escape($message),$server);
1.662     raeburn  3071:     return $status;
                   3072: }
                   3073: 
1.658     raeburn  3074: sub dcmaildump {
                   3075:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3076:     my %returnhash=();
1.846     albertel 3077: 
                   3078:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3079:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3080:                                                          &escape($enddate).':';
                   3081: 	my @esc_senders=map { &escape($_)} @$senders;
                   3082: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3083: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3084:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3085:             if (($key) && ($value)) {
                   3086:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3087:             }
                   3088:         }
                   3089:     }
                   3090:     return %returnhash;
                   3091: }
1.662     raeburn  3092: # ---------------------------------------------------------- Domain roles
                   3093: 
                   3094: sub get_domain_roles {
                   3095:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3096:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3097:         $startdate = '.';
                   3098:     }
1.1018    raeburn  3099:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3100:         $enddate = '.';
                   3101:     }
1.922     raeburn  3102:     my $rolelist;
                   3103:     if (ref($roles) eq 'ARRAY') {
                   3104:         $rolelist = join(':',@{$roles});
                   3105:     }
1.662     raeburn  3106:     my %personnel = ();
1.841     albertel 3107: 
                   3108:     my %servers = &get_servers($dom,'library');
                   3109:     foreach my $tryserver (keys(%servers)) {
                   3110: 	%{$personnel{$tryserver}}=();
                   3111: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3112: 					    &escape($startdate).':'.
                   3113: 					    &escape($enddate).':'.
                   3114: 					    &escape($rolelist), $tryserver))) {
                   3115: 	    my ($key,$value) = split(/\=/,$line,2);
                   3116: 	    if (($key) && ($value)) {
                   3117: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3118: 	    }
                   3119: 	}
1.662     raeburn  3120:     }
                   3121:     return %personnel;
                   3122: }
1.658     raeburn  3123: 
1.149     www      3124: # ----------------------------------------------------------- Check out an item
                   3125: 
1.504     albertel 3126: sub get_first_access {
                   3127:     my ($type,$argsymb)=@_;
1.790     albertel 3128:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3129:     if ($argsymb) { $symb=$argsymb; }
                   3130:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3131:     if ($type eq 'course') {
                   3132: 	$res='course';
                   3133:     } elsif ($type eq 'map') {
1.588     albertel 3134: 	$res=&symbread($map);
                   3135:     } else {
                   3136: 	$res=$symb;
                   3137:     }
                   3138:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3139:     return $times{"$courseid\0$res"};
1.504     albertel 3140: }
                   3141: 
                   3142: sub set_first_access {
                   3143:     my ($type)=@_;
1.790     albertel 3144:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3145:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3146:     if ($type eq 'course') {
                   3147: 	$res='course';
                   3148:     } elsif ($type eq 'map') {
1.588     albertel 3149: 	$res=&symbread($map);
                   3150:     } else {
                   3151: 	$res=$symb;
                   3152:     }
                   3153:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3154:     if (!$firstaccess) {
1.588     albertel 3155: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3156:     }
                   3157:     return 'already_set';
1.504     albertel 3158: }
                   3159: 
1.149     www      3160: sub checkout {
                   3161:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   3162:     my $now=time;
                   3163:     my $lonhost=$perlvar{'lonHostID'};
                   3164:     my $infostr=&escape(
1.234     www      3165:                  'CHECKOUTTOKEN&'.
1.149     www      3166:                  $tuname.'&'.
                   3167:                  $tudom.'&'.
                   3168:                  $tcrsid.'&'.
                   3169:                  $symb.'&'.
                   3170: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   3171:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      3172:     if ($token=~/^error\:/) { 
1.672     albertel 3173:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3174:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3175:                  "</font>");
                   3176:         return ''; 
                   3177:     }
                   3178: 
1.149     www      3179:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   3180:     $token=~tr/a-z/A-Z/;
                   3181: 
1.153     www      3182:     my %infohash=('resource.0.outtoken' => $token,
                   3183:                   'resource.0.checkouttime' => $now,
                   3184:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      3185: 
                   3186:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3187:        return '';
1.151     www      3188:     } else {
1.672     albertel 3189:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3190:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3191:                  "</font>");
1.149     www      3192:     }    
                   3193: 
                   3194:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3195:                          &escape('Checkout '.$infostr.' - '.
                   3196:                                                  $token)) ne 'ok') {
                   3197: 	return '';
1.151     www      3198:     } else {
1.672     albertel 3199:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3200:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3201:                  "</font>");
1.149     www      3202:     }
1.151     www      3203:     return $token;
1.149     www      3204: }
                   3205: 
                   3206: # ------------------------------------------------------------ Check in an item
                   3207: 
                   3208: sub checkin {
                   3209:     my $token=shift;
1.150     www      3210:     my $now=time;
                   3211:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3212:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3213:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3214:     $dtoken=~s/\W/\_/g;
1.234     www      3215:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3216:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3217: 
1.154     www      3218:     unless (($tuname) && ($tudom)) {
                   3219:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3220:         return '';
                   3221:     }
                   3222:     
                   3223:     unless (&allowed('mgr',$tcrsid)) {
                   3224:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3225:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3226:         return '';
                   3227:     }
                   3228: 
1.153     www      3229:     my %infohash=('resource.0.intoken' => $token,
                   3230:                   'resource.0.checkintime' => $now,
                   3231:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3232: 
                   3233:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3234:        return '';
                   3235:     }    
                   3236: 
                   3237:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3238:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3239: 	return '';
                   3240:     }
                   3241: 
                   3242:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3243: }
                   3244: 
                   3245: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3246: 
                   3247: sub expirespread {
                   3248:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3249:     my $cid=$env{'request.course.id'}; 
1.110     www      3250:     if ($cid) {
                   3251:        my $now=time;
                   3252:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3253:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3254:                             $env{'course.'.$cid.'.num'}.
1.110     www      3255: 	        	    ':nohist_expirationdates:'.
                   3256:                             &escape($key).'='.$now,
1.620     albertel 3257:                             $env{'course.'.$cid.'.home'})
1.110     www      3258:     }
                   3259:     return 'ok';
1.14      www      3260: }
                   3261: 
1.109     www      3262: # ----------------------------------------------------- Devalidate Spreadsheets
                   3263: 
                   3264: sub devalidate {
1.325     www      3265:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3266:     my $cid=$env{'request.course.id'}; 
1.109     www      3267:     if ($cid) {
1.391     matthew  3268:         # delete the stored spreadsheets for
                   3269:         # - the student level sheet of this user in course's homespace
                   3270:         # - the assessment level sheet for this resource 
                   3271:         #   for this user in user's homespace
1.553     albertel 3272: 	# - current conditional state info
1.325     www      3273: 	my $key=$uname.':'.$udom.':';
1.109     www      3274:         my $status=
1.299     matthew  3275: 	    &del('nohist_calculatedsheets',
1.391     matthew  3276: 		 [$key.'studentcalc:'],
1.620     albertel 3277: 		 $env{'course.'.$cid.'.domain'},
                   3278: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3279: 		.' '.
                   3280: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3281: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3282:         unless ($status eq 'ok ok') {
                   3283:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3284:                     $uname.' at '.$udom.' for '.
1.109     www      3285: 		    $symb.': '.$status);
1.133     albertel 3286:         }
1.553     albertel 3287: 	&delenv('user.state.'.$cid);
1.109     www      3288:     }
                   3289: }
                   3290: 
1.265     albertel 3291: sub get_scalar {
                   3292:     my ($string,$end) = @_;
                   3293:     my $value;
                   3294:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3295: 	$value = $1;
                   3296:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3297: 	$value = $1;
                   3298:     }
                   3299:     return &unescape($value);
                   3300: }
                   3301: 
                   3302: sub array2str {
                   3303:   my (@array) = @_;
                   3304:   my $result=&arrayref2str(\@array);
                   3305:   $result=~s/^__ARRAY_REF__//;
                   3306:   $result=~s/__END_ARRAY_REF__$//;
                   3307:   return $result;
                   3308: }
                   3309: 
1.204     albertel 3310: sub arrayref2str {
                   3311:   my ($arrayref) = @_;
1.265     albertel 3312:   my $result='__ARRAY_REF__';
1.204     albertel 3313:   foreach my $elem (@$arrayref) {
1.265     albertel 3314:     if(ref($elem) eq 'ARRAY') {
                   3315:       $result.=&arrayref2str($elem).'&';
                   3316:     } elsif(ref($elem) eq 'HASH') {
                   3317:       $result.=&hashref2str($elem).'&';
                   3318:     } elsif(ref($elem)) {
                   3319:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3320:     } else {
                   3321:       $result.=&escape($elem).'&';
                   3322:     }
                   3323:   }
                   3324:   $result=~s/\&$//;
1.265     albertel 3325:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3326:   return $result;
                   3327: }
                   3328: 
1.168     albertel 3329: sub hash2str {
1.204     albertel 3330:   my (%hash) = @_;
                   3331:   my $result=&hashref2str(\%hash);
1.265     albertel 3332:   $result=~s/^__HASH_REF__//;
                   3333:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3334:   return $result;
                   3335: }
                   3336: 
                   3337: sub hashref2str {
                   3338:   my ($hashref)=@_;
1.265     albertel 3339:   my $result='__HASH_REF__';
1.800     albertel 3340:   foreach my $key (sort(keys(%$hashref))) {
                   3341:     if (ref($key) eq 'ARRAY') {
                   3342:       $result.=&arrayref2str($key).'=';
                   3343:     } elsif (ref($key) eq 'HASH') {
                   3344:       $result.=&hashref2str($key).'=';
                   3345:     } elsif (ref($key)) {
1.265     albertel 3346:       $result.='=';
1.800     albertel 3347:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3348:     } else {
1.800     albertel 3349: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3350:     }
                   3351: 
1.800     albertel 3352:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3353:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3354:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3355:       $result.=&hashref2str($hashref->{$key}).'&';
                   3356:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3357:        $result.='&';
1.800     albertel 3358:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3359:     } else {
1.800     albertel 3360:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3361:     }
                   3362:   }
1.168     albertel 3363:   $result=~s/\&$//;
1.265     albertel 3364:   $result .= '__END_HASH_REF__';
1.168     albertel 3365:   return $result;
                   3366: }
                   3367: 
                   3368: sub str2hash {
1.265     albertel 3369:     my ($string)=@_;
                   3370:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3371:     return %$hash;
                   3372: }
                   3373: 
                   3374: sub str2hashref {
1.168     albertel 3375:   my ($string) = @_;
1.265     albertel 3376: 
                   3377:   my %hash;
                   3378: 
                   3379:   if($string !~ /^__HASH_REF__/) {
                   3380:       if (! ($string eq '' || !defined($string))) {
                   3381: 	  $hash{'error'}='Not hash reference';
                   3382:       }
                   3383:       return (\%hash, $string);
                   3384:   }
                   3385: 
                   3386:   $string =~ s/^__HASH_REF__//;
                   3387: 
                   3388:   while($string !~ /^__END_HASH_REF__/) {
                   3389:       #key
                   3390:       my $key='';
                   3391:       if($string =~ /^__HASH_REF__/) {
                   3392:           ($key, $string)=&str2hashref($string);
                   3393:           if(defined($key->{'error'})) {
                   3394:               $hash{'error'}='Bad data';
                   3395:               return (\%hash, $string);
                   3396:           }
                   3397:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3398:           ($key, $string)=&str2arrayref($string);
                   3399:           if($key->[0] eq 'Array reference error') {
                   3400:               $hash{'error'}='Bad data';
                   3401:               return (\%hash, $string);
                   3402:           }
                   3403:       } else {
                   3404:           $string =~ s/^(.*?)=//;
1.267     albertel 3405: 	  $key=&unescape($1);
1.265     albertel 3406:       }
                   3407:       $string =~ s/^=//;
                   3408: 
                   3409:       #value
                   3410:       my $value='';
                   3411:       if($string =~ /^__HASH_REF__/) {
                   3412:           ($value, $string)=&str2hashref($string);
                   3413:           if(defined($value->{'error'})) {
                   3414:               $hash{'error'}='Bad data';
                   3415:               return (\%hash, $string);
                   3416:           }
                   3417:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3418:           ($value, $string)=&str2arrayref($string);
                   3419:           if($value->[0] eq 'Array reference error') {
                   3420:               $hash{'error'}='Bad data';
                   3421:               return (\%hash, $string);
                   3422:           }
                   3423:       } else {
                   3424: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3425:       }
                   3426:       $string =~ s/^&//;
                   3427: 
                   3428:       $hash{$key}=$value;
1.204     albertel 3429:   }
1.265     albertel 3430: 
                   3431:   $string =~ s/^__END_HASH_REF__//;
                   3432: 
                   3433:   return (\%hash, $string);
1.204     albertel 3434: }
                   3435: 
                   3436: sub str2array {
1.265     albertel 3437:     my ($string)=@_;
                   3438:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3439:     return @$array;
                   3440: }
                   3441: 
                   3442: sub str2arrayref {
1.204     albertel 3443:   my ($string) = @_;
1.265     albertel 3444:   my @array;
                   3445: 
                   3446:   if($string !~ /^__ARRAY_REF__/) {
                   3447:       if (! ($string eq '' || !defined($string))) {
                   3448: 	  $array[0]='Array reference error';
                   3449:       }
                   3450:       return (\@array, $string);
                   3451:   }
                   3452: 
                   3453:   $string =~ s/^__ARRAY_REF__//;
                   3454: 
                   3455:   while($string !~ /^__END_ARRAY_REF__/) {
                   3456:       my $value='';
                   3457:       if($string =~ /^__HASH_REF__/) {
                   3458:           ($value, $string)=&str2hashref($string);
                   3459:           if(defined($value->{'error'})) {
                   3460:               $array[0] ='Array reference error';
                   3461:               return (\@array, $string);
                   3462:           }
                   3463:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3464:           ($value, $string)=&str2arrayref($string);
                   3465:           if($value->[0] eq 'Array reference error') {
                   3466:               $array[0] ='Array reference error';
                   3467:               return (\@array, $string);
                   3468:           }
                   3469:       } else {
                   3470: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3471:       }
                   3472:       $string =~ s/^&//;
                   3473: 
                   3474:       push(@array, $value);
1.191     harris41 3475:   }
1.265     albertel 3476: 
                   3477:   $string =~ s/^__END_ARRAY_REF__//;
                   3478: 
                   3479:   return (\@array, $string);
1.168     albertel 3480: }
                   3481: 
1.167     albertel 3482: # -------------------------------------------------------------------Temp Store
                   3483: 
1.168     albertel 3484: sub tmpreset {
                   3485:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3486:   if (!$symb) {
                   3487:     $symb=&symbread();
1.620     albertel 3488:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3489:   }
                   3490:   $symb=escape($symb);
                   3491: 
1.620     albertel 3492:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3493:   $namespace=~s/\//\_/g;
                   3494:   $namespace=~s/\W//g;
                   3495: 
1.620     albertel 3496:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3497:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3498:   if ($domain eq 'public' && $stuname eq 'public') {
                   3499:       $stuname=$ENV{'REMOTE_ADDR'};
                   3500:   }
1.168     albertel 3501:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3502:   my %hash;
                   3503:   if (tie(%hash,'GDBM_File',
                   3504: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3505: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3506:     foreach my $key (keys(%hash)) {
1.180     albertel 3507:       if ($key=~ /:$symb/) {
1.168     albertel 3508: 	delete($hash{$key});
                   3509:       }
                   3510:     }
                   3511:   }
                   3512: }
                   3513: 
1.167     albertel 3514: sub tmpstore {
1.168     albertel 3515:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3516: 
                   3517:   if (!$symb) {
                   3518:     $symb=&symbread();
1.620     albertel 3519:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3520:   }
                   3521:   $symb=escape($symb);
                   3522: 
                   3523:   if (!$namespace) {
                   3524:     # I don't think we would ever want to store this for a course.
                   3525:     # it seems this will only be used if we don't have a course.
1.620     albertel 3526:     #$namespace=$env{'request.course.id'};
1.168     albertel 3527:     #if (!$namespace) {
1.620     albertel 3528:       $namespace=$env{'request.state'};
1.168     albertel 3529:     #}
                   3530:   }
                   3531:   $namespace=~s/\//\_/g;
                   3532:   $namespace=~s/\W//g;
1.620     albertel 3533:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3534:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3535:   if ($domain eq 'public' && $stuname eq 'public') {
                   3536:       $stuname=$ENV{'REMOTE_ADDR'};
                   3537:   }
1.168     albertel 3538:   my $now=time;
                   3539:   my %hash;
                   3540:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3541:   if (tie(%hash,'GDBM_File',
                   3542: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3543: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3544:     $hash{"version:$symb"}++;
                   3545:     my $version=$hash{"version:$symb"};
                   3546:     my $allkeys=''; 
                   3547:     foreach my $key (keys(%$storehash)) {
                   3548:       $allkeys.=$key.':';
1.591     albertel 3549:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3550:     }
                   3551:     $hash{"$version:$symb:timestamp"}=$now;
                   3552:     $allkeys.='timestamp';
                   3553:     $hash{"$version:keys:$symb"}=$allkeys;
                   3554:     if (untie(%hash)) {
                   3555:       return 'ok';
                   3556:     } else {
                   3557:       return "error:$!";
                   3558:     }
                   3559:   } else {
                   3560:     return "error:$!";
                   3561:   }
                   3562: }
1.167     albertel 3563: 
1.168     albertel 3564: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3565: 
1.168     albertel 3566: sub tmprestore {
                   3567:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3568: 
1.168     albertel 3569:   if (!$symb) {
                   3570:     $symb=&symbread();
1.620     albertel 3571:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3572:   }
                   3573:   $symb=escape($symb);
                   3574: 
1.620     albertel 3575:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3576: 
1.620     albertel 3577:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3578:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3579:   if ($domain eq 'public' && $stuname eq 'public') {
                   3580:       $stuname=$ENV{'REMOTE_ADDR'};
                   3581:   }
1.168     albertel 3582:   my %returnhash;
                   3583:   $namespace=~s/\//\_/g;
                   3584:   $namespace=~s/\W//g;
                   3585:   my %hash;
                   3586:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3587:   if (tie(%hash,'GDBM_File',
                   3588: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3589: 	  &GDBM_READER(),0640)) {
1.168     albertel 3590:     my $version=$hash{"version:$symb"};
                   3591:     $returnhash{'version'}=$version;
                   3592:     my $scope;
                   3593:     for ($scope=1;$scope<=$version;$scope++) {
                   3594:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3595:       my @keys=split(/:/,$vkeys);
                   3596:       my $key;
                   3597:       $returnhash{"$scope:keys"}=$vkeys;
                   3598:       foreach $key (@keys) {
1.591     albertel 3599: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3600: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3601:       }
                   3602:     }
1.168     albertel 3603:     if (!(untie(%hash))) {
                   3604:       return "error:$!";
                   3605:     }
                   3606:   } else {
                   3607:     return "error:$!";
                   3608:   }
                   3609:   return %returnhash;
1.167     albertel 3610: }
                   3611: 
1.9       www      3612: # ----------------------------------------------------------------------- Store
                   3613: 
                   3614: sub store {
1.124     www      3615:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3616:     my $home='';
                   3617: 
1.168     albertel 3618:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3619: 
1.213     www      3620:     $symb=&symbclean($symb);
1.122     albertel 3621:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3622: 
1.620     albertel 3623:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3624:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3625: 
                   3626:     &devalidate($symb,$stuname,$domain);
1.109     www      3627: 
                   3628:     $symb=escape($symb);
1.187     www      3629:     if (!$namespace) { 
1.620     albertel 3630:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3631:           return ''; 
                   3632:        } 
                   3633:     }
1.620     albertel 3634:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3635: 
                   3636:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3637:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3638: 
1.12      www      3639:     my $namevalue='';
1.800     albertel 3640:     foreach my $key (keys(%$storehash)) {
                   3641:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3642:     }
1.12      www      3643:     $namevalue=~s/\&$//;
1.187     www      3644:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3645:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3646: }
                   3647: 
1.47      www      3648: # -------------------------------------------------------------- Critical Store
                   3649: 
                   3650: sub cstore {
1.124     www      3651:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3652:     my $home='';
                   3653: 
1.168     albertel 3654:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3655: 
1.213     www      3656:     $symb=&symbclean($symb);
1.122     albertel 3657:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3658: 
1.620     albertel 3659:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3660:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3661: 
                   3662:     &devalidate($symb,$stuname,$domain);
1.109     www      3663: 
                   3664:     $symb=escape($symb);
1.187     www      3665:     if (!$namespace) { 
1.620     albertel 3666:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3667:           return ''; 
                   3668:        } 
                   3669:     }
1.620     albertel 3670:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3671: 
                   3672:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3673:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3674: 
1.47      www      3675:     my $namevalue='';
1.800     albertel 3676:     foreach my $key (keys(%$storehash)) {
                   3677:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3678:     }
1.47      www      3679:     $namevalue=~s/\&$//;
1.187     www      3680:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3681:     return critical
                   3682:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3683: }
                   3684: 
1.9       www      3685: # --------------------------------------------------------------------- Restore
                   3686: 
                   3687: sub restore {
1.124     www      3688:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3689:     my $home='';
                   3690: 
1.168     albertel 3691:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3692: 
1.122     albertel 3693:     if (!$symb) {
                   3694:       unless ($symb=escape(&symbread())) { return ''; }
                   3695:     } else {
1.213     www      3696:       $symb=&escape(&symbclean($symb));
1.122     albertel 3697:     }
1.188     www      3698:     if (!$namespace) { 
1.620     albertel 3699:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3700:           return ''; 
                   3701:        } 
                   3702:     }
1.620     albertel 3703:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3704:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3705:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3706:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3707: 
1.12      www      3708:     my %returnhash=();
1.800     albertel 3709:     foreach my $line (split(/\&/,$answer)) {
                   3710: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3711:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3712:     }
1.75      www      3713:     my $version;
                   3714:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3715:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3716:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3717:        }
1.75      www      3718:     }
1.13      www      3719:     return %returnhash;
1.34      www      3720: }
                   3721: 
                   3722: # ---------------------------------------------------------- Course Description
                   3723: 
                   3724: sub coursedescription {
1.731     albertel 3725:     my ($courseid,$args)=@_;
1.34      www      3726:     $courseid=~s/^\///;
1.49      www      3727:     $courseid=~s/\_/\//g;
1.34      www      3728:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3729:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3730:     my $normalid=$cdomain.'_'.$cnum;
                   3731:     # need to always cache even if we get errors otherwise we keep 
                   3732:     # trying and trying and trying to get the course description.
                   3733:     my %envhash=();
                   3734:     my %returnhash=();
1.731     albertel 3735:     
                   3736:     my $expiretime=600;
                   3737:     if ($env{'request.course.id'} eq $normalid) {
                   3738: 	$expiretime=120;
                   3739:     }
                   3740: 
                   3741:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3742:     if (!$args->{'freshen_cache'}
                   3743: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3744: 	foreach my $key (keys(%env)) {
                   3745: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3746: 	    my ($setting) = $1;
                   3747: 	    $returnhash{$setting} = $env{$key};
                   3748: 	}
                   3749: 	return %returnhash;
                   3750:     }
                   3751: 
                   3752:     # get the data agin
                   3753:     if (!$args->{'one_time'}) {
                   3754: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3755:     }
1.811     albertel 3756: 
1.34      www      3757:     if ($chome ne 'no_host') {
1.302     albertel 3758:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3759:        if (!exists($returnhash{'con_lost'})) {
                   3760:            $returnhash{'home'}= $chome;
                   3761: 	   $returnhash{'domain'} = $cdomain;
                   3762: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3763:            if (!defined($returnhash{'type'})) {
                   3764:                $returnhash{'type'} = 'Course';
                   3765:            }
1.130     albertel 3766:            while (my ($name,$value) = each %returnhash) {
1.53      www      3767:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3768:            }
1.270     www      3769:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3770:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3771: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3772:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3773:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3774:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3775:        }
                   3776:     }
1.731     albertel 3777:     if (!$args->{'one_time'}) {
1.949     raeburn  3778: 	&appenv(\%envhash);
1.731     albertel 3779:     }
1.302     albertel 3780:     return %returnhash;
1.461     www      3781: }
                   3782: 
                   3783: # -------------------------------------------------See if a user is privileged
                   3784: 
                   3785: sub privileged {
                   3786:     my ($username,$domain)=@_;
                   3787:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3788: 			&homeserver($username,$domain));
                   3789:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3790:     my $now=time;
                   3791:     if ($rolesdump ne '') {
1.800     albertel 3792:         foreach my $entry (split(/&/,$rolesdump)) {
                   3793: 	    if ($entry!~/^rolesdef_/) {
                   3794: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3795: 		$area=~s/\_\w\w$//;
                   3796: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3797: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3798: 		    my $active=1;
                   3799: 		    if ($tend) {
                   3800: 			if ($tend<$now) { $active=0; }
                   3801: 		    }
                   3802: 		    if ($tstart) {
                   3803: 			if ($tstart>$now) { $active=0; }
                   3804: 		    }
                   3805: 		    if ($active) { return 1; }
                   3806: 		}
                   3807: 	    }
                   3808: 	}
                   3809:     }
                   3810:     return 0;
1.9       www      3811: }
1.1       albertel 3812: 
1.103     harris41 3813: # -------------------------------------------------------- Get user privileges
1.11      www      3814: 
                   3815: sub rolesinit {
                   3816:     my ($domain,$username,$authhost)=@_;
1.966     raeburn  3817:     my %userroles;
1.11      www      3818:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.966     raeburn  3819:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
1.11      www      3820:     my %allroles=();
1.678     raeburn  3821:     my %allgroups=();   
1.11      www      3822:     my $now=time;
1.966     raeburn  3823:     %userroles = ('user.login.time' => $now);
1.678     raeburn  3824:     my $group_privs;
1.11      www      3825: 
                   3826:     if ($rolesdump ne '') {
1.800     albertel 3827:         foreach my $entry (split(/&/,$rolesdump)) {
                   3828: 	  if ($entry!~/^rolesdef_/) {
                   3829:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3830: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3831:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3832: 	    if ($role=~/^cr/) { 
1.807     albertel 3833: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3834: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3835: 		    ($tend,$tstart)=split('_',$trest);
                   3836: 		} else {
                   3837: 		    $trole=$role;
                   3838: 		}
1.678     raeburn  3839:             } elsif ($role =~ m|^gr/|) {
                   3840:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3841:                 ($trole,$group_privs) = split(/\//,$trole);
                   3842:                 $group_privs = &unescape($group_privs);
1.587     albertel 3843: 	    } else {
                   3844: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3845: 	    }
1.743     albertel 3846: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3847: 					 $username);
                   3848: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3849:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3850:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3851:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3852: 		my $spec=$trole.'.'.$area;
                   3853: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3854: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3855:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3856:                 } elsif ($trole eq 'gr') {
                   3857:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3858: 		} else {
1.567     raeburn  3859:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3860: 		}
1.12      www      3861:             }
1.662     raeburn  3862:           }
1.191     harris41 3863:         }
1.743     albertel 3864:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3865:         $userroles{'user.adv'}    = $adv;
                   3866: 	$userroles{'user.author'} = $author;
1.620     albertel 3867:         $env{'user.adv'}=$adv;
1.11      www      3868:     }
1.743     albertel 3869:     return \%userroles;  
1.11      www      3870: }
                   3871: 
1.567     raeburn  3872: sub set_arearole {
                   3873:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3874: # log the associated role with the area
                   3875:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3876:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3877: }
                   3878: 
                   3879: sub custom_roleprivs {
                   3880:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3881:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3882:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3883:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3884:         my ($rdummy,$roledef)=
                   3885:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3886:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3887:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3888:             if (defined($syspriv)) {
                   3889:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3890:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3891:             }
                   3892:             if ($tdomain ne '') {
                   3893:                 if (defined($dompriv)) {
                   3894:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3895:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3896:                 }
                   3897:                 if (($trest ne '') && (defined($coursepriv))) {
                   3898:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3899:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3900:                 }
                   3901:             }
                   3902:         }
                   3903:     }
                   3904: }
                   3905: 
1.678     raeburn  3906: sub group_roleprivs {
                   3907:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3908:     my $access = 1;
                   3909:     my $now = time;
                   3910:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3911:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3912:     if ($access) {
1.811     albertel 3913:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3914:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3915:     }
                   3916: }
1.567     raeburn  3917: 
                   3918: sub standard_roleprivs {
                   3919:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3920:     if (defined($pr{$trole.':s'})) {
                   3921:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3922:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3923:     }
                   3924:     if ($tdomain ne '') {
                   3925:         if (defined($pr{$trole.':d'})) {
                   3926:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3927:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3928:         }
                   3929:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3930:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3931:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3932:         }
                   3933:     }
                   3934: }
                   3935: 
                   3936: sub set_userprivs {
1.678     raeburn  3937:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3938:     my $author=0;
                   3939:     my $adv=0;
1.678     raeburn  3940:     my %grouproles = ();
                   3941:     if (keys(%{$allgroups}) > 0) {
1.1000    raeburn  3942:         foreach my $role (keys(%{$allroles})) {
1.681     raeburn  3943:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3944:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3945:                 $trole = $1;
                   3946:                 $area = $2;
1.681     raeburn  3947:                 $sec = $3;
                   3948:                 $extendedarea = $area.$sec;
                   3949:                 if (exists($$allgroups{$area})) {
                   3950:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3951:                         my $spec = $trole.'.'.$extendedarea;
                   3952:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3953:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3954:                     }
                   3955:                 }
                   3956:             }
                   3957:         }
                   3958:     }
1.800     albertel 3959:     foreach my $group (keys(%grouproles)) {
                   3960:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3961:     }
1.800     albertel 3962:     foreach my $role (keys(%{$allroles})) {
                   3963:         my %thesepriv;
1.941     raeburn  3964:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3965:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3966:             if ($item ne '') {
                   3967:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3968:                 if ($restrictions eq '') {
                   3969:                     $thesepriv{$privilege}='F';
                   3970:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3971:                     $thesepriv{$privilege}.=$restrictions;
                   3972:                 }
                   3973:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3974:             }
                   3975:         }
                   3976:         my $thesestr='';
1.800     albertel 3977:         foreach my $priv (keys(%thesepriv)) {
                   3978: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3979: 	}
                   3980:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3981:     }
                   3982:     return ($author,$adv);
                   3983: }
                   3984: 
1.994     raeburn  3985: sub role_status {
1.1002    raeburn  3986:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  3987:     my @pwhere = ();
                   3988:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   3989:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   3990:         unless (!defined($$role) || $$role eq '') {
                   3991:             $$where=join('.',@pwhere);
                   3992:             $$trolecode=$$role.'.'.$$where;
                   3993:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   3994:             $$tstatus='is';
                   3995:             if ($$tstart && $$tstart>$then) {
                   3996:                 $$tstatus='future';
1.1002    raeburn  3997:                 if ($$tstart && $$tstart>$refresh) {
                   3998:                     if ($$tstart<$now) {
                   3999:                         if (($$where ne '') && ($$role ne '')) {
                   4000:                             my (%allroles,%allgroups,$group_privs);
                   4001:                             my %userroles = (
                   4002:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4003:                             );
                   4004:                             my $spec=$$role.'.'.$$where;
                   4005:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4006:                             if ($$role eq 'gr') {
                   4007:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4008:                                                     $env{'user.name'})=@_;
                   4009:                                 my ($trole) = split('_',$role,1);
                   4010:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4011:                                 $group_privs = &unescape($group_privs);
                   4012:                             }
                   4013:                             if ($$role =~ /^cr\//) {
                   4014:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
                   4015:                             } elsif ($$role eq 'gr') {
                   4016:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4017:                                                     $env{'user.name'});
                   4018:                                 my $trole = split('_',$rolehash{$$where.'_'.$$role},1);
                   4019:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4020:                                 $group_privs = &unescape($group_privs);
                   4021:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
                   4022:                             } else {
                   4023:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4024:                             }
                   4025:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4026:                             &appenv(\%userroles,[$$role,'cm']);
                   4027:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4028:                             $$tstatus = 'is';
                   4029:                         }
                   4030:                     }
                   4031:                 }
1.994     raeburn  4032:             }
                   4033:             if ($$tend) {
                   4034:                 if ($$tend<$then) {
                   4035:                     $$tstatus='expired';
                   4036:                 } elsif ($$tend<$now) {
                   4037:                     $$tstatus='will_not';
                   4038:                 }
                   4039:             }
                   4040:         }
                   4041:     }
                   4042: }
                   4043: 
                   4044: sub check_adhoc_privs {
1.1002    raeburn  4045:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
1.994     raeburn  4046:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4047:     if ($env{$cckey}) {
                   4048:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002    raeburn  4049:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4050:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
                   4051:             &set_adhoc_privileges($cdom,$cnum,$checkrole);
                   4052:         }
                   4053:     } else {
                   4054:         &set_adhoc_privileges($cdom,$cnum,$checkrole);
                   4055:     }
                   4056: }
                   4057: 
                   4058: sub set_adhoc_privileges {
                   4059: # role can be cc or ca
                   4060:     my ($dcdom,$pickedcourse,$role) = @_;
                   4061:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4062:     my $spec = $role.'.'.$area;
                   4063:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4064:                                   $env{'user.name'});
                   4065:     my %ccrole = ();
                   4066:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4067:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4068:     &appenv(\%userroles,[$role,'cm']);
                   4069:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4070:     &appenv( {'request.role'        => $spec,
                   4071:               'request.role.domain' => $dcdom,
                   4072:               'request.course.sec'  => ''
                   4073:              }
                   4074:            );
                   4075:     my $tadv=0;
                   4076:     if (&allowed('adv') eq 'F') { $tadv=1; }
                   4077:     &appenv({'request.role.adv'    => $tadv});
                   4078: }
                   4079: 
1.12      www      4080: # --------------------------------------------------------------- get interface
                   4081: 
                   4082: sub get {
1.131     albertel 4083:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4084:    my $items='';
1.800     albertel 4085:    foreach my $item (@$storearr) {
                   4086:        $items.=&escape($item).'&';
1.191     harris41 4087:    }
1.12      www      4088:    $items=~s/\&$//;
1.620     albertel 4089:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4090:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4091:    my $uhome=&homeserver($uname,$udomain);
                   4092: 
1.133     albertel 4093:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4094:    my @pairs=split(/\&/,$rep);
1.273     albertel 4095:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4096:      return @pairs;
                   4097:    }
1.15      www      4098:    my %returnhash=();
1.42      www      4099:    my $i=0;
1.800     albertel 4100:    foreach my $item (@$storearr) {
                   4101:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4102:       $i++;
1.191     harris41 4103:    }
1.15      www      4104:    return %returnhash;
1.27      www      4105: }
                   4106: 
                   4107: # --------------------------------------------------------------- del interface
                   4108: 
                   4109: sub del {
1.133     albertel 4110:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4111:    my $items='';
1.800     albertel 4112:    foreach my $item (@$storearr) {
                   4113:        $items.=&escape($item).'&';
1.191     harris41 4114:    }
1.984     neumanie 4115: 
1.27      www      4116:    $items=~s/\&$//;
1.620     albertel 4117:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4118:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4119:    my $uhome=&homeserver($uname,$udomain);
                   4120:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4121: }
                   4122: 
                   4123: # -------------------------------------------------------------- dump interface
                   4124: 
                   4125: sub dump {
1.755     albertel 4126:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   4127:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4128:     if (!$uname) { $uname=$env{'user.name'}; }
                   4129:     my $uhome=&homeserver($uname,$udomain);
                   4130:     if ($regexp) {
                   4131: 	$regexp=&escape($regexp);
                   4132:     } else {
                   4133: 	$regexp='.';
                   4134:     }
                   4135:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4136:     my @pairs=split(/\&/,$rep);
                   4137:     my %returnhash=();
                   4138:     foreach my $item (@pairs) {
                   4139: 	my ($key,$value)=split(/=/,$item,2);
                   4140: 	$key = &unescape($key);
                   4141: 	next if ($key =~ /^error: 2 /);
                   4142: 	$returnhash{$key}=&thaw_unescape($value);
                   4143:     }
                   4144:     return %returnhash;
1.407     www      4145: }
                   4146: 
1.717     albertel 4147: # --------------------------------------------------------- dumpstore interface
                   4148: 
                   4149: sub dumpstore {
                   4150:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4151:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4152:    if (!$uname) { $uname=$env{'user.name'}; }
                   4153:    my $uhome=&homeserver($uname,$udomain);
                   4154:    if ($regexp) {
                   4155:        $regexp=&escape($regexp);
                   4156:    } else {
                   4157:        $regexp='.';
                   4158:    }
                   4159:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4160:    my @pairs=split(/\&/,$rep);
                   4161:    my %returnhash=();
                   4162:    foreach my $item (@pairs) {
                   4163:        my ($key,$value)=split(/=/,$item,2);
                   4164:        next if ($key =~ /^error: 2 /);
                   4165:        $returnhash{$key}=&thaw_unescape($value);
                   4166:    }
                   4167:    return %returnhash;
1.717     albertel 4168: }
                   4169: 
1.407     www      4170: # -------------------------------------------------------------- keys interface
                   4171: 
                   4172: sub getkeys {
                   4173:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4174:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4175:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4176:    my $uhome=&homeserver($uname,$udomain);
                   4177:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4178:    my @keyarray=();
1.800     albertel 4179:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4180:       next if ($key =~ /^error: 2 /);
1.800     albertel 4181:       push(@keyarray,&unescape($key));
1.407     www      4182:    }
                   4183:    return @keyarray;
1.318     matthew  4184: }
                   4185: 
1.319     matthew  4186: # --------------------------------------------------------------- currentdump
                   4187: sub currentdump {
1.328     matthew  4188:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4189:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4190:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4191:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4192:    my $uhome = &homeserver($sname,$sdom);
                   4193:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4194:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4195:    #
1.318     matthew  4196:    my %returnhash=();
1.319     matthew  4197:    #
                   4198:    if ($rep eq "unknown_cmd") { 
                   4199:        # an old lond will not know currentdump
                   4200:        # Do a dump and make it look like a currentdump
1.822     albertel 4201:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4202:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4203:        my %hash = @tmp;
                   4204:        @tmp=();
1.424     matthew  4205:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4206:    } else {
                   4207:        my @pairs=split(/\&/,$rep);
1.800     albertel 4208:        foreach my $pair (@pairs) {
                   4209:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4210:            my ($symb,$param) = split(/:/,$key);
                   4211:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4212:                                                         &thaw_unescape($value);
1.319     matthew  4213:        }
1.191     harris41 4214:    }
1.12      www      4215:    return %returnhash;
1.424     matthew  4216: }
                   4217: 
                   4218: sub convert_dump_to_currentdump{
                   4219:     my %hash = %{shift()};
                   4220:     my %returnhash;
                   4221:     # Code ripped from lond, essentially.  The only difference
                   4222:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4223:     # we might run in to problems with parameter names =~ /^v\./
                   4224:     while (my ($key,$value) = each(%hash)) {
                   4225:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4226: 	$symb  = &unescape($symb);
                   4227: 	$param = &unescape($param);
1.424     matthew  4228:         next if ($v eq 'version' || $symb eq 'keys');
                   4229:         next if (exists($returnhash{$symb}) &&
                   4230:                  exists($returnhash{$symb}->{$param}) &&
                   4231:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4232:         $returnhash{$symb}->{$param}=$value;
                   4233:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4234:     }
                   4235:     #
                   4236:     # Remove all of the keys in the hashes which keep track of
                   4237:     # the version of the parameter.
                   4238:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4239:         # use a foreach because we are going to delete from the hash.
                   4240:         foreach my $key (keys(%$param_hash)) {
                   4241:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4242:         }
                   4243:     }
                   4244:     return \%returnhash;
1.12      www      4245: }
                   4246: 
1.627     albertel 4247: # ------------------------------------------------------ critical inc interface
                   4248: 
                   4249: sub cinc {
                   4250:     return &inc(@_,'critical');
                   4251: }
                   4252: 
1.449     matthew  4253: # --------------------------------------------------------------- inc interface
                   4254: 
                   4255: sub inc {
1.627     albertel 4256:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4257:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4258:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4259:     my $uhome=&homeserver($uname,$udomain);
                   4260:     my $items='';
                   4261:     if (! ref($store)) {
                   4262:         # got a single value, so use that instead
                   4263:         $items = &escape($store).'=&';
                   4264:     } elsif (ref($store) eq 'SCALAR') {
                   4265:         $items = &escape($$store).'=&';        
                   4266:     } elsif (ref($store) eq 'ARRAY') {
                   4267:         $items = join('=&',map {&escape($_);} @{$store});
                   4268:     } elsif (ref($store) eq 'HASH') {
                   4269:         while (my($key,$value) = each(%{$store})) {
                   4270:             $items.= &escape($key).'='.&escape($value).'&';
                   4271:         }
                   4272:     }
                   4273:     $items=~s/\&$//;
1.627     albertel 4274:     if ($critical) {
                   4275: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4276:     } else {
                   4277: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4278:     }
1.449     matthew  4279: }
                   4280: 
1.12      www      4281: # --------------------------------------------------------------- put interface
                   4282: 
                   4283: sub put {
1.134     albertel 4284:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4285:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4286:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4287:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4288:    my $items='';
1.800     albertel 4289:    foreach my $item (keys(%$storehash)) {
                   4290:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4291:    }
1.12      www      4292:    $items=~s/\&$//;
1.134     albertel 4293:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4294: }
                   4295: 
1.631     albertel 4296: # ------------------------------------------------------------ newput interface
                   4297: 
                   4298: sub newput {
                   4299:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4300:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4301:    if (!$uname) { $uname=$env{'user.name'}; }
                   4302:    my $uhome=&homeserver($uname,$udomain);
                   4303:    my $items='';
                   4304:    foreach my $key (keys(%$storehash)) {
                   4305:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4306:    }
                   4307:    $items=~s/\&$//;
                   4308:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4309: }
                   4310: 
                   4311: # ---------------------------------------------------------  putstore interface
                   4312: 
1.524     raeburn  4313: sub putstore {
1.715     albertel 4314:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4315:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4316:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4317:    my $uhome=&homeserver($uname,$udomain);
                   4318:    my $items='';
1.715     albertel 4319:    foreach my $key (keys(%$storehash)) {
                   4320:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4321:    }
1.715     albertel 4322:    $items=~s/\&$//;
1.716     albertel 4323:    my $esc_symb=&escape($symb);
                   4324:    my $esc_v=&escape($version);
1.715     albertel 4325:    my $reply =
1.716     albertel 4326:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4327: 	      $uhome);
                   4328:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4329:        # gfall back to way things use to be done
1.715     albertel 4330:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4331: 			    $uname);
1.524     raeburn  4332:    }
1.715     albertel 4333:    return $reply;
                   4334: }
                   4335: 
                   4336: sub old_putstore {
1.716     albertel 4337:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4338:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4339:     if (!$uname) { $uname=$env{'user.name'}; }
                   4340:     my $uhome=&homeserver($uname,$udomain);
                   4341:     my %newstorehash;
1.800     albertel 4342:     foreach my $item (keys(%$storehash)) {
                   4343: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4344: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4345:     }
                   4346:     my $items='';
                   4347:     my %allitems = ();
1.800     albertel 4348:     foreach my $item (keys(%newstorehash)) {
                   4349: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4350: 	    my $key = $1.':keys:'.$2;
                   4351: 	    $allitems{$key} .= $3.':';
                   4352: 	}
1.800     albertel 4353: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4354:     }
1.800     albertel 4355:     foreach my $item (keys(%allitems)) {
                   4356: 	$allitems{$item} =~ s/\:$//;
                   4357: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4358:     }
                   4359:     $items=~s/\&$//;
                   4360:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4361: }
                   4362: 
1.47      www      4363: # ------------------------------------------------------ critical put interface
                   4364: 
                   4365: sub cput {
1.134     albertel 4366:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4367:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4368:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4369:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4370:    my $items='';
1.800     albertel 4371:    foreach my $item (keys(%$storehash)) {
                   4372:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4373:    }
1.47      www      4374:    $items=~s/\&$//;
1.134     albertel 4375:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4376: }
                   4377: 
                   4378: # -------------------------------------------------------------- eget interface
                   4379: 
                   4380: sub eget {
1.133     albertel 4381:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4382:    my $items='';
1.800     albertel 4383:    foreach my $item (@$storearr) {
                   4384:        $items.=&escape($item).'&';
1.191     harris41 4385:    }
1.12      www      4386:    $items=~s/\&$//;
1.620     albertel 4387:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4388:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4389:    my $uhome=&homeserver($uname,$udomain);
                   4390:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4391:    my @pairs=split(/\&/,$rep);
                   4392:    my %returnhash=();
1.42      www      4393:    my $i=0;
1.800     albertel 4394:    foreach my $item (@$storearr) {
                   4395:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4396:       $i++;
1.191     harris41 4397:    }
1.12      www      4398:    return %returnhash;
                   4399: }
                   4400: 
1.667     albertel 4401: # ------------------------------------------------------------ tmpput interface
                   4402: sub tmpput {
1.802     raeburn  4403:     my ($storehash,$server,$context)=@_;
1.667     albertel 4404:     my $items='';
1.800     albertel 4405:     foreach my $item (keys(%$storehash)) {
                   4406: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4407:     }
                   4408:     $items=~s/\&$//;
1.802     raeburn  4409:     if (defined($context)) {
                   4410:         $items .= ':'.&escape($context);
                   4411:     }
1.667     albertel 4412:     return &reply("tmpput:$items",$server);
                   4413: }
                   4414: 
                   4415: # ------------------------------------------------------------ tmpget interface
                   4416: sub tmpget {
1.688     albertel 4417:     my ($token,$server)=@_;
                   4418:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4419:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4420:     my %returnhash;
                   4421:     foreach my $item (split(/\&/,$rep)) {
                   4422: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4423:         next if ($key =~ /^error: 2 /);
1.667     albertel 4424: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4425:     }
                   4426:     return %returnhash;
                   4427: }
                   4428: 
1.688     albertel 4429: # ------------------------------------------------------------ tmpget interface
                   4430: sub tmpdel {
                   4431:     my ($token,$server)=@_;
                   4432:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4433:     return &reply("tmpdel:$token",$server);
                   4434: }
                   4435: 
1.765     albertel 4436: # -------------------------------------------------- portfolio access checking
                   4437: 
                   4438: sub portfolio_access {
1.766     albertel 4439:     my ($requrl) = @_;
1.765     albertel 4440:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4441:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4442:     if ($result) {
                   4443:         my %setters;
                   4444:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4445:             my ($startblock,$endblock) =
                   4446:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4447:             if ($startblock && $endblock) {
                   4448:                 return 'B';
                   4449:             }
                   4450:         } else {
                   4451:             my ($startblock,$endblock) =
                   4452:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4453:             if ($startblock && $endblock) {
                   4454:                 return 'B';
                   4455:             }
                   4456:         }
                   4457:     }
1.765     albertel 4458:     if ($result eq 'ok') {
1.766     albertel 4459:        return 'F';
1.765     albertel 4460:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4461:        return 'A';
1.765     albertel 4462:     }
1.766     albertel 4463:     return '';
1.765     albertel 4464: }
                   4465: 
                   4466: sub get_portfolio_access {
1.767     albertel 4467:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4468: 
                   4469:     if (!ref($access_hash)) {
                   4470: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4471: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4472: 						   $file_name);
                   4473: 	$access_hash = $access_controls{$file_name};
                   4474:     }
                   4475: 
1.765     albertel 4476:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4477:     my $now = time;
                   4478:     if (ref($access_hash) eq 'HASH') {
                   4479:         foreach my $key (keys(%{$access_hash})) {
                   4480:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4481:             if ($start > $now) {
                   4482:                 next;
                   4483:             }
                   4484:             if ($end && $end<$now) {
                   4485:                 next;
                   4486:             }
                   4487:             if ($scope eq 'public') {
                   4488:                 $public = $key;
                   4489:                 last;
                   4490:             } elsif ($scope eq 'guest') {
                   4491:                 $guest = $key;
                   4492:             } elsif ($scope eq 'domains') {
                   4493:                 push(@domains,$key);
                   4494:             } elsif ($scope eq 'users') {
                   4495:                 push(@users,$key);
                   4496:             } elsif ($scope eq 'course') {
                   4497:                 push(@courses,$key);
                   4498:             } elsif ($scope eq 'group') {
                   4499:                 push(@groups,$key);
                   4500:             }
                   4501:         }
                   4502:         if ($public) {
                   4503:             return 'ok';
                   4504:         }
                   4505:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4506:             if ($guest) {
                   4507:                 return $guest;
                   4508:             }
                   4509:         } else {
                   4510:             if (@domains > 0) {
                   4511:                 foreach my $domkey (@domains) {
                   4512:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4513:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4514:                             return 'ok';
                   4515:                         }
                   4516:                     }
                   4517:                 }
                   4518:             }
                   4519:             if (@users > 0) {
                   4520:                 foreach my $userkey (@users) {
1.865     raeburn  4521:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4522:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4523:                             if (ref($item) eq 'HASH') {
                   4524:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4525:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4526:                                     return 'ok';
                   4527:                                 }
                   4528:                             }
                   4529:                         }
                   4530:                     } 
1.765     albertel 4531:                 }
                   4532:             }
                   4533:             my %roleshash;
                   4534:             my @courses_and_groups = @courses;
                   4535:             push(@courses_and_groups,@groups); 
                   4536:             if (@courses_and_groups > 0) {
                   4537:                 my (%allgroups,%allroles); 
                   4538:                 my ($start,$end,$role,$sec,$group);
                   4539:                 foreach my $envkey (%env) {
1.811     albertel 4540:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4541:                         my $cid = $2.'_'.$3; 
                   4542:                         if ($1 eq 'gr') {
                   4543:                             $group = $4;
                   4544:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4545:                         } else {
                   4546:                             if ($4 eq '') {
                   4547:                                 $sec = 'none';
                   4548:                             } else {
                   4549:                                 $sec = $4;
                   4550:                             }
                   4551:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4552:                         }
1.811     albertel 4553:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4554:                         my $cid = $2.'_'.$3;
                   4555:                         if ($4 eq '') {
                   4556:                             $sec = 'none';
                   4557:                         } else {
                   4558:                             $sec = $4;
                   4559:                         }
                   4560:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4561:                     }
                   4562:                 }
                   4563:                 if (keys(%allroles) == 0) {
                   4564:                     return;
                   4565:                 }
                   4566:                 foreach my $key (@courses_and_groups) {
                   4567:                     my %content = %{$$access_hash{$key}};
                   4568:                     my $cnum = $content{'number'};
                   4569:                     my $cdom = $content{'domain'};
                   4570:                     my $cid = $cdom.'_'.$cnum;
                   4571:                     if (!exists($allroles{$cid})) {
                   4572:                         next;
                   4573:                     }    
                   4574:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4575:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4576:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4577:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4578:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4579:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4580:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4581:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4582:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4583:                                         if (grep/^all$/,@sections) {
                   4584:                                             return 'ok';
                   4585:                                         } else {
                   4586:                                             if (grep/^$sec$/,@sections) {
                   4587:                                                 return 'ok';
                   4588:                                             }
                   4589:                                         }
                   4590:                                     }
                   4591:                                 }
                   4592:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4593:                                     if (grep/^none$/,@groups) {
                   4594:                                         return 'ok';
                   4595:                                     }
                   4596:                                 } else {
                   4597:                                     if (grep/^all$/,@groups) {
                   4598:                                         return 'ok';
                   4599:                                     } 
                   4600:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4601:                                         if (grep/^$group$/,@groups) {
                   4602:                                             return 'ok';
                   4603:                                         }
                   4604:                                     }
                   4605:                                 } 
                   4606:                             }
                   4607:                         }
                   4608:                     }
                   4609:                 }
                   4610:             }
                   4611:             if ($guest) {
                   4612:                 return $guest;
                   4613:             }
                   4614:         }
                   4615:     }
                   4616:     return;
                   4617: }
                   4618: 
                   4619: sub course_group_datechecker {
                   4620:     my ($dates,$now,$status) = @_;
                   4621:     my ($start,$end) = split(/\./,$dates);
                   4622:     if (!$start && !$end) {
                   4623:         return 'ok';
                   4624:     }
                   4625:     if (grep/^active$/,@{$status}) {
                   4626:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4627:             return 'ok';
                   4628:         }
                   4629:     }
                   4630:     if (grep/^previous$/,@{$status}) {
                   4631:         if ($end > $now ) {
                   4632:             return 'ok';
                   4633:         }
                   4634:     }
                   4635:     if (grep/^future$/,@{$status}) {
                   4636:         if ($start > $now) {
                   4637:             return 'ok';
                   4638:         }
                   4639:     }
                   4640:     return; 
                   4641: }
                   4642: 
                   4643: sub parse_portfolio_url {
                   4644:     my ($url) = @_;
                   4645: 
                   4646:     my ($type,$udom,$unum,$group,$file_name);
                   4647:     
1.823     albertel 4648:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4649: 	$type = 1;
                   4650:         $udom = $1;
                   4651:         $unum = $2;
                   4652:         $file_name = $3;
1.823     albertel 4653:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4654: 	$type = 2;
                   4655:         $udom = $1;
                   4656:         $unum = $2;
                   4657:         $group = $3;
                   4658:         $file_name = $3.'/'.$4;
                   4659:     }
                   4660:     if (wantarray) {
                   4661: 	return ($type,$udom,$unum,$file_name,$group);
                   4662:     }
                   4663:     return $type;
                   4664: }
                   4665: 
                   4666: sub is_portfolio_url {
                   4667:     my ($url) = @_;
                   4668:     return scalar(&parse_portfolio_url($url));
                   4669: }
                   4670: 
1.798     raeburn  4671: sub is_portfolio_file {
                   4672:     my ($file) = @_;
1.820     raeburn  4673:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4674:         return 1;
                   4675:     }
                   4676:     return;
                   4677: }
                   4678: 
1.976     raeburn  4679: sub usertools_access {
1.985     raeburn  4680:     my ($uname,$udom,$tool,$action,$context) = @_;
                   4681:     my ($access,%tools);
                   4682:     if ($context eq '') {
                   4683:         $context = 'tools';
                   4684:     }
                   4685:     if ($context eq 'requestcourses') {
                   4686:         %tools = (
                   4687:                       official   => 1,
                   4688:                       unofficial => 1,
1.1006    raeburn  4689:                       community  => 1,
1.985     raeburn  4690:                  );
                   4691:     } else {
                   4692:         %tools = (
                   4693:                       aboutme   => 1,
                   4694:                       blog      => 1,
                   4695:                       portfolio => 1,
                   4696:                  );
                   4697:     }
1.976     raeburn  4698:     return if (!defined($tools{$tool}));
                   4699: 
                   4700:     if ((!defined($udom)) || (!defined($uname))) {
                   4701:         $udom = $env{'user.domain'};
                   4702:         $uname = $env{'user.name'};
                   4703:     }
                   4704: 
1.978     raeburn  4705:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4706:         if ($action ne 'reload') {
1.985     raeburn  4707:             if ($context eq 'requestcourses') {
                   4708:                 return $env{'environment.canrequest.'.$tool};
                   4709:             } else {
                   4710:                 return $env{'environment.availabletools.'.$tool};
                   4711:             }
                   4712:         }
1.976     raeburn  4713:     }
                   4714: 
                   4715:     my ($toolstatus,$inststatus);
                   4716: 
1.985     raeburn  4717:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   4718:          ($action ne 'reload')) {
                   4719:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  4720:         $inststatus = $env{'environment.inststatus'};
                   4721:     } else {
1.985     raeburn  4722:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool);
                   4723:         $toolstatus = $userenv{$context.'.'.$tool};
1.976     raeburn  4724:         $inststatus = $userenv{'inststatus'};
                   4725:     }
                   4726: 
                   4727:     if ($toolstatus ne '') {
                   4728:         if ($toolstatus) {
                   4729:             $access = 1;
                   4730:         } else {
                   4731:             $access = 0;
                   4732:         }
                   4733:         return $access;
                   4734:     }
                   4735: 
                   4736:     my $is_adv = &is_advanced_user($udom,$uname);
                   4737:     my %domdef = &get_domain_defaults($udom);
                   4738:     if (ref($domdef{$tool}) eq 'HASH') {
                   4739:         if ($is_adv) {
                   4740:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   4741:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   4742:                     $access = 1;
                   4743:                 } else {
                   4744:                     $access = 0;
                   4745:                 }
                   4746:                 return $access;
                   4747:             }
                   4748:         }
                   4749:         if ($inststatus ne '') {
                   4750:             my ($hasaccess,$hasnoaccess);
                   4751:             foreach my $affiliation (split(/:/,$inststatus)) {
                   4752:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   4753:                     if ($domdef{$tool}{$affiliation}) {
                   4754:                         $hasaccess = 1;
                   4755:                     } else {
                   4756:                         $hasnoaccess = 1;
                   4757:                     }
                   4758:                 }
                   4759:             }
                   4760:             if ($hasaccess || $hasnoaccess) {
                   4761:                 if ($hasaccess) {
                   4762:                     $access = 1;
                   4763:                 } elsif ($hasnoaccess) {
                   4764:                     $access = 0; 
                   4765:                 }
                   4766:                 return $access;
                   4767:             }
                   4768:         } else {
                   4769:             if ($domdef{$tool}{'default'} ne '') {
                   4770:                 if ($domdef{$tool}{'default'}) {
                   4771:                     $access = 1;
                   4772:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   4773:                     $access = 0;
                   4774:                 }
                   4775:                 return $access;
                   4776:             }
                   4777:         }
                   4778:     } else {
1.985     raeburn  4779:         if ($context eq 'tools') {
                   4780:             $access = 1;
                   4781:         } else {
                   4782:             $access = 0;
                   4783:         }
1.976     raeburn  4784:         return $access;
                   4785:     }
                   4786: }
                   4787: 
                   4788: sub is_advanced_user {
                   4789:     my ($udom,$uname) = @_;
                   4790:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   4791:     my %allroles;
                   4792:     my $is_adv;
                   4793:     foreach my $role (keys(%roleshash)) {
                   4794:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   4795:         my $area = '/'.$tdomain.'/'.$trest;
                   4796:         if ($sec ne '') {
                   4797:             $area .= '/'.$sec;
                   4798:         }
                   4799:         if (($area ne '') && ($trole ne '')) {
                   4800:             my $spec=$trole.'.'.$area;
                   4801:             if ($trole =~ /^cr\//) {
                   4802:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4803:             } elsif ($trole ne 'gr') {
                   4804:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4805:             }
                   4806:         }
                   4807:     }
                   4808:     foreach my $role (keys(%allroles)) {
                   4809:         last if ($is_adv);
                   4810:         foreach my $item (split(/:/,$allroles{$role})) {
                   4811:             if ($item ne '') {
                   4812:                 my ($privilege,$restrictions)=split(/&/,$item);
                   4813:                 if ($privilege eq 'adv') {
                   4814:                     $is_adv = 1;
                   4815:                     last;
                   4816:                 }
                   4817:             }
                   4818:         }
                   4819:     }
                   4820:     return $is_adv;
                   4821: }
1.798     raeburn  4822: 
1.341     www      4823: # ---------------------------------------------- Custom access rule evaluation
                   4824: 
                   4825: sub customaccess {
                   4826:     my ($priv,$uri)=@_;
1.807     albertel 4827:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4828:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4829:     $udom = &LONCAPA::clean_domain($udom);
                   4830:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4831:     my $access=0;
1.800     albertel 4832:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4833: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4834: 	if ($type eq 'user') {
                   4835: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4836: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4837: 		if ($tdom) {
                   4838: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4839: 		}
1.896     albertel 4840: 		if ($tuname) {
                   4841: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4842: 		}
                   4843: 		$access=($effect eq 'allow');
                   4844: 		last;
                   4845: 	    }
                   4846: 	} else {
                   4847: 	    if ($role) {
                   4848: 		if ($role ne $urole) { next; }
                   4849: 	    }
                   4850: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4851: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4852: 		if ($tdom) {
                   4853: 		    if ($tdom ne $udom) { next; }
                   4854: 		}
                   4855: 		if ($tcrs) {
                   4856: 		    if ($tcrs ne $ucrs) { next; }
                   4857: 		}
                   4858: 		if ($tsec) {
                   4859: 		    if ($tsec ne $usec) { next; }
                   4860: 		}
                   4861: 		$access=($effect eq 'allow');
                   4862: 		last;
                   4863: 	    }
                   4864: 	    if ($realm eq '' && $role eq '') {
                   4865: 		$access=($effect eq 'allow');
                   4866: 	    }
1.402     bowersj2 4867: 	}
1.341     www      4868:     }
                   4869:     return $access;
                   4870: }
                   4871: 
1.103     harris41 4872: # ------------------------------------------------- Check for a user privilege
1.12      www      4873: 
                   4874: sub allowed {
1.810     raeburn  4875:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4876:     my $ver_orguri=$uri;
1.439     www      4877:     $uri=&deversion($uri);
1.152     www      4878:     my $orguri=$uri;
1.52      www      4879:     $uri=&declutter($uri);
1.809     raeburn  4880: 
1.810     raeburn  4881:     if ($priv eq 'evb') {
                   4882: # Evade communication block restrictions for specified role in a course
                   4883:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4884:             return $1;
                   4885:         } else {
                   4886:             return;
                   4887:         }
                   4888:     }
                   4889: 
1.620     albertel 4890:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4891: # Free bre access to adm and meta resources
1.775     albertel 4892:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4893: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4894: 	&& ($priv eq 'bre')) {
1.14      www      4895: 	return 'F';
1.159     www      4896:     }
                   4897: 
1.545     banghart 4898: # Free bre access to user's own portfolio contents
1.714     raeburn  4899:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4900:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4901: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4902:         my %setters;
                   4903:         my ($startblock,$endblock) = 
                   4904:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4905:         if ($startblock && $endblock) {
                   4906:             return 'B';
                   4907:         } else {
                   4908:             return 'F';
                   4909:         }
1.545     banghart 4910:     }
                   4911: 
1.762     raeburn  4912: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4913:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4914:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4915:         if (exists($env{'request.course.id'})) {
                   4916:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4917:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4918:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4919:                 my $courseprivid=$env{'request.course.id'};
                   4920:                 $courseprivid=~s/\_/\//;
                   4921:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4922:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4923:                     return $1; 
1.762     raeburn  4924:                 } else {
                   4925:                     if ($env{'request.course.sec'}) {
                   4926:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4927:                     }
                   4928:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4929:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4930:                         return $2;
                   4931:                     }
1.714     raeburn  4932:                 }
                   4933:             }
                   4934:         }
                   4935:     }
                   4936: 
1.159     www      4937: # Free bre to public access
                   4938: 
                   4939:     if ($priv eq 'bre') {
1.238     www      4940:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4941: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4942:            return 'F'; 
                   4943:         }
1.238     www      4944:         if ($copyright eq 'priv') {
                   4945:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4946: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4947: 		return '';
                   4948:             }
                   4949:         }
                   4950:         if ($copyright eq 'domain') {
                   4951:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4952: 	    unless (($env{'user.domain'} eq $1) ||
                   4953:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4954: 		return '';
                   4955:             }
1.262     matthew  4956:         }
1.620     albertel 4957:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4958:             # Library role, so allow browsing of resources in this domain.
                   4959:             return 'F';
1.238     www      4960:         }
1.341     www      4961:         if ($copyright eq 'custom') {
                   4962: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4963:         }
1.14      www      4964:     }
1.264     matthew  4965:     # Domain coordinator is trying to create a course
1.620     albertel 4966:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4967:         # uri is the requested domain in this case.
                   4968:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4969:         # a role of dc for the domain in question.
1.620     albertel 4970:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4971:     }
1.29      www      4972: 
1.52      www      4973:     my $thisallowed='';
                   4974:     my $statecond=0;
                   4975:     my $courseprivid='';
                   4976: 
                   4977: # Course
                   4978: 
1.620     albertel 4979:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4980:        $thisallowed.=$1;
                   4981:     }
1.29      www      4982: 
1.52      www      4983: # Domain
                   4984: 
1.620     albertel 4985:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4986:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4987:        $thisallowed.=$1;
                   4988:     }
1.52      www      4989: 
                   4990: # Course: uri itself is a course
1.66      www      4991:     my $courseuri=$uri;
                   4992:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4993:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4994: 
1.620     albertel 4995:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4996:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4997:        $thisallowed.=$1;
                   4998:     }
1.29      www      4999: 
1.665     albertel 5000: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5001: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5002:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5003: 	$thisallowed='';
1.671     raeburn  5004:         my ($match)=&is_on_map($uri);
                   5005:         if ($match) {
                   5006:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5007:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5008:                 $thisallowed.=$1;
                   5009:             }
                   5010:         } else {
1.705     albertel 5011:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5012:             if ($refuri) {
                   5013:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5014:                     $thisallowed='F';
1.671     raeburn  5015:                 } else {
                   5016:                     $refuri=&declutter($refuri);
                   5017:                     my ($match) = &is_on_map($refuri);
                   5018:                     if ($match) {
                   5019:                         $thisallowed='F';
                   5020:                     }
1.669     raeburn  5021:                 }
1.671     raeburn  5022:             }
                   5023:         }
1.314     www      5024:     }
1.492     albertel 5025: 
1.766     albertel 5026:     if ($priv eq 'bre'
                   5027: 	&& $thisallowed ne 'F' 
                   5028: 	&& $thisallowed ne '2'
                   5029: 	&& &is_portfolio_url($uri)) {
                   5030: 	$thisallowed = &portfolio_access($uri);
                   5031:     }
                   5032:     
1.52      www      5033: # Full access at system, domain or course-wide level? Exit.
1.29      www      5034:     if ($thisallowed=~/F/) {
                   5035: 	return 'F';
                   5036:     }
                   5037: 
1.52      www      5038: # If this is generating or modifying users, exit with special codes
1.29      www      5039: 
1.643     www      5040:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5041: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5042: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5043: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5044: 	    unless ($auname) { return $thisallowed; }
                   5045: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5046: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5047: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5048: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5049: 	}
1.52      www      5050: 	return $thisallowed;
                   5051:     }
                   5052: #
1.103     harris41 5053: # Gathered so far: system, domain and course wide privileges
1.52      www      5054: #
                   5055: # Course: See if uri or referer is an individual resource that is part of 
                   5056: # the course
                   5057: 
1.620     albertel 5058:     if ($env{'request.course.id'}) {
1.232     www      5059: 
1.620     albertel 5060:        $courseprivid=$env{'request.course.id'};
                   5061:        if ($env{'request.course.sec'}) {
                   5062:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5063:        }
                   5064:        $courseprivid=~s/\_/\//;
                   5065:        my $checkreferer=1;
1.232     www      5066:        my ($match,$cond)=&is_on_map($uri);
                   5067:        if ($match) {
                   5068:            $statecond=$cond;
1.620     albertel 5069:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5070:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5071:                $thisallowed.=$1;
                   5072:                $checkreferer=0;
                   5073:            }
1.29      www      5074:        }
1.83      www      5075:        
1.148     www      5076:        if ($checkreferer) {
1.620     albertel 5077: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5078:             unless ($refuri) {
1.800     albertel 5079:                 foreach my $key (keys(%env)) {
                   5080: 		    if ($key=~/^httpref\..*\*/) {
                   5081: 			my $pattern=$key;
1.156     www      5082:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5083:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5084:                         $pattern=~s/\//\\\//g;
1.152     www      5085:                         if ($orguri=~/$pattern/) {
1.800     albertel 5086: 			    $refuri=$env{$key};
1.148     www      5087:                         }
                   5088:                     }
1.191     harris41 5089:                 }
1.148     www      5090:             }
1.232     www      5091: 
1.148     www      5092:          if ($refuri) { 
1.152     www      5093: 	  $refuri=&declutter($refuri);
1.232     www      5094:           my ($match,$cond)=&is_on_map($refuri);
                   5095:             if ($match) {
                   5096:               my $refstatecond=$cond;
1.620     albertel 5097:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5098:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5099:                   $thisallowed.=$1;
1.53      www      5100:                   $uri=$refuri;
                   5101:                   $statecond=$refstatecond;
1.52      www      5102:               }
                   5103:           }
1.148     www      5104:         }
1.29      www      5105:        }
1.52      www      5106:    }
1.29      www      5107: 
1.52      www      5108: #
1.103     harris41 5109: # Gathered now: all privileges that could apply, and condition number
1.52      www      5110: # 
                   5111: #
                   5112: # Full or no access?
                   5113: #
1.29      www      5114: 
1.52      www      5115:     if ($thisallowed=~/F/) {
                   5116: 	return 'F';
                   5117:     }
1.29      www      5118: 
1.52      www      5119:     unless ($thisallowed) {
                   5120:         return '';
                   5121:     }
1.29      www      5122: 
1.52      www      5123: # Restrictions exist, deal with them
                   5124: #
                   5125: #   C:according to course preferences
                   5126: #   R:according to resource settings
                   5127: #   L:unless locked
                   5128: #   X:according to user session state
                   5129: #
                   5130: 
                   5131: # Possibly locked functionality, check all courses
1.54      www      5132: # Locks might take effect only after 10 minutes cache expiration for other
                   5133: # courses, and 2 minutes for current course
1.52      www      5134: 
                   5135:     my $envkey;
                   5136:     if ($thisallowed=~/L/) {
1.1000    raeburn  5137:         foreach $envkey (keys(%env)) {
1.54      www      5138:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5139:                my $courseid=$2;
                   5140:                my $roleid=$1.'.'.$2;
1.92      www      5141:                $courseid=~s/^\///;
1.54      www      5142:                my $expiretime=600;
1.620     albertel 5143:                if ($env{'request.role'} eq $roleid) {
1.54      www      5144: 		  $expiretime=120;
                   5145:                }
                   5146: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5147:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5148:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5149: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5150:                }
1.620     albertel 5151:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5152:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5153: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5154:                        &log($env{'user.domain'},$env{'user.name'},
                   5155:                             $env{'user.home'},
1.57      www      5156:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5157:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5158:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5159: 		       return '';
                   5160:                    }
                   5161:                }
1.620     albertel 5162:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5163:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5164: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5165:                        &log($env{'user.domain'},$env{'user.name'},
                   5166:                             $env{'user.home'},
1.57      www      5167:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5168:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5169:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5170: 		       return '';
                   5171:                    }
                   5172:                }
                   5173: 	   }
1.29      www      5174:        }
1.52      www      5175:     }
                   5176:    
                   5177: #
                   5178: # Rest of the restrictions depend on selected course
                   5179: #
                   5180: 
1.620     albertel 5181:     unless ($env{'request.course.id'}) {
1.766     albertel 5182: 	if ($thisallowed eq 'A') {
                   5183: 	    return 'A';
1.814     raeburn  5184:         } elsif ($thisallowed eq 'B') {
                   5185:             return 'B';
1.766     albertel 5186: 	} else {
                   5187: 	    return '1';
                   5188: 	}
1.52      www      5189:     }
1.29      www      5190: 
1.52      www      5191: #
                   5192: # Now user is definitely in a course
                   5193: #
1.53      www      5194: 
                   5195: 
                   5196: # Course preferences
                   5197: 
                   5198:    if ($thisallowed=~/C/) {
1.620     albertel 5199:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5200:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5201:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5202: 	   =~/\Q$rolecode\E/) {
1.689     albertel 5203: 	   if ($priv ne 'pch') { 
                   5204: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5205: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5206: 			$env{'request.course.id'});
                   5207: 	   }
1.237     www      5208:            return '';
                   5209:        }
                   5210: 
1.620     albertel 5211:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5212: 	   =~/\Q$unamedom\E/) {
1.689     albertel 5213: 	   if ($priv ne 'pch') { 
                   5214: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5215: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5216: 			$env{'request.course.id'});
                   5217: 	   }
1.54      www      5218:            return '';
                   5219:        }
1.53      www      5220:    }
                   5221: 
                   5222: # Resource preferences
                   5223: 
                   5224:    if ($thisallowed=~/R/) {
1.620     albertel 5225:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5226:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 5227: 	   if ($priv ne 'pch') { 
                   5228: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5229: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5230: 	   }
                   5231: 	   return '';
1.54      www      5232:        }
1.53      www      5233:    }
1.30      www      5234: 
1.246     www      5235: # Restricted by state or randomout?
1.30      www      5236: 
1.52      www      5237:    if ($thisallowed=~/X/) {
1.620     albertel 5238:       if ($env{'acc.randomout'}) {
1.579     albertel 5239: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5240:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5241:             return ''; 
                   5242:          }
1.247     www      5243:       }
                   5244:       if (&condval($statecond)) {
1.52      www      5245: 	 return '2';
                   5246:       } else {
                   5247:          return '';
                   5248:       }
                   5249:    }
1.30      www      5250: 
1.766     albertel 5251:     if ($thisallowed eq 'A') {
                   5252: 	return 'A';
1.814     raeburn  5253:     } elsif ($thisallowed eq 'B') {
                   5254:         return 'B';
1.766     albertel 5255:     }
1.52      www      5256:    return 'F';
1.232     www      5257: }
                   5258: 
1.710     albertel 5259: sub split_uri_for_cond {
                   5260:     my $uri=&deversion(&declutter(shift));
                   5261:     my @uriparts=split(/\//,$uri);
                   5262:     my $filename=pop(@uriparts);
                   5263:     my $pathname=join('/',@uriparts);
                   5264:     return ($pathname,$filename);
                   5265: }
1.232     www      5266: # --------------------------------------------------- Is a resource on the map?
                   5267: 
                   5268: sub is_on_map {
1.710     albertel 5269:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5270:     #Trying to find the conditional for the file
1.620     albertel 5271:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5272: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5273:     if ($match) {
1.289     bowersj2 5274: 	return (1,$1);
                   5275:     } else {
1.434     www      5276: 	return (0,0);
1.289     bowersj2 5277:     }
1.12      www      5278: }
                   5279: 
1.427     www      5280: # --------------------------------------------------------- Get symb from alias
                   5281: 
                   5282: sub get_symb_from_alias {
                   5283:     my $symb=shift;
                   5284:     my ($map,$resid,$url)=&decode_symb($symb);
                   5285: # Already is a symb
                   5286:     if ($url) { return $symb; }
                   5287: # Must be an alias
                   5288:     my $aliassymb='';
                   5289:     my %bighash;
1.620     albertel 5290:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5291:                             &GDBM_READER(),0640)) {
                   5292:         my $rid=$bighash{'mapalias_'.$symb};
                   5293: 	if ($rid) {
                   5294: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5295: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5296: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5297: 	}
                   5298:         untie %bighash;
                   5299:     }
                   5300:     return $aliassymb;
                   5301: }
                   5302: 
1.12      www      5303: # ----------------------------------------------------------------- Define Role
                   5304: 
                   5305: sub definerole {
                   5306:   if (allowed('mcr','/')) {
                   5307:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5308:     foreach my $role (split(':',$sysrole)) {
                   5309: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5310:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5311:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5312: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5313:                return "refused:s:$crole&$cqual"; 
                   5314:             }
                   5315:         }
1.191     harris41 5316:     }
1.800     albertel 5317:     foreach my $role (split(':',$domrole)) {
                   5318: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5319:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5320:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5321: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5322:                return "refused:d:$crole&$cqual"; 
                   5323:             }
                   5324:         }
1.191     harris41 5325:     }
1.800     albertel 5326:     foreach my $role (split(':',$courole)) {
                   5327: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5328:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5329:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5330: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5331:                return "refused:c:$crole&$cqual"; 
                   5332:             }
                   5333:         }
1.191     harris41 5334:     }
1.620     albertel 5335:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5336:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5337: 	        "rolesdef_$rolename=".
                   5338:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5339:     return reply($command,$env{'user.home'});
1.12      www      5340:   } else {
                   5341:     return 'refused';
                   5342:   }
1.105     harris41 5343: }
                   5344: 
                   5345: # ---------------- Make a metadata query against the network of library servers
                   5346: 
                   5347: sub metadata_query {
1.244     matthew  5348:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5349:     my %rhash;
1.845     albertel 5350:     my %libserv = &all_library();
1.244     matthew  5351:     my @server_list = (defined($server_array) ? @$server_array
                   5352:                                               : keys(%libserv) );
                   5353:     for my $server (@server_list) {
1.118     harris41 5354: 	unless ($custom or $customshow) {
                   5355: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5356: 	    $rhash{$server}=$reply;
                   5357: 	}
                   5358: 	else {
                   5359: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5360: 			     &escape($custom).':'.&escape($customshow),
                   5361: 			     $server);
                   5362: 	    $rhash{$server}=$reply;
                   5363: 	}
1.112     harris41 5364:     }
1.118     harris41 5365:     return \%rhash;
1.240     www      5366: }
                   5367: 
                   5368: # ----------------------------------------- Send log queries and wait for reply
                   5369: 
                   5370: sub log_query {
                   5371:     my ($uname,$udom,$query,%filters)=@_;
                   5372:     my $uhome=&homeserver($uname,$udom);
                   5373:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5374:     my $uhost=&hostname($uhome);
1.800     albertel 5375:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5376:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5377:                        $uhome);
1.479     albertel 5378:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5379:     return get_query_reply($queryid);
                   5380: }
                   5381: 
1.818     raeburn  5382: # -------------------------- Update MySQL table for portfolio file
                   5383: 
                   5384: sub update_portfolio_table {
1.821     raeburn  5385:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5386:     if ($group ne '') {
                   5387:         $file_name =~s /^\Q$group\E//;
                   5388:     }
1.818     raeburn  5389:     my $homeserver = &homeserver($uname,$udom);
                   5390:     my $queryid=
1.821     raeburn  5391:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5392:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5393:     my $reply = &get_query_reply($queryid);
                   5394:     return $reply;
                   5395: }
                   5396: 
1.899     raeburn  5397: # -------------------------- Update MySQL allusers table
                   5398: 
                   5399: sub update_allusers_table {
                   5400:     my ($uname,$udom,$names) = @_;
                   5401:     my $homeserver = &homeserver($uname,$udom);
                   5402:     my $queryid=
                   5403:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5404:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5405:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5406:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5407:                'generation='.&escape($names->{'generation'}).'%%'.
                   5408:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5409:                'id='.&escape($names->{'id'}),$homeserver);
                   5410:     my $reply = &get_query_reply($queryid);
                   5411:     return $reply;
                   5412: }
                   5413: 
1.508     raeburn  5414: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5415: 
                   5416: sub fetch_enrollment_query {
1.511     raeburn  5417:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5418:     my $homeserver;
1.547     raeburn  5419:     my $maxtries = 1;
1.508     raeburn  5420:     if ($context eq 'automated') {
                   5421:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5422:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5423:     } else {
                   5424:         $homeserver = &homeserver($cnum,$dom);
                   5425:     }
1.838     albertel 5426:     my $host=&hostname($homeserver);
1.506     raeburn  5427:     my $cmd = '';
1.1000    raeburn  5428:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 5429:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5430:     }
                   5431:     $cmd =~ s/%%$//;
                   5432:     $cmd = &escape($cmd);
                   5433:     my $query = 'fetchenrollment';
1.620     albertel 5434:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5435:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5436:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5437:         return 'error: '.$queryid;
                   5438:     }
1.506     raeburn  5439:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5440:     my $tries = 1;
                   5441:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5442:         $reply = &get_query_reply($queryid);
                   5443:         $tries ++;
                   5444:     }
1.526     raeburn  5445:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5446:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5447:     } else {
1.901     albertel 5448:         my @responses = split(/:/,$reply);
1.515     raeburn  5449:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5450:             foreach my $line (@responses) {
                   5451:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5452:                 $$replyref{$key} = $value;
                   5453:             }
                   5454:         } else {
1.506     raeburn  5455:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5456:             foreach my $line (@responses) {
                   5457:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5458:                 $$replyref{$key} = $value;
                   5459:                 if ($value > 0) {
1.800     albertel 5460:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5461:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5462:                         my $destname = $pathname.'/'.$filename;
                   5463:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5464:                         if ($xml_classlist =~ /^error/) {
                   5465:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5466:                         } else {
1.506     raeburn  5467:                             if ( open(FILE,">$destname") ) {
                   5468:                                 print FILE &unescape($xml_classlist);
                   5469:                                 close(FILE);
1.526     raeburn  5470:                             } else {
                   5471:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5472:                             }
                   5473:                         }
                   5474:                     }
                   5475:                 }
                   5476:             }
                   5477:         }
                   5478:         return 'ok';
                   5479:     }
                   5480:     return 'error';
                   5481: }
                   5482: 
1.242     www      5483: sub get_query_reply {
                   5484:     my $queryid=shift;
1.240     www      5485:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5486:     my $reply='';
                   5487:     for (1..100) {
                   5488: 	sleep 2;
                   5489:         if (-e $replyfile.'.end') {
1.448     albertel 5490: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5491: 		$reply = join('',<$fh>);
                   5492: 		close($fh);
1.240     www      5493: 	   } else { return 'error: reply_file_error'; }
1.242     www      5494:            return &unescape($reply);
                   5495: 	}
1.240     www      5496:     }
1.242     www      5497:     return 'timeout:'.$queryid;
1.240     www      5498: }
                   5499: 
                   5500: sub courselog_query {
1.241     www      5501: #
                   5502: # possible filters:
                   5503: # url: url or symb
                   5504: # username
                   5505: # domain
                   5506: # action: view, submit, grade
                   5507: # start: timestamp
                   5508: # end: timestamp
                   5509: #
1.240     www      5510:     my (%filters)=@_;
1.620     albertel 5511:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5512:     if ($filters{'url'}) {
                   5513: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5514:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5515:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5516:     }
1.620     albertel 5517:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5518:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5519:     return &log_query($cname,$cdom,'courselog',%filters);
                   5520: }
                   5521: 
                   5522: sub userlog_query {
1.858     raeburn  5523: #
                   5524: # possible filters:
                   5525: # action: log check role
                   5526: # start: timestamp
                   5527: # end: timestamp
                   5528: #
1.240     www      5529:     my ($uname,$udom,%filters)=@_;
                   5530:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5531: }
                   5532: 
1.506     raeburn  5533: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5534: 
                   5535: sub auto_run {
1.508     raeburn  5536:     my ($cnum,$cdom) = @_;
1.876     raeburn  5537:     my $response = 0;
                   5538:     my $settings;
                   5539:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5540:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5541:         $settings = $domconfig{'autoenroll'};
                   5542:         if ($settings->{'run'} eq '1') {
                   5543:             $response = 1;
                   5544:         }
                   5545:     } else {
1.934     raeburn  5546:         my $homeserver;
                   5547:         if (&is_course($cdom,$cnum)) {
                   5548:             $homeserver = &homeserver($cnum,$cdom);
                   5549:         } else {
                   5550:             $homeserver = &domain($cdom,'primary');
                   5551:         }
                   5552:         if ($homeserver ne 'no_host') {
                   5553:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5554:         }
1.876     raeburn  5555:     }
1.506     raeburn  5556:     return $response;
                   5557: }
1.776     albertel 5558: 
1.506     raeburn  5559: sub auto_get_sections {
1.508     raeburn  5560:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  5561:     my $homeserver;
                   5562:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   5563:         $homeserver = &homeserver($cnum,$cdom);
                   5564:     }
                   5565:     if (!defined($homeserver)) { 
                   5566:         if ($cdom =~ /^$match_domain$/) {
                   5567:             $homeserver = &domain($cdom,'primary');
                   5568:         }
                   5569:     }
                   5570:     my @secs;
                   5571:     if (defined($homeserver)) {
                   5572:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   5573:         unless ($response eq 'refused') {
                   5574:             @secs = split(/:/,$response);
                   5575:         }
1.506     raeburn  5576:     }
                   5577:     return @secs;
                   5578: }
1.776     albertel 5579: 
1.506     raeburn  5580: sub auto_new_course {
1.508     raeburn  5581:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5582:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5583:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5584:     return $response;
                   5585: }
1.776     albertel 5586: 
1.506     raeburn  5587: sub auto_validate_courseID {
1.508     raeburn  5588:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5589:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5590:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5591:     return $response;
                   5592: }
1.776     albertel 5593: 
1.1007    raeburn  5594: sub auto_validate_instcode {
1.1020    raeburn  5595:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  5596:     my ($homeserver,$response);
                   5597:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5598:         $homeserver = &homeserver($cnum,$cdom);
                   5599:     }
                   5600:     if (!defined($homeserver)) {
                   5601:         if ($cdom =~ /^$match_domain$/) {
                   5602:             $homeserver = &domain($cdom,'primary');
                   5603:         }
                   5604:     }
                   5605:     my $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
1.1020    raeburn  5606:                            &escape($instcode).':'.&escape($owner),$homeserver));
1.1007    raeburn  5607:     return $response;
                   5608: }
                   5609: 
1.506     raeburn  5610: sub auto_create_password {
1.873     raeburn  5611:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5612:     my ($homeserver,$response);
1.506     raeburn  5613:     my $create_passwd = 0;
                   5614:     my $authchk = '';
1.873     raeburn  5615:     if ($udom =~ /^$match_domain$/) {
                   5616:         $homeserver = &domain($udom,'primary');
                   5617:     }
                   5618:     if ($homeserver eq '') {
                   5619:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5620:             $homeserver = &homeserver($cnum,$cdom);
                   5621:         }
                   5622:     }
                   5623:     if ($homeserver eq '') {
                   5624:         $authchk = 'nodomain';
1.506     raeburn  5625:     } else {
1.873     raeburn  5626:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5627:         if ($response eq 'refused') {
                   5628:             $authchk = 'refused';
                   5629:         } else {
1.901     albertel 5630:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5631:         }
1.506     raeburn  5632:     }
                   5633:     return ($authparam,$create_passwd,$authchk);
                   5634: }
                   5635: 
1.706     raeburn  5636: sub auto_photo_permission {
                   5637:     my ($cnum,$cdom,$students) = @_;
                   5638:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5639:     my ($outcome,$perm_reqd,$conditions) = 
                   5640: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5641:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5642: 	return (undef,undef);
                   5643:     }
1.706     raeburn  5644:     return ($outcome,$perm_reqd,$conditions);
                   5645: }
                   5646: 
                   5647: sub auto_checkphotos {
                   5648:     my ($uname,$udom,$pid) = @_;
                   5649:     my $homeserver = &homeserver($uname,$udom);
                   5650:     my ($result,$resulttype);
                   5651:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5652: 				   &escape($uname).':'.&escape($pid),
                   5653: 				   $homeserver));
1.709     albertel 5654:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5655: 	return (undef,undef);
                   5656:     }
1.706     raeburn  5657:     if ($outcome) {
                   5658:         ($result,$resulttype) = split(/:/,$outcome);
                   5659:     } 
                   5660:     return ($result,$resulttype);
                   5661: }
                   5662: 
                   5663: sub auto_photochoice {
                   5664:     my ($cnum,$cdom) = @_;
                   5665:     my $homeserver = &homeserver($cnum,$cdom);
                   5666:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5667: 						       &escape($cdom),
                   5668: 						       $homeserver)));
1.709     albertel 5669:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5670: 	return (undef,undef);
                   5671:     }
1.706     raeburn  5672:     return ($update,$comment);
                   5673: }
                   5674: 
                   5675: sub auto_photoupdate {
                   5676:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5677:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5678:     my $host=&hostname($homeserver);
1.706     raeburn  5679:     my $cmd = '';
                   5680:     my $maxtries = 1;
1.800     albertel 5681:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5682:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5683:     }
                   5684:     $cmd =~ s/%%$//;
                   5685:     $cmd = &escape($cmd);
                   5686:     my $query = 'institutionalphotos';
                   5687:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5688:     unless ($queryid=~/^\Q$host\E\_/) {
                   5689:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5690:         return 'error: '.$queryid;
                   5691:     }
                   5692:     my $reply = &get_query_reply($queryid);
                   5693:     my $tries = 1;
                   5694:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5695:         $reply = &get_query_reply($queryid);
                   5696:         $tries ++;
                   5697:     }
                   5698:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5699:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5700:     } else {
                   5701:         my @responses = split(/:/,$reply);
                   5702:         my $outcome = shift(@responses); 
                   5703:         foreach my $item (@responses) {
                   5704:             my ($key,$value) = split(/=/,$item);
                   5705:             $$photo{$key} = $value;
                   5706:         }
                   5707:         return $outcome;
                   5708:     }
                   5709:     return 'error';
                   5710: }
                   5711: 
1.521     raeburn  5712: sub auto_instcode_format {
1.793     albertel 5713:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5714: 	$cat_order) = @_;
1.521     raeburn  5715:     my $courses = '';
1.772     raeburn  5716:     my @homeservers;
1.521     raeburn  5717:     if ($caller eq 'global') {
1.841     albertel 5718: 	my %servers = &get_servers($codedom,'library');
                   5719: 	foreach my $tryserver (keys(%servers)) {
                   5720: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5721: 		push(@homeservers,$tryserver);
                   5722: 	    }
1.584     raeburn  5723:         }
1.1022    raeburn  5724:     } elsif ($caller eq 'requests') {
                   5725:         if ($codedom =~ /^$match_domain$/) {
                   5726:             my $chome = &domain($codedom,'primary');
                   5727:             unless ($chome eq 'no_host') {
                   5728:                 push(@homeservers,$chome);
                   5729:             }
                   5730:         }
1.521     raeburn  5731:     } else {
1.772     raeburn  5732:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5733:     }
1.793     albertel 5734:     foreach my $code (keys(%{$instcodes})) {
                   5735:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5736:     }
                   5737:     chop($courses);
1.772     raeburn  5738:     my $ok_response = 0;
                   5739:     my $response;
                   5740:     while (@homeservers > 0 && $ok_response == 0) {
                   5741:         my $server = shift(@homeservers); 
                   5742:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5743:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5744:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5745: 		split(/:/,$response);
1.772     raeburn  5746:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5747:             push(@{$codetitles},&str2array($codetitles_str));
                   5748:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5749:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5750:             $ok_response = 1;
                   5751:         }
                   5752:     }
                   5753:     if ($ok_response) {
1.521     raeburn  5754:         return 'ok';
1.772     raeburn  5755:     } else {
                   5756:         return $response;
1.521     raeburn  5757:     }
                   5758: }
                   5759: 
1.792     raeburn  5760: sub auto_instcode_defaults {
                   5761:     my ($domain,$returnhash,$code_order) = @_;
                   5762:     my @homeservers;
1.841     albertel 5763: 
                   5764:     my %servers = &get_servers($domain,'library');
                   5765:     foreach my $tryserver (keys(%servers)) {
                   5766: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5767: 	    push(@homeservers,$tryserver);
                   5768: 	}
1.792     raeburn  5769:     }
1.841     albertel 5770: 
1.792     raeburn  5771:     my $response;
1.841     albertel 5772:     foreach my $server (@homeservers) {
1.792     raeburn  5773:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5774:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5775: 	
                   5776: 	foreach my $pair (split(/\&/,$response)) {
                   5777: 	    my ($name,$value)=split(/\=/,$pair);
                   5778: 	    if ($name eq 'code_order') {
                   5779: 		@{$code_order} = split(/\&/,&unescape($value));
                   5780: 	    } else {
                   5781: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5782: 	    }
                   5783: 	}
                   5784: 	return 'ok';
1.792     raeburn  5785:     }
1.841     albertel 5786: 
                   5787:     return $response;
1.1003    raeburn  5788: }
                   5789: 
                   5790: sub auto_possible_instcodes {
1.1007    raeburn  5791:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   5792:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   5793:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   5794:         return;
                   5795:     }
1.1003    raeburn  5796:     my (@homeservers,$uhome);
                   5797:     if (defined(&domain($domain,'primary'))) {
                   5798:         $uhome=&domain($domain,'primary');
                   5799:         push(@homeservers,&domain($domain,'primary'));
                   5800:     } else {
                   5801:         my %servers = &get_servers($domain,'library');
                   5802:         foreach my $tryserver (keys(%servers)) {
                   5803:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5804:                 push(@homeservers,$tryserver);
                   5805:             }
                   5806:         }
                   5807:     }
                   5808:     my $response;
                   5809:     foreach my $server (@homeservers) {
                   5810:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   5811:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  5812:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   5813:             split(':',$response);
                   5814:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   5815:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  5816:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  5817:             my ($name,$value)=split('=',$item);
                   5818:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  5819:         }
                   5820:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  5821:             my ($name,$value)=split('=',$item);
                   5822:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  5823:         }
                   5824:         return 'ok';
                   5825:     }
                   5826:     return $response;
                   5827: }
1.792     raeburn  5828: 
1.1010    raeburn  5829: sub auto_courserequest_checks {
                   5830:     my ($dom) = @_;
1.1020    raeburn  5831:     my ($homeserver,%validations);
                   5832:     if ($dom =~ /^$match_domain$/) {
                   5833:         $homeserver = &domain($dom,'primary');
                   5834:     }
                   5835:     unless ($homeserver eq 'no_host') {
                   5836:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   5837:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   5838:             my @items = split(/&/,$response);
                   5839:             foreach my $item (@items) {
                   5840:                 my ($key,$value) = split('=',$item);
                   5841:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   5842:             }
                   5843:         }
                   5844:     }
1.1010    raeburn  5845:     return %validations; 
                   5846: }
                   5847: 
1.1020    raeburn  5848: sub auto_courserequest_validation {
                   5849:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   5850:     my ($homeserver,$response);
                   5851:     if ($dom =~ /^$match_domain$/) {
                   5852:         $homeserver = &domain($dom,'primary');
                   5853:     }
                   5854:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  5855:           
1.1020    raeburn  5856:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  5857:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  5858:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   5859:                                     $homeserver));
                   5860:     }
                   5861:     return $response;
                   5862: }
                   5863: 
1.777     albertel 5864: sub auto_validate_class_sec {
1.918     raeburn  5865:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5866:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5867:     my $ownerlist;
                   5868:     if (ref($owners) eq 'ARRAY') {
                   5869:         $ownerlist = join(',',@{$owners});
                   5870:     } else {
                   5871:         $ownerlist = $owners;
                   5872:     }
1.773     raeburn  5873:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5874:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5875:     return $response;
                   5876: }
                   5877: 
1.679     raeburn  5878: # ------------------------------------------------------- Course Group routines
                   5879: 
                   5880: sub get_coursegroups {
1.809     raeburn  5881:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5882:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5883: }
                   5884: 
1.679     raeburn  5885: sub modify_coursegroup {
                   5886:     my ($cdom,$cnum,$groupsettings) = @_;
                   5887:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5888: }
                   5889: 
1.809     raeburn  5890: sub toggle_coursegroup_status {
                   5891:     my ($cdom,$cnum,$group,$action) = @_;
                   5892:     my ($from_namespace,$to_namespace);
                   5893:     if ($action eq 'delete') {
                   5894:         $from_namespace = 'coursegroups';
                   5895:         $to_namespace = 'deleted_groups';
                   5896:     } else {
                   5897:         $from_namespace = 'deleted_groups';
                   5898:         $to_namespace = 'coursegroups';
                   5899:     }
                   5900:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5901:     if (my $tmp = &error(%curr_group)) {
                   5902:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5903:         return ('read error',$tmp);
                   5904:     } else {
                   5905:         my %savedsettings = %curr_group; 
1.809     raeburn  5906:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5907:         my $deloutcome;
                   5908:         if ($result eq 'ok') {
1.809     raeburn  5909:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5910:         } else {
                   5911:             return ('write error',$result);
                   5912:         }
                   5913:         if ($deloutcome eq 'ok') {
                   5914:             return 'ok';
                   5915:         } else {
                   5916:             return ('delete error',$deloutcome);
                   5917:         }
                   5918:     }
                   5919: }
                   5920: 
1.679     raeburn  5921: sub modify_group_roles {
1.957     raeburn  5922:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  5923:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5924:     my $role = 'gr/'.&escape($userprivs);
                   5925:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  5926:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  5927:     if ($result eq 'ok') {
                   5928:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5929:     }
1.679     raeburn  5930:     return $result;
                   5931: }
                   5932: 
                   5933: sub modify_coursegroup_membership {
                   5934:     my ($cdom,$cnum,$membership) = @_;
                   5935:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5936:     return $result;
                   5937: }
                   5938: 
1.682     raeburn  5939: sub get_active_groups {
                   5940:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5941:     my $now = time;
                   5942:     my %groups = ();
                   5943:     foreach my $key (keys(%env)) {
1.811     albertel 5944:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5945:             my ($start,$end) = split(/\./,$env{$key});
                   5946:             if (($end!=0) && ($end<$now)) { next; }
                   5947:             if (($start!=0) && ($start>$now)) { next; }
                   5948:             if ($1 eq $cdom && $2 eq $cnum) {
                   5949:                 $groups{$3} = $env{$key} ;
                   5950:             }
                   5951:         }
                   5952:     }
                   5953:     return %groups;
                   5954: }
                   5955: 
1.683     raeburn  5956: sub get_group_membership {
                   5957:     my ($cdom,$cnum,$group) = @_;
                   5958:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5959: }
                   5960: 
                   5961: sub get_users_groups {
                   5962:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5963:     my @usersgroups;
1.683     raeburn  5964:     my $cachetime=1800;
                   5965: 
                   5966:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5967:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5968:     if (defined($cached)) {
1.734     albertel 5969:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5970:     } else {  
                   5971:         $grouplist = '';
1.816     raeburn  5972:         my $courseurl = &courseid_to_courseurl($courseid);
                   5973:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5974:         my $access_end = $env{'course.'.$courseid.
                   5975:                               '.default_enrollment_end_date'};
                   5976:         my $now = time;
                   5977:         foreach my $key (keys(%roleshash)) {
                   5978:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5979:                 my $group = $1;
                   5980:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5981:                     my $start = $2;
                   5982:                     my $end = $1;
                   5983:                     if ($start == -1) { next; } # deleted from group
                   5984:                     if (($start!=0) && ($start>$now)) { next; }
                   5985:                     if (($end!=0) && ($end<$now)) {
                   5986:                         if ($access_end && $access_end < $now) {
                   5987:                             if ($access_end - $end < 86400) {
                   5988:                                 push(@usersgroups,$group);
1.733     raeburn  5989:                             }
                   5990:                         }
1.817     raeburn  5991:                         next;
1.733     raeburn  5992:                     }
1.817     raeburn  5993:                     push(@usersgroups,$group);
1.683     raeburn  5994:                 }
                   5995:             }
                   5996:         }
1.817     raeburn  5997:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5998:         $grouplist = join(':',@usersgroups);
                   5999:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6000:     }
1.733     raeburn  6001:     return @usersgroups;
1.683     raeburn  6002: }
                   6003: 
                   6004: sub devalidate_getgroups_cache {
                   6005:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6006:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6007: 
1.683     raeburn  6008:     my $hashid="$udom:$uname:$courseid";
                   6009:     &devalidate_cache_new('getgroups',$hashid);
                   6010: }
                   6011: 
1.12      www      6012: # ------------------------------------------------------------------ Plain Text
                   6013: 
                   6014: sub plaintext {
1.988     raeburn  6015:     my ($short,$type,$cid,$forcedefault) = @_;
1.758     albertel 6016:     if ($short =~ /^cr/) {
                   6017: 	return (split('/',$short))[-1];
                   6018:     }
1.742     raeburn  6019:     if (!defined($cid)) {
                   6020:         $cid = $env{'request.course.id'};
                   6021:     }
1.988     raeburn  6022:     if (defined($cid) && ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '')) {
                   6023:         unless ($forcedefault) {
                   6024:             my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6025:             &Apache::lonlocal::mt_escape(\$roletext);
                   6026:             return &Apache::lonlocal::mt($roletext);
                   6027:         }
1.742     raeburn  6028:     }
                   6029:     my %rolenames = (
1.1008    raeburn  6030:                       Course    => 'std',
                   6031:                       Community => 'alt1',
1.742     raeburn  6032:                     );
                   6033:     if (defined($type) && 
                   6034:          defined($rolenames{$type}) && 
                   6035:          defined($prp{$short}{$rolenames{$type}})) {
                   6036:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   6037:     } else {
                   6038:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   6039:     }
1.12      www      6040: }
                   6041: 
                   6042: # ----------------------------------------------------------------- Assign Role
                   6043: 
                   6044: sub assignrole {
1.957     raeburn  6045:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6046:         $context)=@_;
1.21      www      6047:     my $mrole;
                   6048:     if ($role =~ /^cr\//) {
1.393     www      6049:         my $cwosec=$url;
1.811     albertel 6050:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      6051: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      6052:            &logthis('Refused custom assignrole: '.
                   6053:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 6054: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      6055:            return 'refused'; 
                   6056:         }
1.21      www      6057:         $mrole='cr';
1.678     raeburn  6058:     } elsif ($role =~ /^gr\//) {
                   6059:         my $cwogrp=$url;
1.811     albertel 6060:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  6061:         unless (&allowed('mdg',$cwogrp)) {
                   6062:             &logthis('Refused group assignrole: '.
                   6063:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   6064:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   6065:             return 'refused';
                   6066:         }
                   6067:         $mrole='gr';
1.21      www      6068:     } else {
1.82      www      6069:         my $cwosec=$url;
1.811     albertel 6070:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  6071:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   6072:             my $refused;
                   6073:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   6074:                 if (!(&allowed('c'.$role,$url))) {
                   6075:                     $refused = 1;
                   6076:                 }
                   6077:             } else {
                   6078:                 $refused = 1;
                   6079:             }
1.947     raeburn  6080:             if ($refused) {
                   6081:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6082:                     $refused = '';
1.1017    raeburn  6083:                 } elsif ($context eq 'requestcourses') {
                   6084:                     if (($role eq 'cc') && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
                   6085:                         my ($cdom,$cnum) = ($cwosec =~ m{^/($match_domain)/($match_courseid)$});
                   6086:                         my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6087:                         if ($crsenv{'internal.courseowner'} eq 
                   6088:                              $env{'user.name'}.':'.$env{'user.domain'}) {
                   6089:                             $refused = '';
                   6090:                         }
                   6091:                     }
                   6092:                 }
                   6093:                 if ($refused) {
1.947     raeburn  6094:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   6095:                              ' '.$role.' '.$end.' '.$start.' by '.
                   6096: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   6097:                     return 'refused';
                   6098:                 }
1.932     raeburn  6099:             }
1.104     www      6100:         }
1.21      www      6101:         $mrole=$role;
                   6102:     }
1.620     albertel 6103:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6104:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6105:     if ($end) { $command.='_'.$end; }
1.21      www      6106:     if ($start) {
                   6107: 	if ($end) { 
1.81      www      6108:            $command.='_'.$start; 
1.21      www      6109:         } else {
1.81      www      6110:            $command.='_0_'.$start;
1.21      www      6111:         }
                   6112:     }
1.739     raeburn  6113:     my $origstart = $start;
                   6114:     my $origend = $end;
1.957     raeburn  6115:     my $delflag;
1.357     www      6116: # actually delete
                   6117:     if ($deleteflag) {
1.373     www      6118: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6119: # modify command to delete the role
1.620     albertel 6120:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6121:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6122: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6123: # set start and finish to negative values for userrolelog
                   6124:            $start=-1;
                   6125:            $end=-1;
1.957     raeburn  6126:            $delflag = 1;
1.357     www      6127:         }
                   6128:     }
                   6129: # send command
1.349     www      6130:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6131: # log new user role if status is ok
1.349     www      6132:     if ($answer eq 'ok') {
1.663     raeburn  6133: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6134: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6135:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6136:         unless ($role =~ /^gr/) {
                   6137:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6138:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6139:         }
1.349     www      6140:     }
                   6141:     return $answer;
1.169     harris41 6142: }
                   6143: 
                   6144: # -------------------------------------------------- Modify user authentication
1.197     www      6145: # Overrides without validation
                   6146: 
1.169     harris41 6147: sub modifyuserauth {
                   6148:     my ($udom,$uname,$umode,$upass)=@_;
                   6149:     my $uhome=&homeserver($uname,$udom);
1.197     www      6150:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6151:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6152:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6153:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6154:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6155: 		     &escape($upass),$uhome);
1.620     albertel 6156:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6157:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6158:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6159:     &log($udom,,$uname,$uhome,
1.620     albertel 6160:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6161:                                      $env{'user.name'}.', '.$umode.
1.197     www      6162:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 6163:     unless ($reply eq 'ok') {
1.197     www      6164:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 6165: 	return 'error: '.$reply;
                   6166:     }   
1.170     harris41 6167:     return 'ok';
1.80      www      6168: }
                   6169: 
1.81      www      6170: # --------------------------------------------------------------- Modify a user
1.80      www      6171: 
1.81      www      6172: sub modifyuser {
1.206     matthew  6173:     my ($udom,    $uname, $uid,
                   6174:         $umode,   $upass, $first,
                   6175:         $middle,  $last,  $gene,
1.963     raeburn  6176:         $forceid, $desiredhome, $email, $inststatus)=@_;
1.807     albertel 6177:     $udom= &LONCAPA::clean_domain($udom);
                   6178:     $uname=&LONCAPA::clean_username($uname);
1.81      www      6179:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      6180:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  6181: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   6182:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   6183:                                      ' desiredhome not specified'). 
1.620     albertel 6184:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6185:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 6186:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      6187: # ----------------------------------------------------------------- Create User
1.406     albertel 6188:     if (($uhome eq 'no_host') && 
                   6189: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      6190:         my $unhome='';
1.844     albertel 6191:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  6192:             $unhome = $desiredhome;
1.620     albertel 6193: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   6194: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  6195:         } else { # load balancing routine for determining $unhome
1.81      www      6196:             my $loadm=10000000;
1.841     albertel 6197: 	    my %servers = &get_servers($udom,'library');
                   6198: 	    foreach my $tryserver (keys(%servers)) {
                   6199: 		my $answer=reply('load',$tryserver);
                   6200: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   6201: 		    $loadm=$answer;
                   6202: 		    $unhome=$tryserver;
                   6203: 		}
1.80      www      6204: 	    }
                   6205:         }
                   6206:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  6207: 	    return 'error: unable to find a home server for '.$uname.
                   6208:                    ' in domain '.$udom;
1.80      www      6209:         }
                   6210:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   6211:                          &escape($upass),$unhome);
                   6212: 	unless ($reply eq 'ok') {
                   6213:             return 'error: '.$reply;
                   6214:         }   
1.230     stredwic 6215:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      6216:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  6217: 	    return 'error: unable verify users home machine.';
1.80      www      6218:         }
1.209     matthew  6219:     }   # End of creation of new user
1.80      www      6220: # ---------------------------------------------------------------------- Add ID
                   6221:     if ($uid) {
                   6222:        $uid=~tr/A-Z/a-z/;
                   6223:        my %uidhash=&idrget($udom,$uname);
1.196     www      6224:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   6225:          && (!$forceid)) {
1.80      www      6226: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  6227: 	      return 'error: user id "'.$uid.'" does not match '.
                   6228:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      6229:           }
                   6230:        } else {
                   6231: 	  &idput($udom,($uname => $uid));
                   6232:        }
                   6233:     }
                   6234: # -------------------------------------------------------------- Add names, etc
1.313     matthew  6235:     my @tmp=&get('environment',
1.899     raeburn  6236: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  6237:                     'permanentemail','inststatus'],
1.134     albertel 6238: 		   $udom,$uname);
1.313     matthew  6239:     my %names;
                   6240:     if ($tmp[0] =~ m/^error:.*/) { 
                   6241:         %names=(); 
                   6242:     } else {
                   6243:         %names = @tmp;
                   6244:     }
1.388     www      6245: #
                   6246: # Make sure to not trash student environment if instructor does not bother
                   6247: # to supply name and email information
                   6248: #
                   6249:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  6250:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      6251:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  6252:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      6253:     if ($email) {
                   6254:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  6255:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      6256:     }
1.899     raeburn  6257:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  6258:     if (defined($inststatus)) {
                   6259:         $names{'inststatus'} = '';
                   6260:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   6261:         if (ref($usertypes) eq 'HASH') {
                   6262:             my @okstatuses; 
                   6263:             foreach my $item (split(/:/,$inststatus)) {
                   6264:                 if (defined($usertypes->{$item})) {
                   6265:                     push(@okstatuses,$item);  
                   6266:                 }
                   6267:             }
                   6268:             if (@okstatuses) {
                   6269:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   6270:             }
                   6271:         }
                   6272:     }
1.134     albertel 6273:     my $reply = &put('environment', \%names, $udom,$uname);
                   6274:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  6275:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      6276:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963     raeburn  6277:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
                   6278:                  $umode.', '.$first.', '.$middle.', '.
                   6279: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
                   6280:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   6281:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   6282:     } else {
                   6283:         $logmsg .= ' during self creation';
                   6284:     }
                   6285:     &logthis($logmsg);
1.134     albertel 6286:     return 'ok';
1.80      www      6287: }
                   6288: 
1.81      www      6289: # -------------------------------------------------------------- Modify student
1.80      www      6290: 
1.81      www      6291: sub modifystudent {
                   6292:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  6293:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  6294:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 6295:     if (!$cid) {
1.620     albertel 6296: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6297: 	    return 'not_in_class';
                   6298: 	}
1.80      www      6299:     }
                   6300: # --------------------------------------------------------------- Make the user
1.81      www      6301:     my $reply=&modifyuser
1.209     matthew  6302: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  6303:          $desiredhome,$email,$inststatus);
1.80      www      6304:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  6305:     # This will cause &modify_student_enrollment to get the uid from the
                   6306:     # students environment
                   6307:     $uid = undef if (!$forceid);
1.455     albertel 6308:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  6309: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  6310:     return $reply;
                   6311: }
                   6312: 
                   6313: sub modify_student_enrollment {
1.957     raeburn  6314:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 6315:     my ($cdom,$cnum,$chome);
                   6316:     if (!$cid) {
1.620     albertel 6317: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6318: 	    return 'not_in_class';
                   6319: 	}
1.620     albertel 6320: 	$cdom=$env{'course.'.$cid.'.domain'};
                   6321: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 6322:     } else {
                   6323: 	($cdom,$cnum)=split(/_/,$cid);
                   6324:     }
1.620     albertel 6325:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 6326:     if (!$chome) {
1.457     raeburn  6327: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  6328:     }
1.455     albertel 6329:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  6330:     # Make sure the user exists
1.81      www      6331:     my $uhome=&homeserver($uname,$udom);
                   6332:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6333: 	return 'error: no such user';
                   6334:     }
1.297     matthew  6335:     # Get student data if we were not given enough information
                   6336:     if (!defined($first)  || $first  eq '' || 
                   6337:         !defined($last)   || $last   eq '' || 
                   6338:         !defined($uid)    || $uid    eq '' || 
                   6339:         !defined($middle) || $middle eq '' || 
                   6340:         !defined($gene)   || $gene   eq '') {
1.294     matthew  6341:         # They did not supply us with enough data to enroll the student, so
                   6342:         # we need to pick up more information.
1.297     matthew  6343:         my %tmp = &get('environment',
1.294     matthew  6344:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  6345:                        ,$udom,$uname);
                   6346: 
1.800     albertel 6347:         #foreach my $key (keys(%tmp)) {
                   6348:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 6349:         #}
1.294     matthew  6350:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   6351:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   6352:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  6353:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  6354:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   6355:     }
1.556     albertel 6356:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 6357:     my $reply=cput('classlist',
                   6358: 		   {"$uname:$udom" => 
1.515     raeburn  6359: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 6360: 		   $cdom,$cnum);
1.81      www      6361:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   6362: 	return 'error: '.$reply;
1.652     albertel 6363:     } else {
                   6364: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      6365:     }
1.297     matthew  6366:     # Add student role to user
1.83      www      6367:     my $uurl='/'.$cid;
1.81      www      6368:     $uurl=~s/\_/\//g;
                   6369:     if ($usec) {
                   6370: 	$uurl.='/'.$usec;
                   6371:     }
1.957     raeburn  6372:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      6373: }
                   6374: 
1.556     albertel 6375: sub format_name {
                   6376:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   6377:     my $name;
                   6378:     if ($first ne 'lastname') {
                   6379: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   6380:     } else {
                   6381: 	if ($lastname=~/\S/) {
                   6382: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   6383: 	    $name=~s/\s+,/,/;
                   6384: 	} else {
                   6385: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   6386: 	}
                   6387:     }
                   6388:     $name=~s/^\s+//;
                   6389:     $name=~s/\s+$//;
                   6390:     $name=~s/\s+/ /g;
                   6391:     return $name;
                   6392: }
                   6393: 
1.84      www      6394: # ------------------------------------------------- Write to course preferences
                   6395: 
                   6396: sub writecoursepref {
                   6397:     my ($courseid,%prefs)=@_;
                   6398:     $courseid=~s/^\///;
                   6399:     $courseid=~s/\_/\//g;
                   6400:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   6401:     my $chome=homeserver($cnum,$cdomain);
                   6402:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   6403: 	return 'error: no such course';
                   6404:     }
                   6405:     my $cstring='';
1.800     albertel 6406:     foreach my $pref (keys(%prefs)) {
                   6407: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 6408:     }
1.84      www      6409:     $cstring=~s/\&$//;
                   6410:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   6411: }
                   6412: 
                   6413: # ---------------------------------------------------------- Make/modify course
                   6414: 
                   6415: sub createcourse {
1.741     raeburn  6416:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  6417:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      6418:     $url=&declutter($url);
                   6419:     my $cid='';
1.264     matthew  6420:     unless (&allowed('ccc',$udom)) {
1.1017    raeburn  6421:         if ($context eq 'requestcourses') {
                   6422:             unless (&usertools_access($course_owner,$udom,$category,undef,$context)) {
                   6423:                 return 'refused';
                   6424:             }
                   6425:         } else {
                   6426:             return 'refused';
                   6427:         }
1.84      www      6428:     }
1.1011    raeburn  6429: # --------------------------------------------------------------- Get Unique ID
                   6430:     my $uname;
                   6431:     if ($cnum =~ /^$match_courseid$/) {
                   6432:         my $chome=&homeserver($cnum,$udom,'true');
                   6433:         if (($chome eq '') || ($chome eq 'no_host')) {
                   6434:             $uname = $cnum;
                   6435:         } else {
                   6436:             $uname = &generate_coursenum($udom);
                   6437:         }
                   6438:     } else {
                   6439:         $uname = &generate_coursenum($udom);
                   6440:     }
                   6441:     return $uname if ($uname =~ /^error/);
                   6442: # -------------------------------------------------- Check supplied server name
1.620     albertel 6443:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 6444:     if (! &is_library($course_server)) {
1.264     matthew  6445:         return 'error:bad server name '.$course_server;
                   6446:     }
1.84      www      6447: # ------------------------------------------------------------- Make the course
                   6448:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  6449:                       $course_server);
1.84      www      6450:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  6451:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      6452:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6453: 	return 'error: no such course';
                   6454:     }
1.271     www      6455: # ----------------------------------------------------------------- Course made
1.516     raeburn  6456: # log existence
1.918     raeburn  6457:     my $newcourse = {
                   6458:                     $udom.'_'.$uname => {
1.921     raeburn  6459:                                      description => $description,
                   6460:                                      inst_code   => $inst_code,
                   6461:                                      owner       => $course_owner,
                   6462:                                      type        => $crstype,
1.918     raeburn  6463:                                                 },
                   6464:                     };
1.921     raeburn  6465:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      6466: # set toplevel url
1.271     www      6467:     my $topurl=$url;
                   6468:     unless ($nonstandard) {
                   6469: # ------------------------------------------ For standard courses, make top url
                   6470:         my $mapurl=&clutter($url);
1.278     www      6471:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 6472:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      6473: <map>
                   6474: <resource id="1" type="start"></resource>
                   6475: <resource id="2" src="$mapurl"></resource>
                   6476: <resource id="3" type="finish"></resource>
                   6477: <link index="1" from="1" to="2"></link>
                   6478: <link index="2" from="2" to="3"></link>
                   6479: </map>
                   6480: ENDINITMAP
                   6481:         $topurl=&declutter(
1.638     albertel 6482:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      6483:                           );
                   6484:     }
                   6485: # ----------------------------------------------------------- Write preferences
1.84      www      6486:     &writecoursepref($udom.'_'.$uname,
                   6487:                      ('description' => $description,
1.271     www      6488:                       'url'         => $topurl));
1.84      www      6489:     return '/'.$udom.'/'.$uname;
                   6490: }
                   6491: 
1.1011    raeburn  6492: # ------------------------------------------------------------------- Create ID
                   6493: sub generate_coursenum {
                   6494:     my ($udom) = @_;
                   6495:     my $domdesc = &domain($udom);
                   6496:     return 'error: invalid domain' if ($domdesc eq '');
                   6497:     my $uname=int(1+rand(9)).
                   6498:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   6499:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   6500:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   6501: # ----------------------------------------------- Make sure that does not exist
                   6502:     my $uhome=&homeserver($uname,$udom,'true');
                   6503:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6504:         $uname=int(1+rand(9)).
                   6505:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   6506:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   6507:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   6508:         $uhome=&homeserver($uname,$udom,'true');
                   6509:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6510:             return 'error: unable to generate unique course-ID';
                   6511:         }
                   6512:     }
                   6513:     return $uname;
                   6514: }
                   6515: 
1.813     albertel 6516: sub is_course {
                   6517:     my ($cdom,$cnum) = @_;
                   6518:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  6519: 				undef,'.');
1.813     albertel 6520:     if (exists($courses{$cdom.'_'.$cnum})) {
                   6521:         return 1;
                   6522:     }
                   6523:     return 0;
                   6524: }
                   6525: 
1.1015    raeburn  6526: sub store_userdata {
                   6527:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  6528:     my $result;
1.1016    raeburn  6529:     if ($datakey ne '') {
1.1013    raeburn  6530:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  6531:             if ($udom eq '' || $uname eq '') {
                   6532:                 $udom = $env{'user.domain'};
                   6533:                 $uname = $env{'user.name'};
                   6534:             }
                   6535:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  6536:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   6537:                 $result = 'error: no_host';
                   6538:             } else {
                   6539:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   6540:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   6541: 
                   6542:                 my $namevalue='';
                   6543:                 foreach my $key (keys(%{$storehash})) {
                   6544:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6545:                 }
                   6546:                 $namevalue=~s/\&$//;
                   6547:                 $result =  &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015    raeburn  6548:                                   "$namespace:$datakey:$namevalue",$uhome);
1.1013    raeburn  6549:             }
                   6550:         } else {
                   6551:             $result = 'error: data to store was not a hash reference'; 
                   6552:         }
                   6553:     } else {
                   6554:         $result= 'error: invalid requestkey'; 
                   6555:     }
                   6556:     return $result;
                   6557: }
                   6558: 
1.21      www      6559: # ---------------------------------------------------------- Assign Custom Role
                   6560: 
                   6561: sub assigncustomrole {
1.957     raeburn  6562:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6563:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  6564:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      6565: }
                   6566: 
                   6567: # ----------------------------------------------------------------- Revoke Role
                   6568: 
                   6569: sub revokerole {
1.957     raeburn  6570:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6571:     my $now=time;
1.965     raeburn  6572:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      6573: }
                   6574: 
                   6575: # ---------------------------------------------------------- Revoke Custom Role
                   6576: 
                   6577: sub revokecustomrole {
1.957     raeburn  6578:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6579:     my $now=time;
1.357     www      6580:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  6581:            $deleteflag,$selfenroll,$context);
1.17      www      6582: }
                   6583: 
1.533     banghart 6584: # ------------------------------------------------------------ Disk usage
1.535     albertel 6585: sub diskusage {
1.955     raeburn  6586:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   6587:     $directorypath =~ s/\/$//;
                   6588:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   6589:                        .&escape($getpropath).':'.&escape($uname).':'
                   6590:                        .&escape($udom),homeserver($uname,$udom));
                   6591:     if ($listing eq 'unknown_cmd') {
                   6592:         if ($getpropath) {
                   6593:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   6594:         }
                   6595:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   6596:     }
1.514     albertel 6597:     return $listing;
1.512     banghart 6598: }
                   6599: 
1.566     banghart 6600: sub is_locked {
                   6601:     my ($file_name, $domain, $user) = @_;
                   6602:     my @check;
                   6603:     my $is_locked;
                   6604:     push @check, $file_name;
1.613     albertel 6605:     my %locked = &get('file_permissions',\@check,
1.620     albertel 6606: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 6607:     my ($tmp)=keys(%locked);
                   6608:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  6609:     
1.566     banghart 6610:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  6611:         $is_locked = 'false';
                   6612:         foreach my $entry (@{$locked{$file_name}}) {
                   6613:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  6614:                $is_locked = 'true';
                   6615:                last;
1.745     raeburn  6616:            }
                   6617:        }
1.566     banghart 6618:     } else {
                   6619:         $is_locked = 'false';
                   6620:     }
                   6621: }
                   6622: 
1.759     albertel 6623: sub declutter_portfile {
                   6624:     my ($file) = @_;
1.833     albertel 6625:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 6626:     return $file;
                   6627: }
                   6628: 
1.559     banghart 6629: # ------------------------------------------------------------- Mark as Read Only
                   6630: 
                   6631: sub mark_as_readonly {
                   6632:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 6633:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6634:     my ($tmp)=keys(%current_permissions);
                   6635:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 6636:     foreach my $file (@{$files}) {
1.759     albertel 6637: 	$file = &declutter_portfile($file);
1.561     banghart 6638:         push(@{$current_permissions{$file}},$what);
1.559     banghart 6639:     }
1.613     albertel 6640:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6641:     return;
                   6642: }
                   6643: 
1.572     banghart 6644: # ------------------------------------------------------------Save Selected Files
                   6645: 
                   6646: sub save_selected_files {
                   6647:     my ($user, $path, @files) = @_;
                   6648:     my $filename = $user."savedfiles";
1.573     banghart 6649:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 6650:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 6651:     foreach my $file (@files) {
1.620     albertel 6652:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 6653:     }
                   6654:     foreach my $file (@other_files) {
1.574     banghart 6655:         print (OUT $file."\n");
1.572     banghart 6656:     }
1.574     banghart 6657:     close (OUT);
1.572     banghart 6658:     return 'ok';
                   6659: }
                   6660: 
1.574     banghart 6661: sub clear_selected_files {
                   6662:     my ($user) = @_;
                   6663:     my $filename = $user."savedfiles";
                   6664:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6665:     print (OUT undef);
                   6666:     close (OUT);
                   6667:     return ("ok");    
                   6668: }
                   6669: 
1.572     banghart 6670: sub files_in_path {
                   6671:     my ($user, $path) = @_;
                   6672:     my $filename = $user."savedfiles";
                   6673:     my %return_files;
1.574     banghart 6674:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 6675:     while (my $line_in = <IN>) {
1.574     banghart 6676:         chomp ($line_in);
                   6677:         my @paths_and_file = split (m!/!, $line_in);
                   6678:         my $file_part = pop (@paths_and_file);
                   6679:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 6680:         $path_part.='/';
                   6681:         my $path_and_file = $path_part.$file_part;
                   6682:         if ($path_part eq $path) {
                   6683:             $return_files{$file_part}= 'selected';
                   6684:         }
                   6685:     }
1.574     banghart 6686:     close (IN);
                   6687:     return (\%return_files);
1.572     banghart 6688: }
                   6689: 
                   6690: # called in portfolio select mode, to show files selected NOT in current directory
                   6691: sub files_not_in_path {
                   6692:     my ($user, $path) = @_;
                   6693:     my $filename = $user."savedfiles";
                   6694:     my @return_files;
                   6695:     my $path_part;
1.800     albertel 6696:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6697:     while (my $line = <IN>) {
1.572     banghart 6698:         #ok, I know it's clunky, but I want it to work
1.800     albertel 6699:         my @paths_and_file = split(m|/|, $line);
                   6700:         my $file_part = pop(@paths_and_file);
                   6701:         chomp($file_part);
                   6702:         my $path_part = join('/', @paths_and_file);
1.572     banghart 6703:         $path_part .= '/';
                   6704:         my $path_and_file = $path_part.$file_part;
                   6705:         if ($path_part ne $path) {
1.800     albertel 6706:             push(@return_files, ($path_and_file));
1.572     banghart 6707:         }
                   6708:     }
1.800     albertel 6709:     close(OUT);
1.574     banghart 6710:     return (@return_files);
1.572     banghart 6711: }
                   6712: 
1.745     raeburn  6713: #----------------------------------------------Get portfolio file permissions
1.629     banghart 6714: 
1.745     raeburn  6715: sub get_portfile_permissions {
                   6716:     my ($domain,$user) = @_;
1.613     albertel 6717:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6718:     my ($tmp)=keys(%current_permissions);
                   6719:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6720:     return \%current_permissions;
                   6721: }
                   6722: 
                   6723: #---------------------------------------------Get portfolio file access controls
                   6724: 
1.749     raeburn  6725: sub get_access_controls {
1.745     raeburn  6726:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 6727:     my %access;
                   6728:     my $real_file = $file;
                   6729:     $file =~ s/\.meta$//;
1.745     raeburn  6730:     if (defined($file)) {
1.749     raeburn  6731:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   6732:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 6733:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  6734:             }
                   6735:         }
1.745     raeburn  6736:     } else {
1.749     raeburn  6737:         foreach my $key (keys(%{$current_permissions})) {
                   6738:             if ($key =~ /\0accesscontrol$/) {
                   6739:                 if (defined($group)) {
                   6740:                     if ($key !~ m-^\Q$group\E/-) {
                   6741:                         next;
                   6742:                     }
                   6743:                 }
                   6744:                 my ($fullpath) = split(/\0/,$key);
                   6745:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   6746:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   6747:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   6748:                     }
                   6749:                 }
                   6750:             }
                   6751:         }
                   6752:     }
                   6753:     return %access;
                   6754: }
                   6755: 
                   6756: sub modify_access_controls {
                   6757:     my ($file_name,$changes,$domain,$user)=@_;
                   6758:     my ($outcome,$deloutcome);
                   6759:     my %store_permissions;
                   6760:     my %new_values;
                   6761:     my %new_control;
                   6762:     my %translation;
                   6763:     my @deletions = ();
                   6764:     my $now = time;
                   6765:     if (exists($$changes{'activate'})) {
                   6766:         if (ref($$changes{'activate'}) eq 'HASH') {
                   6767:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   6768:             my $numnew = scalar(@newitems);
                   6769:             for (my $i=0; $i<$numnew; $i++) {
                   6770:                 my $newkey = $newitems[$i];
                   6771:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  6772:                 if ($newkey =~ /^\d+:/) { 
                   6773:                     $newkey =~ s/^(\d+)/$newid/;
                   6774:                     $translation{$1} = $newid;
                   6775:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   6776:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   6777:                     $translation{$1} = $newid;
                   6778:                 }
1.749     raeburn  6779:                 $new_values{$file_name."\0".$newkey} = 
                   6780:                                           $$changes{'activate'}{$newitems[$i]};
                   6781:                 $new_control{$newkey} = $now;
                   6782:             }
                   6783:         }
                   6784:     }
                   6785:     my %todelete;
                   6786:     my %changed_items;
                   6787:     foreach my $action ('delete','update') {
                   6788:         if (exists($$changes{$action})) {
                   6789:             if (ref($$changes{$action}) eq 'HASH') {
                   6790:                 foreach my $key (keys(%{$$changes{$action}})) {
                   6791:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   6792:                     if ($action eq 'delete') { 
                   6793:                         $todelete{$itemnum} = 1;
                   6794:                     } else {
                   6795:                         $changed_items{$itemnum} = $key;
                   6796:                     }
                   6797:                 }
1.745     raeburn  6798:             }
                   6799:         }
1.749     raeburn  6800:     }
                   6801:     # get lock on access controls for file.
                   6802:     my $lockhash = {
                   6803:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   6804:                                                        ':'.$env{'user.domain'},
                   6805:                    }; 
                   6806:     my $tries = 0;
                   6807:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6808:    
                   6809:     while (($gotlock ne 'ok') && $tries <3) {
                   6810:         $tries ++;
                   6811:         sleep 1;
                   6812:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6813:     }
                   6814:     if ($gotlock eq 'ok') {
                   6815:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6816:         my ($tmp)=keys(%curr_permissions);
                   6817:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6818:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6819:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6820:             if (ref($curr_controls) eq 'HASH') {
                   6821:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6822:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6823:                     if (defined($todelete{$itemnum})) {
                   6824:                         push(@deletions,$file_name."\0".$control_item);
                   6825:                     } else {
                   6826:                         if (defined($changed_items{$itemnum})) {
                   6827:                             $new_control{$changed_items{$itemnum}} = $now;
                   6828:                             push(@deletions,$file_name."\0".$control_item);
                   6829:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6830:                         } else {
                   6831:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6832:                         }
                   6833:                     }
1.745     raeburn  6834:                 }
                   6835:             }
                   6836:         }
1.970     raeburn  6837:         my ($group);
                   6838:         if (&is_course($domain,$user)) {
                   6839:             ($group,my $file) = split(/\//,$file_name,2);
                   6840:         }
1.749     raeburn  6841:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6842:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6843:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6844:         #  remove lock
                   6845:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6846:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6847:         my $sqlresult =
1.970     raeburn  6848:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  6849:                                     $group);
1.749     raeburn  6850:     } else {
                   6851:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6852:     }
1.749     raeburn  6853:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6854: }
                   6855: 
1.827     raeburn  6856: sub make_public_indefinitely {
                   6857:     my ($requrl) = @_;
                   6858:     my $now = time;
                   6859:     my $action = 'activate';
                   6860:     my $aclnum = 0;
                   6861:     if (&is_portfolio_url($requrl)) {
                   6862:         my (undef,$udom,$unum,$file_name,$group) =
                   6863:             &parse_portfolio_url($requrl);
                   6864:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6865:         my %access_controls = &get_access_controls($current_perms,
                   6866:                                                    $group,$file_name);
                   6867:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6868:             my ($num,$scope,$end,$start) = 
                   6869:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6870:             if ($scope eq 'public') {
                   6871:                 if ($start <= $now && $end == 0) {
                   6872:                     $action = 'none';
                   6873:                 } else {
                   6874:                     $action = 'update';
                   6875:                     $aclnum = $num;
                   6876:                 }
                   6877:                 last;
                   6878:             }
                   6879:         }
                   6880:         if ($action eq 'none') {
                   6881:              return 'ok';
                   6882:         } else {
                   6883:             my %changes;
                   6884:             my $newend = 0;
                   6885:             my $newstart = $now;
                   6886:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6887:             $changes{$action}{$newkey} = {
                   6888:                 type => 'public',
                   6889:                 time => {
                   6890:                     start => $newstart,
                   6891:                     end   => $newend,
                   6892:                 },
                   6893:             };
                   6894:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6895:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6896:             return $outcome;
                   6897:         }
                   6898:     } else {
                   6899:         return 'invalid';
                   6900:     }
                   6901: }
                   6902: 
1.745     raeburn  6903: #------------------------------------------------------Get Marked as Read Only
                   6904: 
                   6905: sub get_marked_as_readonly {
                   6906:     my ($domain,$user,$what,$group) = @_;
                   6907:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6908:     my @readonly_files;
1.629     banghart 6909:     my $cmp1=$what;
                   6910:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6911:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6912:         if (defined($group)) {
                   6913:             if ($file_name !~ m-^\Q$group\E/-) {
                   6914:                 next;
                   6915:             }
                   6916:         }
1.561     banghart 6917:         if (ref($value) eq "ARRAY"){
                   6918:             foreach my $stored_what (@{$value}) {
1.629     banghart 6919:                 my $cmp2=$stored_what;
1.759     albertel 6920:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6921:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6922:                 }
1.629     banghart 6923:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6924:                     push(@readonly_files, $file_name);
1.745     raeburn  6925:                     last;
1.563     banghart 6926:                 } elsif (!defined($what)) {
                   6927:                     push(@readonly_files, $file_name);
1.745     raeburn  6928:                     last;
1.561     banghart 6929:                 }
                   6930:             }
1.745     raeburn  6931:         }
1.561     banghart 6932:     }
                   6933:     return @readonly_files;
                   6934: }
1.577     banghart 6935: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6936: 
1.577     banghart 6937: sub get_marked_as_readonly_hash {
1.745     raeburn  6938:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6939:     my %readonly_files;
1.745     raeburn  6940:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6941:         if (defined($group)) {
                   6942:             if ($file_name !~ m-^\Q$group\E/-) {
                   6943:                 next;
                   6944:             }
                   6945:         }
1.577     banghart 6946:         if (ref($value) eq "ARRAY"){
                   6947:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6948:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6949:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6950:                         if ($lock_descriptor eq 'graded') {
                   6951:                             $readonly_files{$file_name} = 'graded';
                   6952:                         } elsif ($lock_descriptor eq 'handback') {
                   6953:                             $readonly_files{$file_name} = 'handback';
                   6954:                         } else {
                   6955:                             if (!exists($readonly_files{$file_name})) {
                   6956:                                 $readonly_files{$file_name} = 'locked';
                   6957:                             }
                   6958:                         }
1.745     raeburn  6959:                     }
1.750     banghart 6960:                 } 
1.577     banghart 6961:             }
                   6962:         } 
                   6963:     }
                   6964:     return %readonly_files;
                   6965: }
1.559     banghart 6966: # ------------------------------------------------------------ Unmark as Read Only
                   6967: 
                   6968: sub unmark_as_readonly {
1.629     banghart 6969:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6970:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6971:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6972:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6973:     my $symb_crs = $what;
                   6974:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6975:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6976:     my ($tmp)=keys(%current_permissions);
                   6977:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6978:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6979:     foreach my $file (@readonly_files) {
1.759     albertel 6980: 	my $clean_file = &declutter_portfile($file);
                   6981: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6982: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6983:         my @new_locks;
                   6984:         my @del_keys;
                   6985:         if (ref($current_locks) eq "ARRAY"){
                   6986:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6987:                 my $compare=$locker;
1.749     raeburn  6988:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6989:                     $compare=join('',@{$locker});
1.746     raeburn  6990:                     if ($compare ne $symb_crs) {
                   6991:                         push(@new_locks, $locker);
                   6992:                     }
1.563     banghart 6993:                 }
                   6994:             }
1.650     albertel 6995:             if (scalar(@new_locks) > 0) {
1.563     banghart 6996:                 $current_permissions{$file} = \@new_locks;
                   6997:             } else {
                   6998:                 push(@del_keys, $file);
1.613     albertel 6999:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 7000:                 delete($current_permissions{$file});
1.563     banghart 7001:             }
                   7002:         }
1.561     banghart 7003:     }
1.613     albertel 7004:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7005:     return;
                   7006: }
1.512     banghart 7007: 
1.17      www      7008: # ------------------------------------------------------------ Directory lister
                   7009: 
                   7010: sub dirlist {
1.955     raeburn  7011:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      7012:     $uri=~s/^\///;
                   7013:     $uri=~s/\/$//;
1.253     stredwic 7014:     my ($udom, $uname);
1.955     raeburn  7015:     if ($getuserdir) {
1.253     stredwic 7016:         $udom = $userdomain;
                   7017:         $uname = $username;
1.955     raeburn  7018:     } else {
                   7019:         (undef,$udom,$uname)=split(/\//,$uri);
                   7020:         if(defined($userdomain)) {
                   7021:             $udom = $userdomain;
                   7022:         }
                   7023:         if(defined($username)) {
                   7024:             $uname = $username;
                   7025:         }
1.253     stredwic 7026:     }
1.955     raeburn  7027:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 7028: 
1.955     raeburn  7029:     $dirRoot = $perlvar{'lonDocRoot'};
                   7030:     if (defined($getpropath)) {
                   7031:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 7032:         $dirRoot =~ s/\/$//;
1.955     raeburn  7033:     } elsif (defined($getuserdir)) {
                   7034:         my $subdir=$uname.'__';
                   7035:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   7036:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   7037:                    ."/$udom/$subdir/$uname";
                   7038:     } elsif (defined($alternateRoot)) {
                   7039:         $dirRoot = $alternateRoot;
1.751     banghart 7040:     }
1.253     stredwic 7041: 
                   7042:     if($udom) {
                   7043:         if($uname) {
1.955     raeburn  7044:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  7045:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  7046:                               .':'.&escape($uname).':'.&escape($udom),
                   7047:                               &homeserver($uname,$udom));
                   7048:             if ($listing eq 'unknown_cmd') {
                   7049:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   7050:                                   &homeserver($uname,$udom));
                   7051:             } else {
                   7052:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7053:             }
1.605     matthew  7054:             if ($listing eq 'unknown_cmd') {
1.800     albertel 7055:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   7056: 				  &homeserver($uname,$udom));
1.605     matthew  7057:                 @listing_results = split(/:/,$listing);
                   7058:             } else {
                   7059:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7060:             }
                   7061:             return @listing_results;
1.955     raeburn  7062:         } elsif(!$alternateRoot) {
1.800     albertel 7063:             my %allusers;
1.841     albertel 7064: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  7065:  	    foreach my $tryserver (keys(%servers)) {
                   7066:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   7067:                                   &escape($udom),$tryserver);
                   7068:                 if ($listing eq 'unknown_cmd') {
                   7069: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7070: 				      $udom, $tryserver);
                   7071:                 } else {
                   7072:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7073:                 }
1.841     albertel 7074: 		if ($listing eq 'unknown_cmd') {
                   7075: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7076: 				      $udom, $tryserver);
                   7077: 		    @listing_results = split(/:/,$listing);
                   7078: 		} else {
                   7079: 		    @listing_results =
                   7080: 			map { &unescape($_); } split(/:/,$listing);
                   7081: 		}
                   7082: 		if ($listing_results[0] ne 'no_such_dir' && 
                   7083: 		    $listing_results[0] ne 'empty'       &&
                   7084: 		    $listing_results[0] ne 'con_lost') {
                   7085: 		    foreach my $line (@listing_results) {
                   7086: 			my ($entry) = split(/&/,$line,2);
                   7087: 			$allusers{$entry} = 1;
                   7088: 		    }
                   7089: 		}
1.253     stredwic 7090:             }
                   7091:             my $alluserstr='';
1.800     albertel 7092:             foreach my $user (sort(keys(%allusers))) {
                   7093:                 $alluserstr.=$user.'&user:';
1.253     stredwic 7094:             }
                   7095:             $alluserstr=~s/:$//;
                   7096:             return split(/:/,$alluserstr);
                   7097:         } else {
1.800     albertel 7098:             return ('missing user name');
1.253     stredwic 7099:         }
1.955     raeburn  7100:     } elsif(!defined($getpropath)) {
1.841     albertel 7101:         my @all_domains = sort(&all_domains());
1.955     raeburn  7102:         foreach my $domain (@all_domains) {
                   7103:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   7104:         }
                   7105:         return @all_domains;
                   7106:     } else {
1.800     albertel 7107:         return ('missing domain');
1.275     stredwic 7108:     }
                   7109: }
                   7110: 
                   7111: # --------------------------------------------- GetFileTimestamp
                   7112: # This function utilizes dirlist and returns the date stamp for
                   7113: # when it was last modified.  It will also return an error of -1
                   7114: # if an error occurs
                   7115: 
                   7116: sub GetFileTimestamp {
1.955     raeburn  7117:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 7118:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   7119:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  7120:     my ($fileStat) = 
                   7121:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   7122:                                  undef,$getuserdir);
1.275     stredwic 7123:     my @stats = split('&', $fileStat);
                   7124:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  7125:         # @stats contains first the filename, then the stat output
                   7126:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 7127:     } else {
                   7128:         return -1;
1.253     stredwic 7129:     }
1.26      www      7130: }
                   7131: 
1.712     albertel 7132: sub stat_file {
                   7133:     my ($uri) = @_;
1.787     albertel 7134:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 7135: 
1.955     raeburn  7136:     my ($udom,$uname,$file);
1.712     albertel 7137:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   7138: 	($udom,$uname,$file) =
1.811     albertel 7139: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 7140: 	$file = 'userfiles/'.$file;
                   7141:     }
                   7142:     if ($uri =~ m-^/res/-) {
                   7143: 	($udom,$uname) = 
1.807     albertel 7144: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 7145: 	$file = $uri;
                   7146:     }
                   7147: 
                   7148:     if (!$udom || !$uname || !$file) {
                   7149: 	# unable to handle the uri
                   7150: 	return ();
                   7151:     }
1.956     raeburn  7152:     my $getpropath;
                   7153:     if ($file =~ /^userfiles\//) {
                   7154:         $getpropath = 1;
                   7155:     }
1.955     raeburn  7156:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 7157:     my @stats = split('&', $result);
1.721     banghart 7158:     
1.712     albertel 7159:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   7160: 	shift(@stats); #filename is first
                   7161: 	return @stats;
                   7162:     }
                   7163:     return ();
                   7164: }
                   7165: 
1.26      www      7166: # -------------------------------------------------------- Value of a Condition
                   7167: 
1.713     albertel 7168: # gets the value of a specific preevaluated condition
                   7169: #    stored in the string  $env{user.state.<cid>}
                   7170: # or looks up a condition reference in the bighash and if if hasn't
                   7171: # already been evaluated recurses into docondval to get the value of
                   7172: # the condition, then memoizing it to 
                   7173: #   $env{user.state.<cid>.<condition>}
1.40      www      7174: sub directcondval {
                   7175:     my $number=shift;
1.620     albertel 7176:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 7177: 	&Apache::lonuserstate::evalstate();
                   7178:     }
1.713     albertel 7179:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   7180: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   7181:     } elsif ($number =~ /^_/) {
                   7182: 	my $sub_condition;
                   7183: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7184: 		&GDBM_READER(),0640)) {
                   7185: 	    $sub_condition=$bighash{'conditions'.$number};
                   7186: 	    untie(%bighash);
                   7187: 	}
                   7188: 	my $value = &docondval($sub_condition);
1.949     raeburn  7189: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 7190: 	return $value;
                   7191:     }
1.620     albertel 7192:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   7193:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      7194:     } else {
                   7195:        return 2;
                   7196:     }
                   7197: }
                   7198: 
1.713     albertel 7199: # get the collection of conditions for this resource
1.26      www      7200: sub condval {
                   7201:     my $condidx=shift;
1.54      www      7202:     my $allpathcond='';
1.713     albertel 7203:     foreach my $cond (split(/\|/,$condidx)) {
                   7204: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   7205: 	    $allpathcond.=
                   7206: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   7207: 	}
1.191     harris41 7208:     }
1.54      www      7209:     $allpathcond=~s/\|$//;
1.713     albertel 7210:     return &docondval($allpathcond);
                   7211: }
                   7212: 
                   7213: #evaluates an expression of conditions
                   7214: sub docondval {
                   7215:     my ($allpathcond) = @_;
                   7216:     my $result=0;
                   7217:     if ($env{'request.course.id'}
                   7218: 	&& defined($allpathcond)) {
                   7219: 	my $operand='|';
                   7220: 	my @stack;
                   7221: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   7222: 	    if ($chunk eq '(') {
                   7223: 		push @stack,($operand,$result);
                   7224: 	    } elsif ($chunk eq ')') {
                   7225: 		my $before=pop @stack;
                   7226: 		if (pop @stack eq '&') {
                   7227: 		    $result=$result>$before?$before:$result;
                   7228: 		} else {
                   7229: 		    $result=$result>$before?$result:$before;
                   7230: 		}
                   7231: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   7232: 		$operand=$chunk;
                   7233: 	    } else {
                   7234: 		my $new=directcondval($chunk);
                   7235: 		if ($operand eq '&') {
                   7236: 		    $result=$result>$new?$new:$result;
                   7237: 		} else {
                   7238: 		    $result=$result>$new?$result:$new;
                   7239: 		}
                   7240: 	    }
                   7241: 	}
1.26      www      7242:     }
                   7243:     return $result;
1.421     albertel 7244: }
                   7245: 
                   7246: # ---------------------------------------------------- Devalidate courseresdata
                   7247: 
                   7248: sub devalidatecourseresdata {
                   7249:     my ($coursenum,$coursedomain)=@_;
                   7250:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7251:     &devalidate_cache_new('courseres',$hashid);
1.28      www      7252: }
                   7253: 
1.763     www      7254: 
1.200     www      7255: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     7256: #
                   7257: #  Parameters:
                   7258: #      $coursenum    - Number of the course.
                   7259: #      $coursedomain - Domain at which the course was created.
                   7260: #  Returns:
                   7261: #     A hash of the course parameters along (I think) with timestamps
                   7262: #     and version info.
1.877     foxr     7263: 
1.624     albertel 7264: sub get_courseresdata {
                   7265:     my ($coursenum,$coursedomain)=@_;
1.200     www      7266:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   7267:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7268:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 7269:     my %dumpreply;
1.417     albertel 7270:     unless (defined($cached)) {
1.624     albertel 7271: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 7272: 	$result=\%dumpreply;
1.251     albertel 7273: 	my ($tmp) = keys(%dumpreply);
                   7274: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 7275: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 7276: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   7277: 	    return $tmp;
1.416     albertel 7278: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 7279: 	    $result=undef;
1.599     albertel 7280: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 7281: 	}
                   7282:     }
1.624     albertel 7283:     return $result;
                   7284: }
                   7285: 
1.633     albertel 7286: sub devalidateuserresdata {
                   7287:     my ($uname,$udom)=@_;
                   7288:     my $hashid="$udom:$uname";
                   7289:     &devalidate_cache_new('userres',$hashid);
                   7290: }
                   7291: 
1.624     albertel 7292: sub get_userresdata {
                   7293:     my ($uname,$udom)=@_;
                   7294:     #most student don\'t have any data set, check if there is some data
                   7295:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   7296: 
                   7297:     my $hashid="$udom:$uname";
                   7298:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   7299:     if (!defined($cached)) {
                   7300: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   7301: 	$result=\%resourcedata;
                   7302: 	&do_cache_new('userres',$hashid,$result,600);
                   7303:     }
                   7304:     my ($tmp)=keys(%$result);
                   7305:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   7306: 	return $result;
                   7307:     }
                   7308:     #error 2 occurs when the .db doesn't exist
                   7309:     if ($tmp!~/error: 2 /) {
1.672     albertel 7310: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 7311: 		 " Trying to get resource data for ".
                   7312: 		 $uname." at ".$udom.": ".
                   7313: 		 $tmp."</font>");
                   7314:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 7315: 	#&EXT_cache_set($udom,$uname);
                   7316: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 7317: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 7318:     }
                   7319:     return $tmp;
                   7320: }
1.879     foxr     7321: #----------------------------------------------- resdata - return resource data
                   7322: #  Purpose:
                   7323: #    Return resource data for either users or for a course.
                   7324: #  Parameters:
                   7325: #     $name      - Course/user name.
                   7326: #     $domain    - Name of the domain the user/course is registered on.
                   7327: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   7328: #     @which     - Array of names of resources desired.
                   7329: #  Returns:
                   7330: #     The value of the first reasource in @which that is found in the
                   7331: #     resource hash.
                   7332: #  Exceptional Conditions:
                   7333: #     If the $type passed in is not valid (not the string 'course' or 
                   7334: #     'user', an undefined  reference is returned.
                   7335: #     If none of the resources are found, an undef is returned
1.624     albertel 7336: sub resdata {
                   7337:     my ($name,$domain,$type,@which)=@_;
                   7338:     my $result;
                   7339:     if ($type eq 'course') {
                   7340: 	$result=&get_courseresdata($name,$domain);
                   7341:     } elsif ($type eq 'user') {
                   7342: 	$result=&get_userresdata($name,$domain);
                   7343:     }
                   7344:     if (!ref($result)) { return $result; }    
1.251     albertel 7345:     foreach my $item (@which) {
1.927     albertel 7346: 	if (defined($result->{$item->[0]})) {
                   7347: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 7348: 	}
1.250     albertel 7349:     }
1.291     albertel 7350:     return undef;
1.200     www      7351: }
                   7352: 
1.379     matthew  7353: #
                   7354: # EXT resource caching routines
                   7355: #
                   7356: 
                   7357: sub clear_EXT_cache_status {
1.383     albertel 7358:     &delenv('cache.EXT.');
1.379     matthew  7359: }
                   7360: 
                   7361: sub EXT_cache_status {
                   7362:     my ($target_domain,$target_user) = @_;
1.383     albertel 7363:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 7364:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  7365:         # We know already the user has no data
                   7366:         return 1;
                   7367:     } else {
                   7368:         return 0;
                   7369:     }
                   7370: }
                   7371: 
                   7372: sub EXT_cache_set {
                   7373:     my ($target_domain,$target_user) = @_;
1.383     albertel 7374:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  7375:     #&appenv({$cachename => time});
1.379     matthew  7376: }
                   7377: 
1.28      www      7378: # --------------------------------------------------------- Value of a Variable
1.58      www      7379: sub EXT {
1.715     albertel 7380: 
1.395     albertel 7381:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      7382:     unless ($varname) { return ''; }
1.218     albertel 7383:     #get real user name/domain, courseid and symb
                   7384:     my $courseid;
1.359     albertel 7385:     my $publicuser;
1.427     www      7386:     if ($symbparm) {
                   7387: 	$symbparm=&get_symb_from_alias($symbparm);
                   7388:     }
1.218     albertel 7389:     if (!($uname && $udom)) {
1.790     albertel 7390:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 7391:       if (!$symbparm) {	$symbparm=$cursymb; }
                   7392:     } else {
1.620     albertel 7393: 	$courseid=$env{'request.course.id'};
1.218     albertel 7394:     }
1.48      www      7395:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   7396:     my $rest;
1.320     albertel 7397:     if (defined($therest[0])) {
1.48      www      7398:        $rest=join('.',@therest);
                   7399:     } else {
                   7400:        $rest='';
                   7401:     }
1.320     albertel 7402: 
1.57      www      7403:     my $qualifierrest=$qualifier;
                   7404:     if ($rest) { $qualifierrest.='.'.$rest; }
                   7405:     my $spacequalifierrest=$space;
                   7406:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      7407:     if ($realm eq 'user') {
1.48      www      7408: # --------------------------------------------------------------- user.resource
                   7409: 	if ($space eq 'resource') {
1.651     albertel 7410: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   7411: 		  || defined($Apache::lonhomework::parsing_a_task))
                   7412: 		 &&
1.744     albertel 7413: 		 ($symbparm eq &symbread()) ) {	
                   7414: 		# if we are in the middle of processing the resource the
                   7415: 		# get the value we are planning on committing
                   7416:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   7417:                     return $Apache::lonhomework::results{$qualifierrest};
                   7418:                 } else {
                   7419:                     return $Apache::lonhomework::history{$qualifierrest};
                   7420:                 }
1.335     albertel 7421: 	    } else {
1.359     albertel 7422: 		my %restored;
1.620     albertel 7423: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 7424: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   7425: 		} else {
                   7426: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   7427: 		}
1.335     albertel 7428: 		return $restored{$qualifierrest};
                   7429: 	    }
1.48      www      7430: # ----------------------------------------------------------------- user.access
                   7431:         } elsif ($space eq 'access') {
1.218     albertel 7432: 	    # FIXME - not supporting calls for a specific user
1.48      www      7433:             return &allowed($qualifier,$rest);
                   7434: # ------------------------------------------ user.preferences, user.environment
                   7435:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 7436: 	    if (($uname eq $env{'user.name'}) &&
                   7437: 		($udom eq $env{'user.domain'})) {
                   7438: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 7439: 	    } else {
1.359     albertel 7440: 		my %returnhash;
                   7441: 		if (!$publicuser) {
                   7442: 		    %returnhash=&userenvironment($udom,$uname,
                   7443: 						 $qualifierrest);
                   7444: 		}
1.218     albertel 7445: 		return $returnhash{$qualifierrest};
                   7446: 	    }
1.48      www      7447: # ----------------------------------------------------------------- user.course
                   7448:         } elsif ($space eq 'course') {
1.218     albertel 7449: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 7450:             return $env{join('.',('request.course',$qualifier))};
1.48      www      7451: # ------------------------------------------------------------------- user.role
                   7452:         } elsif ($space eq 'role') {
1.218     albertel 7453: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 7454:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      7455:             if ($qualifier eq 'value') {
                   7456: 		return $role;
                   7457:             } elsif ($qualifier eq 'extent') {
                   7458:                 return $where;
                   7459:             }
                   7460: # ----------------------------------------------------------------- user.domain
                   7461:         } elsif ($space eq 'domain') {
1.218     albertel 7462:             return $udom;
1.48      www      7463: # ------------------------------------------------------------------- user.name
                   7464:         } elsif ($space eq 'name') {
1.218     albertel 7465:             return $uname;
1.48      www      7466: # ---------------------------------------------------- Any other user namespace
1.29      www      7467:         } else {
1.359     albertel 7468: 	    my %reply;
                   7469: 	    if (!$publicuser) {
                   7470: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   7471: 	    }
                   7472: 	    return $reply{$qualifierrest};
1.48      www      7473:         }
1.236     www      7474:     } elsif ($realm eq 'query') {
                   7475: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 7476:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   7477: 						[$spacequalifierrest]);
1.620     albertel 7478: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      7479:    } elsif ($realm eq 'request') {
1.48      www      7480: # ------------------------------------------------------------- request.browser
                   7481:         if ($space eq 'browser') {
1.430     www      7482: 	    if ($qualifier eq 'textremote') {
1.676     albertel 7483: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      7484: 		    return 1;
                   7485: 		} else {
                   7486: 		    return 0;
                   7487: 		}
                   7488: 	    } else {
1.620     albertel 7489: 		return $env{'browser.'.$qualifier};
1.430     www      7490: 	    }
1.57      www      7491: # ------------------------------------------------------------ request.filename
                   7492:         } else {
1.620     albertel 7493:             return $env{'request.'.$spacequalifierrest};
1.29      www      7494:         }
1.28      www      7495:     } elsif ($realm eq 'course') {
1.48      www      7496: # ---------------------------------------------------------- course.description
1.620     albertel 7497:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      7498:     } elsif ($realm eq 'resource') {
1.165     www      7499: 
1.620     albertel 7500: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 7501: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   7502: 	}
1.693     albertel 7503: 
                   7504: 	if ($space eq 'title') {
                   7505: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   7506: 	    return &gettitle($symbparm);
                   7507: 	}
                   7508: 	
                   7509: 	if ($space eq 'map') {
                   7510: 	    my ($map) = &decode_symb($symbparm);
                   7511: 	    return &symbread($map);
                   7512: 	}
1.905     albertel 7513: 	if ($space eq 'filename') {
                   7514: 	    if ($symbparm) {
                   7515: 		return &clutter((&decode_symb($symbparm))[2]);
                   7516: 	    }
                   7517: 	    return &hreflocation('',$env{'request.filename'});
                   7518: 	}
1.693     albertel 7519: 
                   7520: 	my ($section, $group, @groups);
1.593     albertel 7521: 	my ($courselevelm,$courselevel);
1.539     albertel 7522: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7523: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      7524: 
1.218     albertel 7525: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      7526: 
1.60      www      7527: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 7528: 	    my $symbp=$symbparm;
1.735     albertel 7529: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 7530: 
                   7531: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   7532: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   7533: 
1.620     albertel 7534: 	    if (($env{'user.name'} eq $uname) &&
                   7535: 		($env{'user.domain'} eq $udom)) {
                   7536: 		$section=$env{'request.course.sec'};
1.733     raeburn  7537:                 @groups = split(/:/,$env{'request.course.groups'});  
                   7538:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 7539: 	    } else {
1.539     albertel 7540: 		if (! defined($usection)) {
1.551     albertel 7541: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 7542: 		} else {
                   7543: 		    $section = $usection;
                   7544: 		}
1.733     raeburn  7545:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 7546: 	    }
                   7547: 
                   7548: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   7549: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   7550: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   7551: 
1.593     albertel 7552: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 7553: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 7554: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      7555: 
1.60      www      7556: # ----------------------------------------------------------- first, check user
1.624     albertel 7557: 
                   7558: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 7559: 				       ([$courselevelr,'resource'],
                   7560: 					[$courselevelm,'map'     ],
                   7561: 					[$courselevel, 'course'  ]));
1.931     albertel 7562: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      7563: 
1.594     albertel 7564: # ------------------------------------------------ second, check some of course
1.684     raeburn  7565:             my $coursereply;
1.691     raeburn  7566:             if (@groups > 0) {
                   7567:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   7568:                                        $mapparm,$spacequalifierrest);
1.927     albertel 7569:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  7570:             }
1.96      www      7571: 
1.684     raeburn  7572: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 7573: 				  $env{'course.'.$courseid.'.domain'},
                   7574: 				  'course',
                   7575: 				  ([$seclevelr,   'resource'],
                   7576: 				   [$seclevelm,   'map'     ],
                   7577: 				   [$seclevel,    'course'  ],
                   7578: 				   [$courselevelr,'resource']));
                   7579: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      7580: 
1.60      www      7581: # ------------------------------------------------------ third, check map parms
1.218     albertel 7582: 	    my %parmhash=();
                   7583: 	    my $thisparm='';
                   7584: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 7585: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 7586: 		    &GDBM_READER(),0640)) {
1.218     albertel 7587: 		$thisparm=$parmhash{$symbparm};
                   7588: 		untie(%parmhash);
                   7589: 	    }
1.927     albertel 7590: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 7591: 	}
1.594     albertel 7592: # ------------------------------------------ fourth, look in resource metadata
1.71      www      7593: 
1.218     albertel 7594: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 7595: 	my $filename;
                   7596: 	if (!$symbparm) { $symbparm=&symbread(); }
                   7597: 	if ($symbparm) {
1.409     www      7598: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 7599: 	} else {
1.620     albertel 7600: 	    $filename=$env{'request.filename'};
1.282     albertel 7601: 	}
                   7602: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 7603: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 7604: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 7605: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      7606: 
1.927     albertel 7607: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 7608: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7609: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 7610: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   7611: 				     $env{'course.'.$courseid.'.domain'},
                   7612: 				     'course',
1.927     albertel 7613: 				     ([$courselevelm,'map'   ],
                   7614: 				      [$courselevel, 'course']));
                   7615: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 7616: 	}
1.145     www      7617: # ------------------------------------------------------------------ Cascade up
1.218     albertel 7618: 	unless ($space eq '0') {
1.336     albertel 7619: 	    my @parts=split(/_/,$space);
                   7620: 	    my $id=pop(@parts);
                   7621: 	    my $part=join('_',@parts);
                   7622: 	    if ($part eq '') { $part='0'; }
1.927     albertel 7623: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 7624: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  7625: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 7626: 	}
1.395     albertel 7627: 	if ($recurse) { return undef; }
                   7628: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 7629: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      7630: # ---------------------------------------------------- Any other user namespace
                   7631:     } elsif ($realm eq 'environment') {
                   7632: # ----------------------------------------------------------------- environment
1.620     albertel 7633: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   7634: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 7635: 	} else {
1.770     albertel 7636: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   7637: 		return '';
                   7638: 	    }
1.219     albertel 7639: 	    my %returnhash=&userenvironment($udom,$uname,
                   7640: 					    $spacequalifierrest);
                   7641: 	    return $returnhash{$spacequalifierrest};
                   7642: 	}
1.28      www      7643:     } elsif ($realm eq 'system') {
1.48      www      7644: # ----------------------------------------------------------------- system.time
                   7645: 	if ($space eq 'time') {
                   7646: 	    return time;
                   7647:         }
1.696     albertel 7648:     } elsif ($realm eq 'server') {
                   7649: # ----------------------------------------------------------------- system.time
                   7650: 	if ($space eq 'name') {
                   7651: 	    return $ENV{'SERVER_NAME'};
                   7652:         }
1.28      www      7653:     }
1.48      www      7654:     return '';
1.61      www      7655: }
                   7656: 
1.927     albertel 7657: sub get_reply {
                   7658:     my ($reply_value) = @_;
1.940     raeburn  7659:     if (ref($reply_value) eq 'ARRAY') {
                   7660:         if (wantarray) {
                   7661: 	    return @$reply_value;
                   7662:         }
                   7663:         return $reply_value->[0];
                   7664:     } else {
                   7665:         return $reply_value;
1.927     albertel 7666:     }
                   7667: }
                   7668: 
1.691     raeburn  7669: sub check_group_parms {
                   7670:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   7671:     my @groupitems = ();
                   7672:     my $resultitem;
1.927     albertel 7673:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  7674:     foreach my $group (@{$groups}) {
                   7675:         foreach my $level (@levels) {
1.927     albertel 7676:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   7677:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  7678:         }
                   7679:     }
                   7680:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   7681:                             $env{'course.'.$courseid.'.domain'},
                   7682:                                      'course',@groupitems);
                   7683:     return $coursereply;
                   7684: }
                   7685: 
                   7686: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  7687:     my ($courseid,@groups) = @_;
                   7688:     @groups = sort(@groups);
1.691     raeburn  7689:     return @groups;
                   7690: }
                   7691: 
1.395     albertel 7692: sub packages_tab_default {
                   7693:     my ($uri,$varname)=@_;
                   7694:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 7695: 
                   7696:     my (@extension,@specifics,$do_default);
                   7697:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 7698: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 7699: 	if ($pack_type eq 'default') {
                   7700: 	    $do_default=1;
                   7701: 	} elsif ($pack_type eq 'extension') {
                   7702: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 7703: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 7704: 	    # only look at packages defaults for packages that this id is
1.738     albertel 7705: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   7706: 	}
                   7707:     }
                   7708:     # first look for a package that matches the requested part id
                   7709:     foreach my $package (@specifics) {
                   7710: 	my (undef,$pack_type,$pack_part)=@{$package};
                   7711: 	next if ($pack_part ne $part);
                   7712: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7713: 	    return $packagetab{"$pack_type&$name&default"};
                   7714: 	}
                   7715:     }
                   7716:     # look for any possible matching non extension_ package
                   7717:     foreach my $package (@specifics) {
                   7718: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 7719: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7720: 	    return $packagetab{"$pack_type&$name&default"};
                   7721: 	}
1.585     albertel 7722: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 7723: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   7724: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 7725: 	}
                   7726:     }
1.738     albertel 7727:     # look for any posible extension_ match
                   7728:     foreach my $package (@extension) {
                   7729: 	my ($package,$pack_type)=@{$package};
                   7730: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7731: 	    return $packagetab{"$pack_type&$name&default"};
                   7732: 	}
                   7733: 	if (defined($packagetab{$package."&$name&default"})) {
                   7734: 	    return $packagetab{$package."&$name&default"};
                   7735: 	}
                   7736:     }
                   7737:     # look for a global default setting
                   7738:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   7739: 	return $packagetab{"default&$name&default"};
                   7740:     }
1.395     albertel 7741:     return undef;
                   7742: }
                   7743: 
1.334     albertel 7744: sub add_prefix_and_part {
                   7745:     my ($prefix,$part)=@_;
                   7746:     my $keyroot;
                   7747:     if (defined($prefix) && $prefix !~ /^__/) {
                   7748: 	# prefix that has a part already
                   7749: 	$keyroot=$prefix;
                   7750:     } elsif (defined($prefix)) {
                   7751: 	# prefix that is missing a part
                   7752: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   7753:     } else {
                   7754: 	# no prefix at all
                   7755: 	if (defined($part)) { $keyroot='_'.$part; }
                   7756:     }
                   7757:     return $keyroot;
                   7758: }
                   7759: 
1.71      www      7760: # ---------------------------------------------------------------- Get metadata
                   7761: 
1.599     albertel 7762: my %metaentry;
1.71      www      7763: sub metadata {
1.176     www      7764:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      7765:     $uri=&declutter($uri);
1.288     albertel 7766:     # if it is a non metadata possible uri return quickly
1.529     albertel 7767:     if (($uri eq '') || 
                   7768: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 7769: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 7770:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   7771: 	return undef;
                   7772:     }
                   7773:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   7774: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 7775: 	return undef;
1.288     albertel 7776:     }
1.73      www      7777:     my $filename=$uri;
                   7778:     $uri=~s/\.meta$//;
1.172     www      7779: #
                   7780: # Is the metadata already cached?
1.177     www      7781: # Look at timestamp of caching
1.172     www      7782: # Everything is cached by the main uri, libraries are never directly cached
                   7783: #
1.428     albertel 7784:     if (!defined($liburi)) {
1.599     albertel 7785: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 7786: 	if (defined($cached)) { return $result->{':'.$what}; }
                   7787:     }
                   7788:     {
1.172     www      7789: #
                   7790: # Is this a recursive call for a library?
                   7791: #
1.599     albertel 7792: #	if (! exists($metacache{$uri})) {
                   7793: #	    $metacache{$uri}={};
                   7794: #	}
1.924     albertel 7795: 	my $cachetime = 60*60;
1.171     www      7796:         if ($liburi) {
                   7797: 	    $liburi=&declutter($liburi);
                   7798:             $filename=$liburi;
1.401     bowersj2 7799:         } else {
1.599     albertel 7800: 	    &devalidate_cache_new('meta',$uri);
                   7801: 	    undef(%metaentry);
1.401     bowersj2 7802: 	}
1.140     www      7803:         my %metathesekeys=();
1.73      www      7804:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 7805: 	my $metastring;
1.924     albertel 7806: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 7807: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 7808: 	    $metastring = 
1.929     albertel 7809: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 7810: 					  ('grade_target' => 'meta'));
                   7811: 	    $cachetime = 1; # only want this cached in the child not long term
                   7812: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 7813: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 7814: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 7815: 	    $metastring=&getfile($file);
1.489     albertel 7816: 	}
1.208     albertel 7817:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      7818:         my $token;
1.140     www      7819:         undef %metathesekeys;
1.71      www      7820:         while ($token=$parser->get_token) {
1.339     albertel 7821: 	    if ($token->[0] eq 'S') {
                   7822: 		if (defined($token->[2]->{'package'})) {
1.172     www      7823: #
                   7824: # This is a package - get package info
                   7825: #
1.339     albertel 7826: 		    my $package=$token->[2]->{'package'};
                   7827: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7828: 		    if (defined($token->[2]->{'id'})) { 
                   7829: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7830: 		    }
1.599     albertel 7831: 		    if ($metaentry{':packages'}) {
                   7832: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7833: 		    } else {
1.599     albertel 7834: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7835: 		    }
1.736     albertel 7836: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7837: 			my $part=$keyroot;
                   7838: 			$part=~s/^\_//;
1.736     albertel 7839: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7840: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7841: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7842: 			    # ignore package.tab specified default values
                   7843:                             # here &package_tab_default() will fetch those
                   7844: 			    if ($subp eq 'default') { next; }
1.736     albertel 7845: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7846: 			    my $unikey;
                   7847: 			    if ($pack =~ /_0$/) {
                   7848: 				$unikey='parameter_0_'.$name;
                   7849: 				$part=0;
                   7850: 			    } else {
                   7851: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7852: 			    }
1.339     albertel 7853: 			    if ($subp eq 'display') {
                   7854: 				$value.=' [Part: '.$part.']';
                   7855: 			    }
1.599     albertel 7856: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7857: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7858: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7859: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7860: 			    }
1.599     albertel 7861: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7862: 				$metaentry{':'.$unikey}=
                   7863: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7864: 			    }
1.339     albertel 7865: 			}
                   7866: 		    }
                   7867: 		} else {
1.172     www      7868: #
                   7869: # This is not a package - some other kind of start tag
1.339     albertel 7870: #
                   7871: 		    my $entry=$token->[1];
                   7872: 		    my $unikey;
                   7873: 		    if ($entry eq 'import') {
                   7874: 			$unikey='';
                   7875: 		    } else {
                   7876: 			$unikey=$entry;
                   7877: 		    }
                   7878: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7879: 
                   7880: 		    if (defined($token->[2]->{'id'})) { 
                   7881: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7882: 		    }
1.175     www      7883: 
1.339     albertel 7884: 		    if ($entry eq 'import') {
1.175     www      7885: #
                   7886: # Importing a library here
1.339     albertel 7887: #
                   7888: 			if ($depthcount<20) {
                   7889: 			    my $location=$parser->get_text('/import');
                   7890: 			    my $dir=$filename;
                   7891: 			    $dir=~s|[^/]*$||;
                   7892: 			    $location=&filelocation($dir,$location);
1.736     albertel 7893: 			    my $metadata = 
                   7894: 				&metadata($uri,'keys', $location,$unikey,
                   7895: 					  $depthcount+1);
                   7896: 			    foreach my $meta (split(',',$metadata)) {
                   7897: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7898: 				$metathesekeys{$meta}=1;
1.339     albertel 7899: 			    }
                   7900: 			}
                   7901: 		    } else { 
                   7902: 			
                   7903: 			if (defined($token->[2]->{'name'})) { 
                   7904: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7905: 			}
                   7906: 			$metathesekeys{$unikey}=1;
1.736     albertel 7907: 			foreach my $param (@{$token->[3]}) {
                   7908: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7909: 				$token->[2]->{$param};
1.339     albertel 7910: 			}
                   7911: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7912: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7913: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7914: 		 # only ws inside the tag, and not in default, so use default
                   7915: 		 # as value
1.599     albertel 7916: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7917: 			} elsif ( $internaltext =~ /\S/ ) {
                   7918: 		  # something interesting inside the tag
                   7919: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7920: 			} else {
1.908     albertel 7921: 		  # no interesting values, don't set a default
1.339     albertel 7922: 			}
1.172     www      7923: # end of not-a-package not-a-library import
1.339     albertel 7924: 		    }
1.172     www      7925: # end of not-a-package start tag
1.339     albertel 7926: 		}
1.172     www      7927: # the next is the end of "start tag"
1.339     albertel 7928: 	    }
                   7929: 	}
1.483     albertel 7930: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7931: 	$extension = lc($extension);
                   7932: 	if ($extension eq 'htm') { $extension='html'; }
                   7933: 
1.737     albertel 7934: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7935: 	    #no specific packages #how's our extension
                   7936: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7937: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7938: 					 \%metathesekeys);
                   7939: 	}
1.883     albertel 7940: 
                   7941: 	if (!exists($metaentry{':packages'})
                   7942: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7943: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7944: 		#no specific packages well let's get default then
                   7945: 		if ($key!~/^default&/) { next; }
1.488     albertel 7946: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7947: 					     \%metathesekeys);
                   7948: 	    }
                   7949: 	}
1.338     www      7950: # are there custom rights to evaluate
1.599     albertel 7951: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7952: 
1.338     www      7953:     #
                   7954:     # Importing a rights file here
1.339     albertel 7955:     #
                   7956: 	    unless ($depthcount) {
1.599     albertel 7957: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7958: 		my $dir=$filename;
                   7959: 		$dir=~s|[^/]*$||;
                   7960: 		$location=&filelocation($dir,$location);
1.736     albertel 7961: 		my $rights_metadata =
                   7962: 		    &metadata($uri,'keys',$location,'_rights',
                   7963: 			      $depthcount+1);
                   7964: 		foreach my $rights (split(',',$rights_metadata)) {
                   7965: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7966: 		    $metathesekeys{$rights}=1;
1.339     albertel 7967: 		}
                   7968: 	    }
                   7969: 	}
1.737     albertel 7970: 	# uniqifiy package listing
                   7971: 	my %seen;
                   7972: 	my @uniq_packages =
                   7973: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7974: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7975: 
                   7976: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7977: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7978: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7979: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7980: # this is the end of "was not already recently cached
1.71      www      7981:     }
1.599     albertel 7982:     return $metaentry{':'.$what};
1.261     albertel 7983: }
                   7984: 
1.488     albertel 7985: sub metadata_create_package_def {
1.483     albertel 7986:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7987:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7988:     if ($subp eq 'default') { next; }
                   7989:     
1.599     albertel 7990:     if (defined($metaentry{':packages'})) {
                   7991: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7992:     } else {
1.599     albertel 7993: 	$metaentry{':packages'}=$package;
1.483     albertel 7994:     }
                   7995:     my $value=$packagetab{$key};
                   7996:     my $unikey;
                   7997:     $unikey='parameter_0_'.$name;
1.599     albertel 7998:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7999:     $$metathesekeys{$unikey}=1;
1.599     albertel 8000:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8001: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 8002:     }
1.599     albertel 8003:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   8004: 	$metaentry{':'.$unikey}=
                   8005: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 8006:     }
                   8007: }
                   8008: 
1.261     albertel 8009: sub metadata_generate_part0 {
                   8010:     my ($metadata,$metacache,$uri) = @_;
                   8011:     my %allnames;
1.737     albertel 8012:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 8013: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 8014: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   8015: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 8016: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 8017: 	    $allnames{$name}=$part;
                   8018: 	  }
                   8019: 	}
                   8020:     }
                   8021:     foreach my $name (keys(%allnames)) {
                   8022:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 8023:       my $key=":parameter_0_$name";
1.261     albertel 8024:       $$metacache{"$key.part"}='0';
                   8025:       $$metacache{"$key.name"}=$name;
1.428     albertel 8026:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 8027: 					   $allnames{$name}.'_'.$name.
                   8028: 					   '.type'};
1.428     albertel 8029:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 8030: 			     '.display'};
1.644     www      8031:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 8032:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 8033:       $$metacache{"$key.display"}=$olddis;
                   8034:     }
1.71      www      8035: }
                   8036: 
1.764     albertel 8037: # ------------------------------------------------------ Devalidate title cache
                   8038: 
                   8039: sub devalidate_title_cache {
                   8040:     my ($url)=@_;
                   8041:     if (!$env{'request.course.id'}) { return; }
                   8042:     my $symb=&symbread($url);
                   8043:     if (!$symb) { return; }
                   8044:     my $key=$env{'request.course.id'}."\0".$symb;
                   8045:     &devalidate_cache_new('title',$key);
                   8046: }
                   8047: 
1.1014    droeschl 8048: # ------------------------------------------------- Get the title of a course
                   8049: 
                   8050: sub current_course_title {
                   8051:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   8052: }
1.301     www      8053: # ------------------------------------------------- Get the title of a resource
                   8054: 
                   8055: sub gettitle {
                   8056:     my $urlsymb=shift;
                   8057:     my $symb=&symbread($urlsymb);
1.534     albertel 8058:     if ($symb) {
1.620     albertel 8059: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 8060: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 8061: 	if (defined($cached)) { 
                   8062: 	    return $result;
                   8063: 	}
1.534     albertel 8064: 	my ($map,$resid,$url)=&decode_symb($symb);
                   8065: 	my $title='';
1.907     albertel 8066: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   8067: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   8068: 	} else {
                   8069: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8070: 		    &GDBM_READER(),0640)) {
                   8071: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   8072: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   8073: 		untie(%bighash);
                   8074: 	    }
1.534     albertel 8075: 	}
                   8076: 	$title=~s/\&colon\;/\:/gs;
                   8077: 	if ($title) {
1.599     albertel 8078: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 8079: 	}
                   8080: 	$urlsymb=$url;
                   8081:     }
                   8082:     my $title=&metadata($urlsymb,'title');
                   8083:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   8084:     return $title;
1.301     www      8085: }
1.613     albertel 8086: 
1.614     albertel 8087: sub get_slot {
                   8088:     my ($which,$cnum,$cdom)=@_;
                   8089:     if (!$cnum || !$cdom) {
1.790     albertel 8090: 	(undef,my $courseid)=&whichuser();
1.620     albertel 8091: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   8092: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 8093:     }
1.703     albertel 8094:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   8095:     my %slotinfo;
                   8096:     if (exists($remembered{$key})) {
                   8097: 	$slotinfo{$which} = $remembered{$key};
                   8098:     } else {
                   8099: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   8100: 	&Apache::lonhomework::showhash(%slotinfo);
                   8101: 	my ($tmp)=keys(%slotinfo);
                   8102: 	if ($tmp=~/^error:/) { return (); }
                   8103: 	$remembered{$key} = $slotinfo{$which};
                   8104:     }
1.616     albertel 8105:     if (ref($slotinfo{$which}) eq 'HASH') {
                   8106: 	return %{$slotinfo{$which}};
                   8107:     }
                   8108:     return $slotinfo{$which};
1.614     albertel 8109: }
1.31      www      8110: # ------------------------------------------------- Update symbolic store links
                   8111: 
                   8112: sub symblist {
                   8113:     my ($mapname,%newhash)=@_;
1.438     www      8114:     $mapname=&deversion(&declutter($mapname));
1.31      www      8115:     my %hash;
1.620     albertel 8116:     if (($env{'request.course.fn'}) && (%newhash)) {
                   8117:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8118:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  8119: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 8120: 		next if ($url eq 'last_known'
                   8121: 			 && $env{'form.no_update_last_known'});
                   8122: 		$hash{declutter($url)}=&encode_symb($mapname,
                   8123: 						    $newhash{$url}->[1],
                   8124: 						    $newhash{$url}->[0]);
1.191     harris41 8125:             }
1.31      www      8126:             if (untie(%hash)) {
                   8127: 		return 'ok';
                   8128:             }
                   8129:         }
                   8130:     }
                   8131:     return 'error';
1.212     www      8132: }
                   8133: 
                   8134: # --------------------------------------------------------------- Verify a symb
                   8135: 
                   8136: sub symbverify {
1.510     www      8137:     my ($symb,$thisurl)=@_;
                   8138:     my $thisfn=$thisurl;
1.439     www      8139:     $thisfn=&declutter($thisfn);
1.215     www      8140: # direct jump to resource in page or to a sequence - will construct own symbs
                   8141:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   8142: # check URL part
1.409     www      8143:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      8144: 
1.431     www      8145:     unless ($url eq $thisfn) { return 0; }
1.213     www      8146: 
1.216     www      8147:     $symb=&symbclean($symb);
1.510     www      8148:     $thisurl=&deversion($thisurl);
1.439     www      8149:     $thisfn=&deversion($thisfn);
1.213     www      8150: 
                   8151:     my %bighash;
                   8152:     my $okay=0;
1.431     www      8153: 
1.620     albertel 8154:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8155:                             &GDBM_READER(),0640)) {
1.510     www      8156:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      8157:         unless ($ids) { 
1.510     www      8158:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      8159:         }
                   8160:         if ($ids) {
                   8161: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 8162: 	    foreach my $id (split(/\,/,$ids)) {
                   8163: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      8164:                if (
                   8165:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   8166:    eq $symb) { 
1.620     albertel 8167: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 8168: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 8169: 		       $okay=1; 
                   8170: 		   }
                   8171: 	       }
1.216     www      8172: 	   }
                   8173:         }
1.213     www      8174: 	untie(%bighash);
                   8175:     }
                   8176:     return $okay;
1.31      www      8177: }
                   8178: 
1.210     www      8179: # --------------------------------------------------------------- Clean-up symb
                   8180: 
                   8181: sub symbclean {
                   8182:     my $symb=shift;
1.568     albertel 8183:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      8184: # remove version from map
                   8185:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      8186: 
1.210     www      8187: # remove version from URL
                   8188:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      8189: 
1.507     www      8190: # remove wrapper
                   8191: 
1.510     www      8192:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 8193:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      8194:     return $symb;
1.409     www      8195: }
                   8196: 
                   8197: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 8198: 
                   8199: sub encode_symb {
                   8200:     my ($map,$resid,$url)=@_;
                   8201:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   8202: }
1.409     www      8203: 
                   8204: sub decode_symb {
1.568     albertel 8205:     my $symb=shift;
                   8206:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   8207:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      8208:     return (&fixversion($map),$resid,&fixversion($url));
                   8209: }
                   8210: 
                   8211: sub fixversion {
                   8212:     my $fn=shift;
1.609     banghart 8213:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      8214:     my %bighash;
                   8215:     my $uri=&clutter($fn);
1.620     albertel 8216:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      8217: # is this cached?
1.599     albertel 8218:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      8219:     if (defined($cached)) { return $result; }
                   8220: # unfortunately not cached, or expired
1.620     albertel 8221:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      8222: 	    &GDBM_READER(),0640)) {
                   8223:  	if ($bighash{'version_'.$uri}) {
                   8224:  	    my $version=$bighash{'version_'.$uri};
1.444     www      8225:  	    unless (($version eq 'mostrecent') || 
                   8226: 		    ($version==&getversion($uri))) {
1.440     www      8227:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   8228:  	    }
                   8229:  	}
                   8230:  	untie %bighash;
1.413     www      8231:     }
1.599     albertel 8232:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      8233: }
                   8234: 
                   8235: sub deversion {
                   8236:     my $url=shift;
                   8237:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   8238:     return $url;
1.210     www      8239: }
                   8240: 
1.31      www      8241: # ------------------------------------------------------ Return symb list entry
                   8242: 
                   8243: sub symbread {
1.249     www      8244:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 8245:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 8246:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      8247: # no filename provided? try from environment
1.44      www      8248:     unless ($thisfn) {
1.620     albertel 8249:         if ($env{'request.symb'}) {
                   8250: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 8251: 	}
1.620     albertel 8252: 	$thisfn=$env{'request.filename'};
1.44      www      8253:     }
1.569     albertel 8254:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      8255: # is that filename actually a symb? Verify, clean, and return
                   8256:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 8257: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 8258: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 8259: 	}
1.242     www      8260:     }
1.44      www      8261:     $thisfn=declutter($thisfn);
1.31      www      8262:     my %hash;
1.37      www      8263:     my %bighash;
                   8264:     my $syval='';
1.620     albertel 8265:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  8266:         my $targetfn = $thisfn;
1.609     banghart 8267:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  8268:             $targetfn = 'adm/wrapper/'.$thisfn;
                   8269:         }
1.687     albertel 8270: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   8271: 	    $targetfn=$1;
                   8272: 	}
1.620     albertel 8273:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8274:                       &GDBM_READER(),0640)) {
1.481     raeburn  8275: 	    $syval=$hash{$targetfn};
1.37      www      8276:             untie(%hash);
                   8277:         }
                   8278: # ---------------------------------------------------------- There was an entry
                   8279:         if ($syval) {
1.601     albertel 8280: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 8281: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  8282: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 8283: 		    #return $env{$cache_str}='';
1.601     albertel 8284: 		#}    
                   8285: 		#$syval.=$1;
                   8286: 	    #}
1.37      www      8287:         } else {
                   8288: # ------------------------------------------------------- Was not in symb table
1.620     albertel 8289:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8290:                             &GDBM_READER(),0640)) {
1.37      www      8291: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      8292:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      8293:               unless ($ids) { 
                   8294:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      8295:               }
                   8296:               unless ($ids) {
                   8297: # alias?
                   8298: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      8299:               }
1.37      www      8300:               if ($ids) {
                   8301: # ------------------------------------------------------------------- Has ID(s)
                   8302:                  my @possibilities=split(/\,/,$ids);
1.39      www      8303:                  if ($#possibilities==0) {
                   8304: # ----------------------------------------------- There is only one possibility
1.37      www      8305: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 8306: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   8307: 						    $resid,$thisfn);
1.249     www      8308:                  } elsif (!$donotrecurse) {
1.39      www      8309: # ------------------------------------------ There is more than one possibility
                   8310:                      my $realpossible=0;
1.800     albertel 8311:                      foreach my $id (@possibilities) {
                   8312: 			 my $file=$bighash{'src_'.$id};
1.39      www      8313:                          if (&allowed('bre',$file)) {
1.800     albertel 8314:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      8315:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   8316: 				$realpossible++;
1.626     albertel 8317:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   8318: 						    $resid,$thisfn);
1.39      www      8319:                             }
                   8320: 			 }
1.191     harris41 8321:                      }
1.39      www      8322: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      8323:                  } else {
                   8324:                      $syval='';
1.37      www      8325:                  }
                   8326: 	      }
                   8327:               untie(%bighash)
1.481     raeburn  8328:            }
1.31      www      8329:         }
1.62      www      8330:         if ($syval) {
1.620     albertel 8331: 	    return $env{$cache_str}=$syval;
1.62      www      8332:         }
1.31      www      8333:     }
1.949     raeburn  8334:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 8335:     return $env{$cache_str}='';
1.31      www      8336: }
                   8337: 
                   8338: # ---------------------------------------------------------- Return random seed
                   8339: 
1.32      www      8340: sub numval {
                   8341:     my $txt=shift;
                   8342:     $txt=~tr/A-J/0-9/;
                   8343:     $txt=~tr/a-j/0-9/;
                   8344:     $txt=~tr/K-T/0-9/;
                   8345:     $txt=~tr/k-t/0-9/;
                   8346:     $txt=~tr/U-Z/0-5/;
                   8347:     $txt=~tr/u-z/0-5/;
                   8348:     $txt=~s/\D//g;
1.564     albertel 8349:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      8350:     return int($txt);
1.368     albertel 8351: }
                   8352: 
1.484     albertel 8353: sub numval2 {
                   8354:     my $txt=shift;
                   8355:     $txt=~tr/A-J/0-9/;
                   8356:     $txt=~tr/a-j/0-9/;
                   8357:     $txt=~tr/K-T/0-9/;
                   8358:     $txt=~tr/k-t/0-9/;
                   8359:     $txt=~tr/U-Z/0-5/;
                   8360:     $txt=~tr/u-z/0-5/;
                   8361:     $txt=~s/\D//g;
                   8362:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   8363:     my $total;
                   8364:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 8365:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 8366:     return int($total);
                   8367: }
                   8368: 
1.575     albertel 8369: sub numval3 {
                   8370:     use integer;
                   8371:     my $txt=shift;
                   8372:     $txt=~tr/A-J/0-9/;
                   8373:     $txt=~tr/a-j/0-9/;
                   8374:     $txt=~tr/K-T/0-9/;
                   8375:     $txt=~tr/k-t/0-9/;
                   8376:     $txt=~tr/U-Z/0-5/;
                   8377:     $txt=~tr/u-z/0-5/;
                   8378:     $txt=~s/\D//g;
                   8379:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   8380:     my $total;
                   8381:     foreach my $val (@txts) { $total+=$val; }
                   8382:     if ($_64bit) { $total=(($total<<32)>>32); }
                   8383:     return $total;
                   8384: }
                   8385: 
1.675     albertel 8386: sub digest {
                   8387:     my ($data)=@_;
                   8388:     my $digest=&Digest::MD5::md5($data);
                   8389:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   8390:     my ($e,$f);
                   8391:     {
                   8392:         use integer;
                   8393:         $e=($a+$b);
                   8394:         $f=($c+$d);
                   8395:         if ($_64bit) {
                   8396:             $e=(($e<<32)>>32);
                   8397:             $f=(($f<<32)>>32);
                   8398:         }
                   8399:     }
                   8400:     if (wantarray) {
                   8401: 	return ($e,$f);
                   8402:     } else {
                   8403: 	my $g;
                   8404: 	{
                   8405: 	    use integer;
                   8406: 	    $g=($e+$f);
                   8407: 	    if ($_64bit) {
                   8408: 		$g=(($g<<32)>>32);
                   8409: 	    }
                   8410: 	}
                   8411: 	return $g;
                   8412:     }
                   8413: }
                   8414: 
1.368     albertel 8415: sub latest_rnd_algorithm_id {
1.675     albertel 8416:     return '64bit5';
1.366     albertel 8417: }
1.32      www      8418: 
1.503     albertel 8419: sub get_rand_alg {
                   8420:     my ($courseid)=@_;
1.790     albertel 8421:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 8422:     if ($courseid) {
1.620     albertel 8423: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 8424:     }
                   8425:     return &latest_rnd_algorithm_id();
                   8426: }
                   8427: 
1.562     albertel 8428: sub validCODE {
                   8429:     my ($CODE)=@_;
                   8430:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   8431:     return 0;
                   8432: }
                   8433: 
1.491     albertel 8434: sub getCODE {
1.620     albertel 8435:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 8436:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   8437: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   8438: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 8439: 	return $Apache::lonhomework::history{'resource.CODE'};
                   8440:     }
                   8441:     return undef;
                   8442: }
                   8443: 
1.31      www      8444: sub rndseed {
1.155     albertel 8445:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 8446:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 8447:     if (!defined($symb)) {
1.366     albertel 8448: 	unless ($symb=$wsymb) { return time; }
                   8449:     }
                   8450:     if (!$courseid) { $courseid=$wcourseid; }
                   8451:     if (!$domain) { $domain=$wdomain; }
                   8452:     if (!$username) { $username=$wusername }
1.503     albertel 8453:     my $which=&get_rand_alg();
1.803     albertel 8454: 
1.491     albertel 8455:     if (defined(&getCODE())) {
1.675     albertel 8456: 	if ($which eq '64bit5') {
                   8457: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   8458: 	} elsif ($which eq '64bit4') {
1.575     albertel 8459: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   8460: 	} else {
                   8461: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   8462: 	}
1.675     albertel 8463:     } elsif ($which eq '64bit5') {
                   8464: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 8465:     } elsif ($which eq '64bit4') {
                   8466: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 8467:     } elsif ($which eq '64bit3') {
                   8468: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 8469:     } elsif ($which eq '64bit2') {
                   8470: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 8471:     } elsif ($which eq '64bit') {
                   8472: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   8473:     }
                   8474:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   8475: }
                   8476: 
                   8477: sub rndseed_32bit {
                   8478:     my ($symb,$courseid,$domain,$username)=@_;
                   8479:     {
                   8480: 	use integer;
                   8481: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   8482: 	my $symbseed=numval($symb) << 22;
                   8483: 	my $namechck=unpack("%32C*",$username) << 17;
                   8484: 	my $nameseed=numval($username) << 12;
                   8485: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   8486: 	my $courseseed=unpack("%32C*",$courseid);
                   8487: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 8488: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8489: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8490: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 8491: 	return $num;
                   8492:     }
                   8493: }
                   8494: 
                   8495: sub rndseed_64bit {
                   8496:     my ($symb,$courseid,$domain,$username)=@_;
                   8497:     {
                   8498: 	use integer;
                   8499: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   8500: 	my $symbseed=numval($symb) << 10;
                   8501: 	my $namechck=unpack("%32S*",$username);
                   8502: 	
                   8503: 	my $nameseed=numval($username) << 21;
                   8504: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   8505: 	my $courseseed=unpack("%32S*",$courseid);
                   8506: 	
                   8507: 	my $num1=$symbchck+$symbseed+$namechck;
                   8508: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8509: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8510: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8511: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 8512: 	return "$num1,$num2";
1.155     albertel 8513:     }
1.366     albertel 8514: }
                   8515: 
1.443     albertel 8516: sub rndseed_64bit2 {
                   8517:     my ($symb,$courseid,$domain,$username)=@_;
                   8518:     {
                   8519: 	use integer;
                   8520: 	# strings need to be an even # of cahracters long, it it is odd the
                   8521:         # last characters gets thrown away
                   8522: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8523: 	my $symbseed=numval($symb) << 10;
                   8524: 	my $namechck=unpack("%32S*",$username.' ');
                   8525: 	
                   8526: 	my $nameseed=numval($username) << 21;
1.501     albertel 8527: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8528: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8529: 	
                   8530: 	my $num1=$symbchck+$symbseed+$namechck;
                   8531: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8532: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8533: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 8534: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 8535: 	return "$num1,$num2";
                   8536:     }
                   8537: }
                   8538: 
                   8539: sub rndseed_64bit3 {
                   8540:     my ($symb,$courseid,$domain,$username)=@_;
                   8541:     {
                   8542: 	use integer;
                   8543: 	# strings need to be an even # of cahracters long, it it is odd the
                   8544:         # last characters gets thrown away
                   8545: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8546: 	my $symbseed=numval2($symb) << 10;
                   8547: 	my $namechck=unpack("%32S*",$username.' ');
                   8548: 	
                   8549: 	my $nameseed=numval2($username) << 21;
1.443     albertel 8550: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8551: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8552: 	
                   8553: 	my $num1=$symbchck+$symbseed+$namechck;
                   8554: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8555: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8556: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 8557: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8558: 	
1.503     albertel 8559: 	return "$num1:$num2";
1.443     albertel 8560:     }
                   8561: }
                   8562: 
1.575     albertel 8563: sub rndseed_64bit4 {
                   8564:     my ($symb,$courseid,$domain,$username)=@_;
                   8565:     {
                   8566: 	use integer;
                   8567: 	# strings need to be an even # of cahracters long, it it is odd the
                   8568:         # last characters gets thrown away
                   8569: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8570: 	my $symbseed=numval3($symb) << 10;
                   8571: 	my $namechck=unpack("%32S*",$username.' ');
                   8572: 	
                   8573: 	my $nameseed=numval3($username) << 21;
                   8574: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8575: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8576: 	
                   8577: 	my $num1=$symbchck+$symbseed+$namechck;
                   8578: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8579: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8580: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 8581: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8582: 	
                   8583: 	return "$num1:$num2";
                   8584:     }
                   8585: }
                   8586: 
1.675     albertel 8587: sub rndseed_64bit5 {
                   8588:     my ($symb,$courseid,$domain,$username)=@_;
                   8589:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   8590:     return "$num1:$num2";
                   8591: }
                   8592: 
1.366     albertel 8593: sub rndseed_CODE_64bit {
                   8594:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 8595:     {
1.366     albertel 8596: 	use integer;
1.443     albertel 8597: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 8598: 	my $symbseed=numval2($symb);
1.491     albertel 8599: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8600: 	my $CODEseed=numval(&getCODE());
1.443     albertel 8601: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 8602: 	my $num1=$symbseed+$CODEchck;
                   8603: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8604: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8605: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 8606: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8607: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 8608: 	return "$num1:$num2";
1.366     albertel 8609:     }
                   8610: }
                   8611: 
1.575     albertel 8612: sub rndseed_CODE_64bit4 {
                   8613:     my ($symb,$courseid,$domain,$username)=@_;
                   8614:     {
                   8615: 	use integer;
                   8616: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   8617: 	my $symbseed=numval3($symb);
                   8618: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8619: 	my $CODEseed=numval3(&getCODE());
                   8620: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8621: 	my $num1=$symbseed+$CODEchck;
                   8622: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8623: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8624: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 8625: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8626: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   8627: 	return "$num1:$num2";
                   8628:     }
                   8629: }
                   8630: 
1.675     albertel 8631: sub rndseed_CODE_64bit5 {
                   8632:     my ($symb,$courseid,$domain,$username)=@_;
                   8633:     my $code = &getCODE();
                   8634:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   8635:     return "$num1:$num2";
                   8636: }
                   8637: 
1.366     albertel 8638: sub setup_random_from_rndseed {
                   8639:     my ($rndseed)=@_;
1.503     albertel 8640:     if ($rndseed =~/([,:])/) {
                   8641: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 8642: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   8643:     } else {
                   8644: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 8645:     }
1.36      albertel 8646: }
                   8647: 
1.474     albertel 8648: sub latest_receipt_algorithm_id {
1.835     albertel 8649:     return 'receipt3';
1.474     albertel 8650: }
                   8651: 
1.480     www      8652: sub recunique {
                   8653:     my $fucourseid=shift;
                   8654:     my $unique;
1.835     albertel 8655:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   8656: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8657: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      8658:     } else {
                   8659: 	$unique=$perlvar{'lonReceipt'};
                   8660:     }
                   8661:     return unpack("%32C*",$unique);
                   8662: }
                   8663: 
                   8664: sub recprefix {
                   8665:     my $fucourseid=shift;
                   8666:     my $prefix;
1.835     albertel 8667:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   8668: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8669: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      8670:     } else {
                   8671: 	$prefix=$perlvar{'lonHostID'};
                   8672:     }
                   8673:     return unpack("%32C*",$prefix);
                   8674: }
                   8675: 
1.76      www      8676: sub ireceipt {
1.474     albertel 8677:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 8678: 
                   8679:     my $return =&recprefix($fucourseid).'-';
                   8680: 
                   8681:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   8682: 	$env{'request.state'} eq 'construct') {
                   8683: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   8684: 	return $return;
                   8685:     }
                   8686: 
1.76      www      8687:     my $cuname=unpack("%32C*",$funame);
                   8688:     my $cudom=unpack("%32C*",$fudom);
                   8689:     my $cucourseid=unpack("%32C*",$fucourseid);
                   8690:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      8691:     my $cunique=&recunique($fucourseid);
1.474     albertel 8692:     my $cpart=unpack("%32S*",$part);
1.835     albertel 8693:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   8694: 
1.790     albertel 8695: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 8696: 			       
                   8697: 	$return.= ($cunique%$cuname+
                   8698: 		   $cunique%$cudom+
                   8699: 		   $cusymb%$cuname+
                   8700: 		   $cusymb%$cudom+
                   8701: 		   $cucourseid%$cuname+
                   8702: 		   $cucourseid%$cudom+
                   8703: 		   $cpart%$cuname+
                   8704: 		   $cpart%$cudom);
                   8705:     } else {
                   8706: 	$return.= ($cunique%$cuname+
                   8707: 		   $cunique%$cudom+
                   8708: 		   $cusymb%$cuname+
                   8709: 		   $cusymb%$cudom+
                   8710: 		   $cucourseid%$cuname+
                   8711: 		   $cucourseid%$cudom);
                   8712:     }
                   8713:     return $return;
1.76      www      8714: }
                   8715: 
                   8716: sub receipt {
1.474     albertel 8717:     my ($part)=@_;
1.790     albertel 8718:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 8719:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      8720: }
1.260     ng       8721: 
1.790     albertel 8722: sub whichuser {
                   8723:     my ($passedsymb)=@_;
                   8724:     my ($symb,$courseid,$domain,$name,$publicuser);
                   8725:     if (defined($env{'form.grade_symb'})) {
                   8726: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   8727: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   8728: 	if (!$allowed &&
                   8729: 	    exists($env{'request.course.sec'}) &&
                   8730: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   8731: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   8732: 			      '/'.$env{'request.course.sec'});
                   8733: 	}
                   8734: 	if ($allowed) {
                   8735: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   8736: 	    $courseid=$tmp_courseid;
                   8737: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   8738: 	    ($name)=&get_env_multiple('form.grade_username');
                   8739: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   8740: 	}
                   8741:     }
                   8742:     if (!$passedsymb) {
                   8743: 	$symb=&symbread();
                   8744:     } else {
                   8745: 	$symb=$passedsymb;
                   8746:     }
                   8747:     $courseid=$env{'request.course.id'};
                   8748:     $domain=$env{'user.domain'};
                   8749:     $name=$env{'user.name'};
                   8750:     if ($name eq 'public' && $domain eq 'public') {
                   8751: 	if (!defined($env{'form.username'})) {
                   8752: 	    $env{'form.username'}.=time.rand(10000000);
                   8753: 	}
                   8754: 	$name.=$env{'form.username'};
                   8755:     }
                   8756:     return ($symb,$courseid,$domain,$name,$publicuser);
                   8757: 
                   8758: }
                   8759: 
1.36      albertel 8760: # ------------------------------------------------------------ Serves up a file
1.472     albertel 8761: # returns either the contents of the file or 
                   8762: # -1 if the file doesn't exist
1.481     raeburn  8763: #
                   8764: # if the target is a file that was uploaded via DOCS, 
                   8765: # a check will be made to see if a current copy exists on the local server,
                   8766: # if it does this will be served, otherwise a copy will be retrieved from
                   8767: # the home server for the course and stored in /home/httpd/html/userfiles on
                   8768: # the local server.   
1.472     albertel 8769: 
1.36      albertel 8770: sub getfile {
1.538     albertel 8771:     my ($file) = @_;
1.609     banghart 8772:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 8773:     &repcopy($file);
                   8774:     return &readfile($file);
                   8775: }
                   8776: 
                   8777: sub repcopy_userfile {
                   8778:     my ($file)=@_;
1.609     banghart 8779:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 8780:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 8781:     my ($cdom,$cnum,$filename) = 
1.811     albertel 8782: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 8783:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   8784:     if (-e "$file") {
1.828     www      8785: # we already have a local copy, check it out
1.538     albertel 8786: 	my @fileinfo = stat($file);
1.828     www      8787: 	my $rtncode;
                   8788: 	my $info;
1.538     albertel 8789: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 8790: 	if ($lwpresp ne 'ok') {
1.828     www      8791: # there is no such file anymore, even though we had a local copy
1.482     albertel 8792: 	    if ($rtncode eq '404') {
1.538     albertel 8793: 		unlink($file);
1.482     albertel 8794: 	    }
                   8795: 	    return -1;
                   8796: 	}
                   8797: 	if ($info < $fileinfo[9]) {
1.828     www      8798: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  8799: 	    return 'ok';
1.828     www      8800: 	} else {
                   8801: # the file is outdated, get rid of it
                   8802: 	    unlink($file);
1.482     albertel 8803: 	}
1.828     www      8804:     }
                   8805: # one way or the other, at this point, we don't have the file
                   8806: # construct the correct path for the file
                   8807:     my @parts = ($cdom,$cnum); 
                   8808:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   8809: 	push @parts, split(/\//,$1);
                   8810:     }
                   8811:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   8812:     foreach my $part (@parts) {
                   8813: 	$path .= '/'.$part;
                   8814: 	if (!-e $path) {
                   8815: 	    mkdir($path,0770);
1.482     albertel 8816: 	}
                   8817:     }
1.828     www      8818: # now the path exists for sure
                   8819: # get a user agent
                   8820:     my $ua=new LWP::UserAgent;
                   8821:     my $transferfile=$file.'.in.transfer';
                   8822: # FIXME: this should flock
                   8823:     if (-e $transferfile) { return 'ok'; }
                   8824:     my $request;
                   8825:     $uri=~s/^\///;
1.980     raeburn  8826:     my $homeserver = &homeserver($cnum,$cdom);
                   8827:     my $protocol = $protocol{$homeserver};
                   8828:     $protocol = 'http' if ($protocol ne 'https');
                   8829:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      8830:     my $response=$ua->request($request,$transferfile);
                   8831: # did it work?
                   8832:     if ($response->is_error()) {
                   8833: 	unlink($transferfile);
                   8834: 	&logthis("Userfile repcopy failed for $uri");
                   8835: 	return -1;
                   8836:     }
                   8837: # worked, rename the transfer file
                   8838:     rename($transferfile,$file);
1.607     raeburn  8839:     return 'ok';
1.481     raeburn  8840: }
                   8841: 
1.517     albertel 8842: sub tokenwrapper {
                   8843:     my $uri=shift;
1.980     raeburn  8844:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 8845:     $uri=~s|^/||;
1.620     albertel 8846:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8847:     my $token=$1;
1.552     albertel 8848:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8849:     if ($udom && $uname && $file) {
                   8850: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8851:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  8852:         my $homeserver = &homeserver($uname,$udom);
                   8853:         my $protocol = $protocol{$homeserver};
                   8854:         $protocol = 'http' if ($protocol ne 'https');
                   8855:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 8856:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8857:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8858:     } else {
                   8859:         return '/adm/notfound.html';
                   8860:     }
                   8861: }
                   8862: 
1.828     www      8863: # call with reqtype HEAD: get last modification time
                   8864: # call with reqtype GET: get the file contents
                   8865: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8866: #
1.481     raeburn  8867: sub getuploaded {
                   8868:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8869:     $uri=~s/^\///;
1.980     raeburn  8870:     my $homeserver = &homeserver($cnum,$cdom);
                   8871:     my $protocol = $protocol{$homeserver};
                   8872:     $protocol = 'http' if ($protocol ne 'https');
                   8873:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  8874:     my $ua=new LWP::UserAgent;
                   8875:     my $request=new HTTP::Request($reqtype,$uri);
                   8876:     my $response=$ua->request($request);
                   8877:     $$rtncode = $response->code;
1.482     albertel 8878:     if (! $response->is_success()) {
                   8879: 	return 'failed';
                   8880:     }      
                   8881:     if ($reqtype eq 'HEAD') {
1.486     www      8882: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8883:     } elsif ($reqtype eq 'GET') {
                   8884: 	$$info = $response->content;
1.472     albertel 8885:     }
1.482     albertel 8886:     return 'ok';
1.36      albertel 8887: }
                   8888: 
1.481     raeburn  8889: sub readfile {
                   8890:     my $file = shift;
                   8891:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8892:     my $fh;
                   8893:     open($fh,"<$file");
                   8894:     my $a='';
1.800     albertel 8895:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8896:     return $a;
                   8897: }
                   8898: 
1.36      albertel 8899: sub filelocation {
1.590     banghart 8900:     my ($dir,$file) = @_;
                   8901:     my $location;
                   8902:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8903: 
                   8904:     if ($file =~ m-^/adm/-) {
                   8905: 	$file=~s-^/adm/wrapper/-/-;
                   8906: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8907:     }
1.882     albertel 8908: 
1.590     banghart 8909:     if ($file=~m:^/~:) { # is a contruction space reference
                   8910:         $location = $file;
                   8911:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8912:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8913: 	# is a correct contruction space reference
                   8914:         $location = $file;
1.956     raeburn  8915:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   8916:         $location = $file;
1.609     banghart 8917:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8918:         my ($udom,$uname,$filename)=
1.811     albertel 8919:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8920:         my $home=&homeserver($uname,$udom);
                   8921:         my $is_me=0;
                   8922:         my @ids=&current_machine_ids();
                   8923:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8924:         if ($is_me) {
1.955     raeburn  8925:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 8926:         } else {
                   8927:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8928:   	      $udom.'/'.$uname.'/'.$filename;
                   8929:         }
1.882     albertel 8930:     } elsif ($file =~ m-^/adm/-) {
                   8931: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8932:     } else {
                   8933:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8934:         $file=~s:^/res/:/:;
                   8935:         if ( !( $file =~ m:^/:) ) {
                   8936:             $location = $dir. '/'.$file;
                   8937:         } else {
                   8938:             $location = '/home/httpd/html/res'.$file;
                   8939:         }
1.59      albertel 8940:     }
1.590     banghart 8941:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8942:     while ($location=~m{/\.\./}) {
                   8943: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8944: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8945: 	} else {
                   8946: 	    $location=~ s{/\.\./}{/}g;
                   8947: 	}
                   8948:     } #remove dir/..
1.590     banghart 8949:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8950:     return $location;
1.46      www      8951: }
1.36      albertel 8952: 
1.46      www      8953: sub hreflocation {
                   8954:     my ($dir,$file)=@_;
1.980     raeburn  8955:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 8956: 	$file=filelocation($dir,$file);
1.700     albertel 8957:     } elsif ($file=~m-^/adm/-) {
                   8958: 	$file=~s-^/adm/wrapper/-/-;
                   8959: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8960:     }
                   8961:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8962: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8963:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8964: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8965:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8966: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8967: 	    -/uploaded/$1/$2/-x;
1.46      www      8968:     }
1.913     albertel 8969:     if ($file=~ m{^/userfiles/}) {
                   8970: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8971:     }
1.462     albertel 8972:     return $file;
1.465     albertel 8973: }
                   8974: 
                   8975: sub current_machine_domains {
1.853     albertel 8976:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8977: }
                   8978: 
                   8979: sub machine_domains {
                   8980:     my ($hostname) = @_;
1.465     albertel 8981:     my @domains;
1.838     albertel 8982:     my %hostname = &all_hostnames();
1.465     albertel 8983:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8984: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8985: 	if ($hostname eq $name) {
1.844     albertel 8986: 	    push(@domains,&host_domain($id));
1.465     albertel 8987: 	}
                   8988:     }
                   8989:     return @domains;
                   8990: }
                   8991: 
                   8992: sub current_machine_ids {
1.853     albertel 8993:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8994: }
                   8995: 
                   8996: sub machine_ids {
                   8997:     my ($hostname) = @_;
                   8998:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8999:     my @ids;
1.888     albertel 9000:     my %name_to_host = &all_names();
1.889     albertel 9001:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   9002: 	return @{ $name_to_host{$hostname} };
                   9003:     }
                   9004:     return;
1.31      www      9005: }
                   9006: 
1.824     raeburn  9007: sub additional_machine_domains {
                   9008:     my @domains;
                   9009:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   9010:     while( my $line = <$fh>) {
                   9011:         $line =~ s/\s//g;
                   9012:         push(@domains,$line);
                   9013:     }
                   9014:     return @domains;
                   9015: }
                   9016: 
                   9017: sub default_login_domain {
                   9018:     my $domain = $perlvar{'lonDefDomain'};
                   9019:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   9020:     foreach my $posdom (&current_machine_domains(),
                   9021:                         &additional_machine_domains()) {
                   9022:         if (lc($posdom) eq lc($testdomain)) {
                   9023:             $domain=$posdom;
                   9024:             last;
                   9025:         }
                   9026:     }
                   9027:     return $domain;
                   9028: }
                   9029: 
1.31      www      9030: # ------------------------------------------------------------- Declutters URLs
                   9031: 
                   9032: sub declutter {
                   9033:     my $thisfn=shift;
1.569     albertel 9034:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 9035:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      9036:     $thisfn=~s/^\///;
1.697     albertel 9037:     $thisfn=~s|^adm/wrapper/||;
                   9038:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      9039:     $thisfn=~s/^res\///;
1.235     www      9040:     $thisfn=~s/\?.+$//;
1.268     www      9041:     return $thisfn;
                   9042: }
                   9043: 
                   9044: # ------------------------------------------------------------- Clutter up URLs
                   9045: 
                   9046: sub clutter {
                   9047:     my $thisfn='/'.&declutter(shift);
1.887     albertel 9048:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 9049: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      9050:        $thisfn='/res'.$thisfn; 
                   9051:     }
1.694     albertel 9052:     if ($thisfn !~m|/adm|) {
1.695     albertel 9053: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 9054: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 9055: 	} else {
                   9056: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   9057: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 9058: 	    if ($embstyle eq 'ssi'
                   9059: 		|| ($embstyle eq 'hdn')
                   9060: 		|| ($embstyle eq 'rat')
                   9061: 		|| ($embstyle eq 'prv')
                   9062: 		|| ($embstyle eq 'ign')) {
                   9063: 		#do nothing with these
                   9064: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 9065: 		|| ($embstyle eq 'emb')
                   9066: 		|| ($embstyle eq 'wrp')) {
                   9067: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 9068: 	    } elsif ($embstyle eq 'unk'
                   9069: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 9070: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 9071: 	    } else {
1.718     www      9072: #		&logthis("Got a blank emb style");
1.695     albertel 9073: 	    }
1.694     albertel 9074: 	}
                   9075:     }
1.31      www      9076:     return $thisfn;
1.12      www      9077: }
                   9078: 
1.787     albertel 9079: sub clutter_with_no_wrapper {
                   9080:     my $uri = &clutter(shift);
                   9081:     if ($uri =~ m-^/adm/-) {
                   9082: 	$uri =~ s-^/adm/wrapper/-/-;
                   9083: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   9084:     }
                   9085:     return $uri;
                   9086: }
                   9087: 
1.557     albertel 9088: sub freeze_escape {
                   9089:     my ($value)=@_;
                   9090:     if (ref($value)) {
                   9091: 	$value=&nfreeze($value);
                   9092: 	return '__FROZEN__'.&escape($value);
                   9093:     }
                   9094:     return &escape($value);
                   9095: }
                   9096: 
1.11      www      9097: 
1.557     albertel 9098: sub thaw_unescape {
                   9099:     my ($value)=@_;
                   9100:     if ($value =~ /^__FROZEN__/) {
                   9101: 	substr($value,0,10,undef);
                   9102: 	$value=&unescape($value);
                   9103: 	return &thaw($value);
                   9104:     }
                   9105:     return &unescape($value);
                   9106: }
                   9107: 
1.436     albertel 9108: sub correct_line_ends {
                   9109:     my ($result)=@_;
                   9110:     $$result =~s/\r\n/\n/mg;
                   9111:     $$result =~s/\r/\n/mg;
1.415     albertel 9112: }
1.1       albertel 9113: # ================================================================ Main Program
                   9114: 
1.184     www      9115: sub goodbye {
1.204     albertel 9116:    &logthis("Starting Shut down");
1.443     albertel 9117: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 9118:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 9119: #converted
1.599     albertel 9120: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 9121:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   9122: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   9123: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 9124: #1.1 only
1.870     albertel 9125: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   9126: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   9127: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   9128: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   9129:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 9130:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   9131:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      9132:    &flushcourselogs();
                   9133:    &logthis("Shutting down");
                   9134: }
                   9135: 
1.852     albertel 9136: sub get_dns {
1.869     albertel 9137:     my ($url,$func,$ignore_cache) = @_;
                   9138:     if (!$ignore_cache) {
                   9139: 	my ($content,$cached)=
                   9140: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   9141: 	if ($cached) {
                   9142: 	    &$func($content);
                   9143: 	    return;
                   9144: 	}
                   9145:     }
                   9146: 
                   9147:     my %alldns;
1.852     albertel 9148:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9149:     foreach my $dns (<$config>) {
                   9150: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  9151:         my $line = $1;
                   9152:         my ($host,$protocol) = split(/:/,$line);
                   9153:         if ($protocol ne 'https') {
                   9154:             $protocol = 'http';
                   9155:         }
                   9156: 	$alldns{$host} = $protocol;
1.869     albertel 9157:     }
                   9158:     while (%alldns) {
                   9159: 	my ($dns) = keys(%alldns);
1.852     albertel 9160: 	my $ua=new LWP::UserAgent;
1.979     raeburn  9161: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 9162: 	my $response=$ua->request($request);
1.979     raeburn  9163:         delete($alldns{$dns});
1.852     albertel 9164: 	next if ($response->is_error());
                   9165: 	my @content = split("\n",$response->content);
1.869     albertel 9166: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 9167: 	&$func(\@content);
1.869     albertel 9168: 	return;
1.852     albertel 9169:     }
                   9170:     close($config);
1.871     albertel 9171:     my $which = (split('/',$url))[3];
                   9172:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   9173:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 9174:     my @content = <$config>;
                   9175:     &$func(\@content);
                   9176:     return;
1.852     albertel 9177: }
1.327     albertel 9178: # ------------------------------------------------------------ Read domain file
                   9179: {
1.852     albertel 9180:     my $loaded;
1.846     albertel 9181:     my %domain;
                   9182: 
1.852     albertel 9183:     sub parse_domain_tab {
                   9184: 	my ($lines) = @_;
                   9185: 	foreach my $line (@$lines) {
                   9186: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      9187: 
1.846     albertel 9188: 	    chomp($line);
1.852     albertel 9189: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 9190: 	    my %this_domain;
                   9191: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   9192: 			       'lang_def', 'city', 'longi', 'lati',
                   9193: 			       'primary') {
                   9194: 		$this_domain{$field} = shift(@elements);
                   9195: 	    }
                   9196: 	    $domain{$name} = \%this_domain;
1.852     albertel 9197: 	}
                   9198:     }
1.864     albertel 9199: 
                   9200:     sub reset_domain_info {
                   9201: 	undef($loaded);
                   9202: 	undef(%domain);
                   9203:     }
                   9204: 
1.852     albertel 9205:     sub load_domain_tab {
1.869     albertel 9206: 	my ($ignore_cache) = @_;
                   9207: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 9208: 	my $fh;
                   9209: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   9210: 	    my @lines = <$fh>;
                   9211: 	    &parse_domain_tab(\@lines);
1.448     albertel 9212: 	}
1.852     albertel 9213: 	close($fh);
                   9214: 	$loaded = 1;
1.327     albertel 9215:     }
1.846     albertel 9216: 
                   9217:     sub domain {
1.852     albertel 9218: 	&load_domain_tab() if (!$loaded);
                   9219: 
1.846     albertel 9220: 	my ($name,$what) = @_;
                   9221: 	return if ( !exists($domain{$name}) );
                   9222: 
                   9223: 	if (!$what) {
                   9224: 	    return $domain{$name}{'description'};
                   9225: 	}
                   9226: 	return $domain{$name}{$what};
                   9227:     }
1.974     raeburn  9228: 
                   9229:     sub domain_info {
                   9230:         &load_domain_tab() if (!$loaded);
                   9231:         return %domain;
                   9232:     }
                   9233: 
1.327     albertel 9234: }
                   9235: 
                   9236: 
1.1       albertel 9237: # ------------------------------------------------------------- Read hosts file
                   9238: {
1.838     albertel 9239:     my %hostname;
1.844     albertel 9240:     my %hostdom;
1.845     albertel 9241:     my %libserv;
1.852     albertel 9242:     my $loaded;
1.888     albertel 9243:     my %name_to_host;
1.852     albertel 9244: 
                   9245:     sub parse_hosts_tab {
                   9246: 	my ($file) = @_;
                   9247: 	foreach my $configline (@$file) {
                   9248: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   9249: 	    next if ($configline =~ /^\^/);
                   9250: 	    chomp($configline);
1.968     raeburn  9251: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852     albertel 9252: 	    $name=~s/\s//g;
                   9253: 	    if ($id && $domain && $role && $name) {
                   9254: 		$hostname{$id}=$name;
1.888     albertel 9255: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 9256: 		$hostdom{$id}=$domain;
                   9257: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  9258:                 if (defined($protocol)) {
                   9259:                     if ($protocol eq 'https') {
                   9260:                         $protocol{$id} = $protocol;
                   9261:                     } else {
                   9262:                         $protocol{$id} = 'http'; 
                   9263:                     }
1.968     raeburn  9264:                 } else {
1.969     raeburn  9265:                     $protocol{$id} = 'http';
1.968     raeburn  9266:                 }
1.852     albertel 9267: 	    }
                   9268: 	}
                   9269:     }
1.864     albertel 9270:     
                   9271:     sub reset_hosts_info {
1.897     albertel 9272: 	&purge_remembered();
1.864     albertel 9273: 	&reset_domain_info();
                   9274: 	&reset_hosts_ip_info();
1.892     albertel 9275: 	undef(%name_to_host);
1.864     albertel 9276: 	undef(%hostname);
                   9277: 	undef(%hostdom);
                   9278: 	undef(%libserv);
                   9279: 	undef($loaded);
                   9280:     }
1.1       albertel 9281: 
1.852     albertel 9282:     sub load_hosts_tab {
1.869     albertel 9283: 	my ($ignore_cache) = @_;
                   9284: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 9285: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9286: 	my @config = <$config>;
                   9287: 	&parse_hosts_tab(\@config);
                   9288: 	close($config);
                   9289: 	$loaded=1;
1.1       albertel 9290:     }
1.852     albertel 9291: 
1.838     albertel 9292:     sub hostname {
1.852     albertel 9293: 	&load_hosts_tab() if (!$loaded);
                   9294: 
1.838     albertel 9295: 	my ($lonid) = @_;
                   9296: 	return $hostname{$lonid};
                   9297:     }
1.845     albertel 9298: 
1.838     albertel 9299:     sub all_hostnames {
1.852     albertel 9300: 	&load_hosts_tab() if (!$loaded);
                   9301: 
1.838     albertel 9302: 	return %hostname;
                   9303:     }
1.845     albertel 9304: 
1.888     albertel 9305:     sub all_names {
                   9306: 	&load_hosts_tab() if (!$loaded);
                   9307: 
                   9308: 	return %name_to_host;
                   9309:     }
                   9310: 
1.974     raeburn  9311:     sub all_host_domain {
                   9312:         &load_hosts_tab() if (!$loaded);
                   9313:         return %hostdom;
                   9314:     }
                   9315: 
1.845     albertel 9316:     sub is_library {
1.852     albertel 9317: 	&load_hosts_tab() if (!$loaded);
                   9318: 
1.845     albertel 9319: 	return exists($libserv{$_[0]});
                   9320:     }
                   9321: 
                   9322:     sub all_library {
1.852     albertel 9323: 	&load_hosts_tab() if (!$loaded);
                   9324: 
1.845     albertel 9325: 	return %libserv;
                   9326:     }
                   9327: 
1.841     albertel 9328:     sub get_servers {
1.852     albertel 9329: 	&load_hosts_tab() if (!$loaded);
                   9330: 
1.841     albertel 9331: 	my ($domain,$type) = @_;
                   9332: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   9333: 	                                          : %hostname;
                   9334: 	my %result;
1.842     albertel 9335: 	if (ref($domain) eq 'ARRAY') {
                   9336: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 9337: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 9338: 		    $result{$host} = $hostname;
                   9339: 		}
                   9340: 	    }
                   9341: 	} else {
                   9342: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   9343: 		if ($hostdom{$host} eq $domain) {
                   9344: 		    $result{$host} = $hostname;
                   9345: 		}
1.841     albertel 9346: 	    }
                   9347: 	}
                   9348: 	return %result;
                   9349:     }
1.845     albertel 9350: 
1.844     albertel 9351:     sub host_domain {
1.852     albertel 9352: 	&load_hosts_tab() if (!$loaded);
                   9353: 
1.844     albertel 9354: 	my ($lonid) = @_;
                   9355: 	return $hostdom{$lonid};
                   9356:     }
                   9357: 
1.841     albertel 9358:     sub all_domains {
1.852     albertel 9359: 	&load_hosts_tab() if (!$loaded);
                   9360: 
1.841     albertel 9361: 	my %seen;
                   9362: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   9363: 	return @uniq;
                   9364:     }
1.1       albertel 9365: }
                   9366: 
1.847     albertel 9367: { 
                   9368:     my %iphost;
1.856     albertel 9369:     my %name_to_ip;
                   9370:     my %lonid_to_ip;
1.869     albertel 9371: 
1.847     albertel 9372:     sub get_hosts_from_ip {
                   9373: 	my ($ip) = @_;
                   9374: 	my %iphosts = &get_iphost();
                   9375: 	if (ref($iphosts{$ip})) {
                   9376: 	    return @{$iphosts{$ip}};
                   9377: 	}
                   9378: 	return;
1.839     albertel 9379:     }
1.864     albertel 9380:     
                   9381:     sub reset_hosts_ip_info {
                   9382: 	undef(%iphost);
                   9383: 	undef(%name_to_ip);
                   9384: 	undef(%lonid_to_ip);
                   9385:     }
1.856     albertel 9386: 
                   9387:     sub get_host_ip {
                   9388: 	my ($lonid) = @_;
                   9389: 	if (exists($lonid_to_ip{$lonid})) {
                   9390: 	    return $lonid_to_ip{$lonid};
                   9391: 	}
                   9392: 	my $name=&hostname($lonid);
                   9393:    	my $ip = gethostbyname($name);
                   9394: 	return if (!$ip || length($ip) ne 4);
                   9395: 	$ip=inet_ntoa($ip);
                   9396: 	$name_to_ip{$name}   = $ip;
                   9397: 	$lonid_to_ip{$lonid} = $ip;
                   9398: 	return $ip;
                   9399:     }
1.847     albertel 9400:     
                   9401:     sub get_iphost {
1.869     albertel 9402: 	my ($ignore_cache) = @_;
1.894     albertel 9403: 
1.869     albertel 9404: 	if (!$ignore_cache) {
                   9405: 	    if (%iphost) {
                   9406: 		return %iphost;
                   9407: 	    }
                   9408: 	    my ($ip_info,$cached)=
                   9409: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   9410: 	    if ($cached) {
                   9411: 		%iphost      = %{$ip_info->[0]};
                   9412: 		%name_to_ip  = %{$ip_info->[1]};
                   9413: 		%lonid_to_ip = %{$ip_info->[2]};
                   9414: 		return %iphost;
                   9415: 	    }
                   9416: 	}
1.894     albertel 9417: 
                   9418: 	# get yesterday's info for fallback
                   9419: 	my %old_name_to_ip;
                   9420: 	my ($ip_info,$cached)=
                   9421: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   9422: 	if ($cached) {
                   9423: 	    %old_name_to_ip = %{$ip_info->[1]};
                   9424: 	}
                   9425: 
1.888     albertel 9426: 	my %name_to_host = &all_names();
                   9427: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 9428: 	    my $ip;
                   9429: 	    if (!exists($name_to_ip{$name})) {
                   9430: 		$ip = gethostbyname($name);
                   9431: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 9432: 		    if (defined($old_name_to_ip{$name})) {
                   9433: 			$ip = $old_name_to_ip{$name};
                   9434: 			&logthis("Can't find $name defaulting to old $ip");
                   9435: 		    } else {
                   9436: 			&logthis("Name $name no IP found");
                   9437: 			next;
                   9438: 		    }
                   9439: 		} else {
                   9440: 		    $ip=inet_ntoa($ip);
1.847     albertel 9441: 		}
                   9442: 		$name_to_ip{$name} = $ip;
                   9443: 	    } else {
                   9444: 		$ip = $name_to_ip{$name};
1.653     albertel 9445: 	    }
1.888     albertel 9446: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   9447: 		$lonid_to_ip{$id} = $ip;
                   9448: 	    }
                   9449: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 9450: 	}
1.869     albertel 9451: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   9452: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 9453: 				      48*60*60);
1.869     albertel 9454: 
1.847     albertel 9455: 	return %iphost;
1.598     albertel 9456:     }
                   9457: 
1.992     raeburn  9458:     #
                   9459:     #  Given a DNS returns the loncapa host name for that DNS 
                   9460:     # 
                   9461:     sub host_from_dns {
                   9462:         my ($dns) = @_;
                   9463:         my @hosts;
                   9464:         my $ip;
                   9465: 
1.993     raeburn  9466:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  9467:             $ip = $name_to_ip{$dns};
                   9468:         }
                   9469:         if (!$ip) {
                   9470:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   9471:             if (length($ip) == 4) { 
                   9472: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   9473:             }
                   9474:         }
                   9475:         if ($ip) {
                   9476: 	    @hosts = get_hosts_from_ip($ip);
                   9477: 	    return $hosts[0];
                   9478:         }
                   9479:         return undef;
1.986     foxr     9480:     }
1.992     raeburn  9481: 
1.986     foxr     9482: }
                   9483: 
1.862     albertel 9484: BEGIN {
                   9485: 
                   9486: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   9487:     unless ($readit) {
                   9488: {
                   9489:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   9490:     %perlvar = (%perlvar,%{$configvars});
                   9491: }
                   9492: 
                   9493: 
1.1       albertel 9494: # ------------------------------------------------------ Read spare server file
                   9495: {
1.448     albertel 9496:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 9497: 
                   9498:     while (my $configline=<$config>) {
                   9499:        chomp($configline);
1.284     matthew  9500:        if ($configline) {
1.784     albertel 9501: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 9502: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 9503: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 9504:        }
                   9505:     }
1.448     albertel 9506:     close($config);
1.1       albertel 9507: }
1.11      www      9508: # ------------------------------------------------------------ Read permissions
                   9509: {
1.448     albertel 9510:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      9511: 
                   9512:     while (my $configline=<$config>) {
1.448     albertel 9513: 	chomp($configline);
                   9514: 	if ($configline) {
                   9515: 	    my ($role,$perm)=split(/ /,$configline);
                   9516: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   9517: 	}
1.11      www      9518:     }
1.448     albertel 9519:     close($config);
1.11      www      9520: }
                   9521: 
                   9522: # -------------------------------------------- Read plain texts for permissions
                   9523: {
1.448     albertel 9524:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      9525: 
                   9526:     while (my $configline=<$config>) {
1.448     albertel 9527: 	chomp($configline);
                   9528: 	if ($configline) {
1.742     raeburn  9529: 	    my ($short,@plain)=split(/:/,$configline);
                   9530:             %{$prp{$short}} = ();
                   9531: 	    if (@plain > 0) {
                   9532:                 $prp{$short}{'std'} = $plain[0];
                   9533:                 for (my $i=1; $i<@plain; $i++) {
                   9534:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   9535:                 }
                   9536:             }
1.448     albertel 9537: 	}
1.135     www      9538:     }
1.448     albertel 9539:     close($config);
1.135     www      9540: }
                   9541: 
                   9542: # ---------------------------------------------------------- Read package table
                   9543: {
1.448     albertel 9544:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      9545: 
                   9546:     while (my $configline=<$config>) {
1.483     albertel 9547: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 9548: 	chomp($configline);
                   9549: 	my ($short,$plain)=split(/:/,$configline);
                   9550: 	my ($pack,$name)=split(/\&/,$short);
                   9551: 	if ($plain ne '') {
                   9552: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   9553: 	    $packagetab{$short}=$plain; 
                   9554: 	}
1.11      www      9555:     }
1.448     albertel 9556:     close($config);
1.329     matthew  9557: }
                   9558: 
                   9559: # ------------- set up temporary directory
                   9560: {
                   9561:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   9562: 
1.11      www      9563: }
                   9564: 
1.794     albertel 9565: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   9566: 				'compress_threshold'=> 20_000,
                   9567:  			        });
1.185     www      9568: 
1.281     www      9569: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      9570: $dumpcount=0;
1.958     www      9571: $locknum=0;
1.22      www      9572: 
1.163     harris41 9573: &logtouch();
1.672     albertel 9574: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      9575: $readit=1;
1.564     albertel 9576:     {
                   9577: 	use integer;
                   9578: 	my $test=(2**32)+1;
1.568     albertel 9579: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 9580: 	&logthis(" Detected 64bit platform ($_64bit)");
                   9581:     }
1.195     www      9582: }
1.1       albertel 9583: }
1.179     www      9584: 
1.1       albertel 9585: 1;
1.191     harris41 9586: __END__
                   9587: 
1.243     albertel 9588: =pod
                   9589: 
1.191     harris41 9590: =head1 NAME
                   9591: 
1.243     albertel 9592: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 9593: 
                   9594: =head1 SYNOPSIS
                   9595: 
1.243     albertel 9596: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 9597: 
                   9598:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   9599: 
1.243     albertel 9600: Common parameters:
                   9601: 
                   9602: =over 4
                   9603: 
                   9604: =item *
                   9605: 
                   9606: $uname : an internal username (if $cname expecting a course Id specifically)
                   9607: 
                   9608: =item *
                   9609: 
                   9610: $udom : a domain (if $cdom expecting a course's domain specifically)
                   9611: 
                   9612: =item *
                   9613: 
                   9614: $symb : a resource instance identifier
                   9615: 
                   9616: =item *
                   9617: 
                   9618: $namespace : the name of a .db file that contains the data needed or
                   9619: being set.
                   9620: 
                   9621: =back
                   9622: 
1.394     bowersj2 9623: =head1 OVERVIEW
1.191     harris41 9624: 
1.394     bowersj2 9625: lonnet provides subroutines which interact with the
                   9626: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   9627: about classes, users, and resources.
1.243     albertel 9628: 
                   9629: For many of these objects you can also use this to store data about
                   9630: them or modify them in various ways.
1.191     harris41 9631: 
1.394     bowersj2 9632: =head2 Symbs
1.191     harris41 9633: 
1.394     bowersj2 9634: To identify a specific instance of a resource, LON-CAPA uses symbols
                   9635: or "symbs"X<symb>. These identifiers are built from the URL of the
                   9636: map, the resource number of the resource in the map, and the URL of
                   9637: the resource itself. The latter is somewhat redundant, but might help
                   9638: if maps change.
                   9639: 
                   9640: An example is
                   9641: 
                   9642:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   9643: 
                   9644: The respective map entry is
                   9645: 
                   9646:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   9647:   title="Problem 2">
                   9648:  </resource>
                   9649: 
                   9650: Symbs are used by the random number generator, as well as to store and
                   9651: restore data specific to a certain instance of for example a problem.
                   9652: 
                   9653: =head2 Storing And Retrieving Data
                   9654: 
                   9655: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   9656: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   9657: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   9658: is is the non-critical message twin of cstore. These functions are for
                   9659: handlers to store a perl hash to a user's permanent data space in an
                   9660: easy manner, and to retrieve it again on another call. It is expected
                   9661: that a handler would use this once at the beginning to retrieve data,
                   9662: and then again once at the end to send only the new data back.
                   9663: 
                   9664: The data is stored in the user's data directory on the user's
                   9665: homeserver under the ID of the course.
                   9666: 
                   9667: The hash that is returned by restore will have all of the previous
                   9668: value for all of the elements of the hash.
                   9669: 
                   9670: Example:
                   9671: 
                   9672:  #creating a hash
                   9673:  my %hash;
                   9674:  $hash{'foo'}='bar';
                   9675: 
                   9676:  #storing it
                   9677:  &Apache::lonnet::cstore(\%hash);
                   9678: 
                   9679:  #changing a value
                   9680:  $hash{'foo'}='notbar';
                   9681: 
                   9682:  #adding a new value
                   9683:  $hash{'bar'}='foo';
                   9684:  &Apache::lonnet::cstore(\%hash);
                   9685: 
                   9686:  #retrieving the hash
                   9687:  my %history=&Apache::lonnet::restore();
                   9688: 
                   9689:  #print the hash
                   9690:  foreach my $key (sort(keys(%history))) {
                   9691:    print("\%history{$key} = $history{$key}");
                   9692:  }
                   9693: 
                   9694: Will print out:
1.191     harris41 9695: 
1.394     bowersj2 9696:  %history{1:foo} = bar
                   9697:  %history{1:keys} = foo:timestamp
                   9698:  %history{1:timestamp} = 990455579
                   9699:  %history{2:bar} = foo
                   9700:  %history{2:foo} = notbar
                   9701:  %history{2:keys} = foo:bar:timestamp
                   9702:  %history{2:timestamp} = 990455580
                   9703:  %history{bar} = foo
                   9704:  %history{foo} = notbar
                   9705:  %history{timestamp} = 990455580
                   9706:  %history{version} = 2
                   9707: 
                   9708: Note that the special hash entries C<keys>, C<version> and
                   9709: C<timestamp> were added to the hash. C<version> will be equal to the
                   9710: total number of versions of the data that have been stored. The
                   9711: C<timestamp> attribute will be the UNIX time the hash was
                   9712: stored. C<keys> is available in every historical section to list which
                   9713: keys were added or changed at a specific historical revision of a
                   9714: hash.
                   9715: 
                   9716: B<Warning>: do not store the hash that restore returns directly. This
                   9717: will cause a mess since it will restore the historical keys as if the
                   9718: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 9719: 
1.394     bowersj2 9720: Calling convention:
1.191     harris41 9721: 
1.394     bowersj2 9722:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   9723:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 9724: 
1.394     bowersj2 9725: For more detailed information, see lonnet specific documentation.
1.191     harris41 9726: 
1.394     bowersj2 9727: =head1 RETURN MESSAGES
1.191     harris41 9728: 
1.394     bowersj2 9729: =over 4
1.191     harris41 9730: 
1.394     bowersj2 9731: =item * B<con_lost>: unable to contact remote host
1.191     harris41 9732: 
1.394     bowersj2 9733: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   9734: when the connection is brought back up
1.191     harris41 9735: 
1.394     bowersj2 9736: =item * B<con_failed>: unable to contact remote host and unable to save message
                   9737: for later delivery
1.191     harris41 9738: 
1.967     bisitz   9739: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 9740: 
1.394     bowersj2 9741: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 9742: that was requested
1.191     harris41 9743: 
1.243     albertel 9744: =back
1.191     harris41 9745: 
1.243     albertel 9746: =head1 PUBLIC SUBROUTINES
1.191     harris41 9747: 
1.243     albertel 9748: =head2 Session Environment Functions
1.191     harris41 9749: 
1.243     albertel 9750: =over 4
1.191     harris41 9751: 
1.394     bowersj2 9752: =item * 
                   9753: X<appenv()>
1.949     raeburn  9754: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 9755: the user envirnoment file, and will be restored for each access this
1.620     albertel 9756: user makes during this session, also modifies the %env for the current
1.949     raeburn  9757: process. Optional rolesarrayref - if defined contains a reference to an array
                   9758: of roles which are exempt from the restriction on modifying user.role entries 
                   9759: in the user's environment.db and in %env.    
1.191     harris41 9760: 
                   9761: =item *
1.394     bowersj2 9762: X<delenv()>
1.987     raeburn  9763: B<delenv($delthis,$regexp)>: removes all items from the session
                   9764: environment file that begin with $delthis. If the 
                   9765: optional second arg - $regexp - is true, $delthis is treated as a 
                   9766: regular expression, otherwise \Q$delthis\E is used. 
                   9767: The values are also deleted from the current processes %env.
1.191     harris41 9768: 
1.795     albertel 9769: =item * get_env_multiple($name) 
                   9770: 
                   9771: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   9772: values may be defined and end up as an array ref.
                   9773: 
                   9774: returns an array of values
                   9775: 
1.243     albertel 9776: =back
                   9777: 
                   9778: =head2 User Information
1.191     harris41 9779: 
1.243     albertel 9780: =over 4
1.191     harris41 9781: 
                   9782: =item *
1.394     bowersj2 9783: X<queryauthenticate()>
                   9784: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 9785: authentication scheme
                   9786: 
                   9787: =item *
1.394     bowersj2 9788: X<authenticate()>
                   9789: B<authenticate($uname,$upass,$udom)>: try to
                   9790: authenticate user from domain's lib servers (first use the current
                   9791: one). C<$upass> should be the users password.
1.191     harris41 9792: 
                   9793: =item *
1.394     bowersj2 9794: X<homeserver()>
                   9795: B<homeserver($uname,$udom)>: find the server which has
                   9796: the user's directory and files (there must be only one), this caches
                   9797: the answer, and also caches if there is a borken connection.
1.191     harris41 9798: 
                   9799: =item *
1.394     bowersj2 9800: X<idget()>
                   9801: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   9802: (IDs are a unique resource in a domain, there must be only 1 ID per
                   9803: username, and only 1 username per ID in a specific domain) (returns
                   9804: hash: id=>name,id=>name)
1.191     harris41 9805: 
                   9806: =item *
1.394     bowersj2 9807: X<idrget()>
                   9808: B<idrget($udom,@unames)>: find the IDs behind a list of
                   9809: usernames (returns hash: name=>id,name=>id)
1.191     harris41 9810: 
                   9811: =item *
1.394     bowersj2 9812: X<idput()>
                   9813: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 9814: 
                   9815: =item *
1.394     bowersj2 9816: X<rolesinit()>
                   9817: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 9818: 
                   9819: =item *
1.551     albertel 9820: X<getsection()>
                   9821: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 9822: course $cname, return section name/number or '' for "not in course"
                   9823: and '-1' for "no section"
                   9824: 
                   9825: =item *
1.394     bowersj2 9826: X<userenvironment()>
                   9827: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 9828: passed in @what from the requested user's environment, returns a hash
                   9829: 
1.858     raeburn  9830: =item * 
                   9831: X<userlog_query()>
1.859     albertel 9832: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   9833: activity.log file. %filters defines filters applied when parsing the
                   9834: log file. These can be start or end timestamps, or the type of action
                   9835: - log to look for Login or Logout events, check for Checkin or
                   9836: Checkout, role for role selection. The response is in the form
                   9837: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   9838: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  9839: 
1.243     albertel 9840: =back
                   9841: 
                   9842: =head2 User Roles
                   9843: 
                   9844: =over 4
                   9845: 
                   9846: =item *
                   9847: 
1.810     raeburn  9848: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 9849:  F: full access
                   9850:  U,I,K: authentication modes (cxx only)
                   9851:  '': forbidden
                   9852:  1: user needs to choose course
                   9853:  2: browse allowed
1.766     albertel 9854:  A: passphrase authentication needed
1.243     albertel 9855: 
                   9856: =item *
                   9857: 
                   9858: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   9859: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   9860: and course level
                   9861: 
                   9862: =item *
                   9863: 
1.988     raeburn  9864: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   9865: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  9866: $type is Course (default) or Community.
1.988     raeburn  9867: If $forcedefault evaluates to true, text returned will be default 
                   9868: text for $type. Otherwise, if this is a course, the text returned 
                   9869: will be a custom name for the role (if defined in the course's 
                   9870: environment).  If no custom name is defined the default is returned.
                   9871:    
1.832     raeburn  9872: =item *
                   9873: 
1.935     raeburn  9874: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  9875: All arguments are optional. Returns a hash of a roles, either for
                   9876: co-author/assistant author roles for a user's Construction Space
1.906     albertel 9877: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  9878: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   9879: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   9880: For each key, value is set to colon-separated start and end times for
                   9881: the role.  If no username and domain are specified, will default to
1.934     raeburn  9882: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  9883: of role statuses (active, future or previous), roles 
                   9884: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   9885: to restrict the list of roles reported. If no array ref is 
                   9886: provided for types, will default to return only active roles.
1.834     albertel 9887: 
1.243     albertel 9888: =back
                   9889: 
                   9890: =head2 User Modification
                   9891: 
                   9892: =over 4
                   9893: 
                   9894: =item *
                   9895: 
1.957     raeburn  9896: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 9897: user for the level given by URL.  Optional start and end dates (leave empty
                   9898: string or zero for "no date")
1.191     harris41 9899: 
                   9900: =item *
                   9901: 
1.243     albertel 9902: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   9903: change a users, password, possible return values are: ok,
                   9904: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   9905: refused
1.191     harris41 9906: 
                   9907: =item *
                   9908: 
1.243     albertel 9909: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9910: 
                   9911: =item *
                   9912: 
1.963     raeburn  9913: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
                   9914:            $forceid,$desiredhome,$email,$inststatus) : 
1.243     albertel 9915: modify user
1.191     harris41 9916: 
                   9917: =item *
                   9918: 
1.286     matthew  9919: modifystudent
                   9920: 
1.957     raeburn  9921: modify a student's enrollment and identification information.
1.286     matthew  9922: The course id is resolved based on the current users environment.  
                   9923: This means the envoking user must be a course coordinator or otherwise
                   9924: associated with a course.
                   9925: 
1.297     matthew  9926: This call is essentially a wrapper for lonnet::modifyuser and
                   9927: lonnet::modify_student_enrollment
1.286     matthew  9928: 
                   9929: Inputs: 
                   9930: 
                   9931: =over 4
                   9932: 
1.957     raeburn  9933: =item B<$udom> Student's loncapa domain
1.286     matthew  9934: 
1.957     raeburn  9935: =item B<$uname> Student's loncapa login name
1.286     matthew  9936: 
1.964     bisitz   9937: =item B<$uid> Student/Employee ID
1.286     matthew  9938: 
1.957     raeburn  9939: =item B<$umode> Student's authentication mode
1.286     matthew  9940: 
1.957     raeburn  9941: =item B<$upass> Student's password
1.286     matthew  9942: 
1.957     raeburn  9943: =item B<$first> Student's first name
1.286     matthew  9944: 
1.957     raeburn  9945: =item B<$middle> Student's middle name
1.286     matthew  9946: 
1.957     raeburn  9947: =item B<$last> Student's last name
1.286     matthew  9948: 
1.957     raeburn  9949: =item B<$gene> Student's generation
1.286     matthew  9950: 
1.957     raeburn  9951: =item B<$usec> Student's section in course
1.286     matthew  9952: 
                   9953: =item B<$end> Unix time of the roles expiration
                   9954: 
                   9955: =item B<$start> Unix time of the roles start date
                   9956: 
                   9957: =item B<$forceid> If defined, allow $uid to be changed
                   9958: 
                   9959: =item B<$desiredhome> server to use as home server for student
                   9960: 
1.957     raeburn  9961: =item B<$email> Student's permanent e-mail address
                   9962: 
                   9963: =item B<$type> Type of enrollment (auto or manual)
                   9964: 
1.963     raeburn  9965: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   9966: 
                   9967: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  9968: 
1.963     raeburn  9969: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  9970: 
1.963     raeburn  9971: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  9972: 
1.963     raeburn  9973: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  9974: 
1.286     matthew  9975: =back
1.297     matthew  9976: 
                   9977: =item *
                   9978: 
                   9979: modify_student_enrollment
                   9980: 
                   9981: Change a students enrollment status in a class.  The environment variable
                   9982: 'role.request.course' must be defined for this function to proceed.
                   9983: 
                   9984: Inputs:
                   9985: 
                   9986: =over 4
                   9987: 
                   9988: =item $udom, students domain
                   9989: 
                   9990: =item $uname, students name
                   9991: 
                   9992: =item $uid, students user id
                   9993: 
                   9994: =item $first, students first name
                   9995: 
                   9996: =item $middle
                   9997: 
                   9998: =item $last
                   9999: 
                   10000: =item $gene
                   10001: 
                   10002: =item $usec
                   10003: 
                   10004: =item $end
                   10005: 
                   10006: =item $start
                   10007: 
1.957     raeburn  10008: =item $type
                   10009: 
                   10010: =item $locktype
                   10011: 
                   10012: =item $cid
                   10013: 
                   10014: =item $selfenroll
                   10015: 
                   10016: =item $context
                   10017: 
1.297     matthew  10018: =back
                   10019: 
1.191     harris41 10020: 
                   10021: =item *
                   10022: 
1.243     albertel 10023: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   10024: custom role; give a custom role to a user for the level given by URL.  Specify
                   10025: name and domain of role author, and role name
1.191     harris41 10026: 
                   10027: =item *
                   10028: 
1.243     albertel 10029: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 10030: 
                   10031: =item *
                   10032: 
1.243     albertel 10033: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   10034: 
                   10035: =back
                   10036: 
                   10037: =head2 Course Infomation
                   10038: 
                   10039: =over 4
1.191     harris41 10040: 
                   10041: =item *
                   10042: 
1.631     albertel 10043: coursedescription($courseid) : returns a hash of information about the
                   10044: specified course id, including all environment settings for the
                   10045: course, the description of the course will be in the hash under the
                   10046: key 'description'
1.191     harris41 10047: 
                   10048: =item *
                   10049: 
1.624     albertel 10050: resdata($name,$domain,$type,@which) : request for current parameter
                   10051: setting for a specific $type, where $type is either 'course' or 'user',
                   10052: @what should be a list of parameters to ask about. This routine caches
                   10053: answers for 5 minutes.
1.243     albertel 10054: 
1.877     foxr     10055: =item *
                   10056: 
                   10057: get_courseresdata($courseid, $domain) : dump the entire course resource
                   10058: data base, returning a hash that is keyed by the resource name and has
                   10059: values that are the resource value.  I believe that the timestamps and
                   10060: versions are also returned.
                   10061: 
                   10062: 
1.243     albertel 10063: =back
                   10064: 
                   10065: =head2 Course Modification
                   10066: 
                   10067: =over 4
1.191     harris41 10068: 
                   10069: =item *
                   10070: 
1.243     albertel 10071: writecoursepref($courseid,%prefs) : write preferences (environment
                   10072: database) for a course
1.191     harris41 10073: 
                   10074: =item *
                   10075: 
1.1011    raeburn  10076: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   10077: 
                   10078: =item *
                   10079: 
                   10080: generate_coursenum($udom) : get a unique (unused) course number in domain $udom
1.243     albertel 10081: 
                   10082: =back
                   10083: 
                   10084: =head2 Resource Subroutines
                   10085: 
                   10086: =over 4
1.191     harris41 10087: 
                   10088: =item *
                   10089: 
1.243     albertel 10090: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 10091: 
                   10092: =item *
                   10093: 
1.243     albertel 10094: repcopy($filename) : subscribes to the requested file, and attempts to
                   10095: replicate from the owning library server, Might return
1.607     raeburn  10096: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   10097: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 10098: resource. Expects the local filesystem pathname
                   10099: (/home/httpd/html/res/....)
                   10100: 
                   10101: =back
                   10102: 
                   10103: =head2 Resource Information
                   10104: 
                   10105: =over 4
1.191     harris41 10106: 
                   10107: =item *
                   10108: 
1.243     albertel 10109: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   10110: a vairety of different possible values, $varname should be a request
                   10111: string, and the other parameters can be used to specify who and what
                   10112: one is asking about.
                   10113: 
                   10114: Possible values for $varname are environment.lastname (or other item
                   10115: from the envirnment hash), user.name (or someother aspect about the
                   10116: user), resource.0.maxtries (or some other part and parameter of a
                   10117: resource)
1.204     albertel 10118: 
                   10119: =item *
                   10120: 
1.243     albertel 10121: directcondval($number) : get current value of a condition; reads from a state
                   10122: string
1.204     albertel 10123: 
                   10124: =item *
                   10125: 
1.243     albertel 10126: condval($condidx) : value of condition index based on state
1.204     albertel 10127: 
                   10128: =item *
                   10129: 
1.243     albertel 10130: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   10131: resource's metadata, $what should be either a specific key, or either
                   10132: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   10133: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   10134: 
                   10135: this function automatically caches all requests
1.191     harris41 10136: 
                   10137: =item *
                   10138: 
1.243     albertel 10139: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   10140: network of library servers; returns file handle of where SQL and regex results
                   10141: will be stored for query
1.191     harris41 10142: 
                   10143: =item *
                   10144: 
1.243     albertel 10145: symbread($filename) : return symbolic list entry (filename argument optional);
                   10146: returns the data handle
1.191     harris41 10147: 
                   10148: =item *
                   10149: 
1.243     albertel 10150: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 10151: a possible symb for the URL in $thisfn, and if is an encryypted
                   10152: resource that the user accessed using /enc/ returns a 1 on success, 0
                   10153: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 10154: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 10155: 
1.191     harris41 10156: 
                   10157: =item *
                   10158: 
1.243     albertel 10159: symbclean($symb) : removes versions numbers from a symb, returns the
                   10160: cleaned symb
1.191     harris41 10161: 
                   10162: =item *
                   10163: 
1.243     albertel 10164: is_on_map($uri) : checks if the $uri is somewhere on the current
                   10165: course map, user must be in a course for it to work.
1.191     harris41 10166: 
                   10167: =item *
                   10168: 
1.243     albertel 10169: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 10170: 
                   10171: =item *
                   10172: 
1.243     albertel 10173: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   10174: a random seed, all arguments are optional, if they aren't sent it uses the
                   10175: environment to derive them. Note: if symb isn't sent and it can't get one
                   10176: from &symbread it will use the current time as its return value
1.191     harris41 10177: 
                   10178: =item *
                   10179: 
1.243     albertel 10180: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   10181: unfakeable, receipt
1.191     harris41 10182: 
                   10183: =item *
                   10184: 
1.620     albertel 10185: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 10186: 
                   10187: =item *
                   10188: 
1.243     albertel 10189: countacc($url) : count the number of accesses to a given URL
1.191     harris41 10190: 
                   10191: =item *
                   10192: 
1.243     albertel 10193: 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 10194: 
                   10195: =item *
                   10196: 
1.243     albertel 10197: 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 10198: 
                   10199: =item *
                   10200: 
1.243     albertel 10201: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 10202: 
                   10203: =item *
                   10204: 
1.243     albertel 10205: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   10206: forcing spreadsheet to reevaluate the resource scores next time.
                   10207: 
                   10208: =back
                   10209: 
                   10210: =head2 Storing/Retreiving Data
                   10211: 
                   10212: =over 4
1.191     harris41 10213: 
                   10214: =item *
                   10215: 
1.243     albertel 10216: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   10217: for this url; hashref needs to be given and should be a \%hashname; the
                   10218: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 10219: be derived from the env
1.191     harris41 10220: 
                   10221: =item *
                   10222: 
1.243     albertel 10223: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   10224: uses critical subroutine
1.191     harris41 10225: 
                   10226: =item *
                   10227: 
1.243     albertel 10228: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   10229: all args are optional
1.191     harris41 10230: 
                   10231: =item *
                   10232: 
1.717     albertel 10233: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   10234: dumps the complete (or key matching regexp) namespace into a hash
                   10235: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   10236: normally &store()ed into
                   10237: 
                   10238: $range should be either an integer '100' (give me the first 100
                   10239:                                            matching records)
                   10240:               or be  two integers sperated by a - with no spaces
                   10241:                  '30-50' (give me the 30th through the 50th matching
                   10242:                           records)
                   10243: 
                   10244: 
                   10245: =item *
                   10246: 
                   10247: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   10248: replaces a &store() version of data with a replacement set of data
                   10249: for a particular resource in a namespace passed in the $storehash hash 
                   10250: reference
                   10251: 
                   10252: =item *
                   10253: 
1.243     albertel 10254: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   10255: works very similar to store/cstore, but all data is stored in a
                   10256: temporary location and can be reset using tmpreset, $storehash should
                   10257: be a hash reference, returns nothing on success
1.191     harris41 10258: 
                   10259: =item *
                   10260: 
1.243     albertel 10261: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   10262: similar to restore, but all data is stored in a temporary location and
                   10263: can be reset using tmpreset. Returns a hash of values on success,
                   10264: error string otherwise.
1.191     harris41 10265: 
                   10266: =item *
                   10267: 
1.243     albertel 10268: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   10269: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 10270: 
                   10271: =item *
                   10272: 
1.243     albertel 10273: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   10274: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 10275: 
                   10276: =item *
                   10277: 
1.243     albertel 10278: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   10279: namesp ($udom and $uname are optional)
1.191     harris41 10280: 
                   10281: =item *
                   10282: 
1.702     albertel 10283: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 10284: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 10285: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  10286: 
1.702     albertel 10287: $range should be either an integer '100' (give me the first 100
                   10288:                                            matching records)
                   10289:               or be  two integers sperated by a - with no spaces
                   10290:                  '30-50' (give me the 30th through the 50th matching
                   10291:                           records)
1.449     matthew  10292: =item *
                   10293: 
                   10294: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   10295: $store can be a scalar, an array reference, or if the amount to be 
                   10296: incremented is > 1, a hash reference.
                   10297: 
                   10298: ($udom and $uname are optional)
1.191     harris41 10299: 
                   10300: =item *
                   10301: 
1.243     albertel 10302: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   10303: ($udom and $uname are optional)
1.191     harris41 10304: 
                   10305: =item *
                   10306: 
1.243     albertel 10307: cput($namespace,$storehash,$udom,$uname) : critical put
                   10308: ($udom and $uname are optional)
1.191     harris41 10309: 
                   10310: =item *
                   10311: 
1.748     albertel 10312: newput($namespace,$storehash,$udom,$uname) :
                   10313: 
                   10314: Attempts to store the items in the $storehash, but only if they don't
                   10315: currently exist, if this succeeds you can be certain that you have 
                   10316: successfully created a new key value pair in the $namespace db.
                   10317: 
                   10318: 
                   10319: Args:
                   10320:  $namespace: name of database to store values to
                   10321:  $storehash: hashref to store to the db
                   10322:  $udom: (optional) domain of user containing the db
                   10323:  $uname: (optional) name of user caontaining the db
                   10324: 
                   10325: Returns:
                   10326:  'ok' -> succeeded in storing all keys of $storehash
                   10327:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   10328:                         least <key> already existed in the db (other
                   10329:                         requested keys may also already exist)
1.967     bisitz   10330:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 10331:  'con_lost' -> unable to contact request server
                   10332:  'refused' -> action was not allowed by remote machine
                   10333: 
                   10334: 
                   10335: =item *
                   10336: 
1.243     albertel 10337: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   10338: reference filled in from namesp (encrypts the return communication)
                   10339: ($udom and $uname are optional)
1.191     harris41 10340: 
                   10341: =item *
                   10342: 
1.243     albertel 10343: log($udom,$name,$home,$message) : write to permanent log for user; use
                   10344: critical subroutine
                   10345: 
1.806     raeburn  10346: =item *
                   10347: 
1.860     raeburn  10348: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   10349: array reference filled in from namespace found in domain level on either
                   10350: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  10351: 
                   10352: =item *
                   10353: 
1.860     raeburn  10354: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   10355: domain level either on specified domain server ($uhome) or primary domain 
                   10356: server ($udom and $uhome are optional)
1.806     raeburn  10357: 
1.943     raeburn  10358: =item * 
                   10359: 
                   10360: get_domain_defaults($target_domain) : returns hash with defaults for
                   10361: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   10362: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   10363: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   10364: Values are retrieved from cache (if current), or from domain's configuration.db
                   10365: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   10366: or lonTabs/domain.tab. 
                   10367: 
                   10368: %domdefaults = &get_auth_defaults($target_domain);
                   10369: 
1.243     albertel 10370: =back
                   10371: 
                   10372: =head2 Network Status Functions
                   10373: 
                   10374: =over 4
1.191     harris41 10375: 
                   10376: =item *
                   10377: 
                   10378: dirlist($uri) : return directory list based on URI
                   10379: 
                   10380: =item *
                   10381: 
1.243     albertel 10382: spareserver() : find server with least workload from spare.tab
                   10383: 
1.986     foxr     10384: 
                   10385: =item *
                   10386: 
                   10387: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   10388: if there is no corresponding loncapa host.
                   10389: 
1.243     albertel 10390: =back
                   10391: 
1.986     foxr     10392: 
1.243     albertel 10393: =head2 Apache Request
                   10394: 
                   10395: =over 4
1.191     harris41 10396: 
                   10397: =item *
                   10398: 
1.243     albertel 10399: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   10400: localhost, posts hash
                   10401: 
                   10402: =back
                   10403: 
                   10404: =head2 Data to String to Data
                   10405: 
                   10406: =over 4
1.191     harris41 10407: 
                   10408: =item *
                   10409: 
1.243     albertel 10410: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   10411: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 10412: 
                   10413: =item *
                   10414: 
1.243     albertel 10415: hashref2str($hashref) : convert a hashref into a string complete with
                   10416: escaping and '=' and '&' separators, supports elements that are
                   10417: arrayrefs and hashrefs
1.191     harris41 10418: 
                   10419: =item *
                   10420: 
1.243     albertel 10421: arrayref2str($arrayref) : convert an arrayref into a string complete
                   10422: with escaping and '&' separators, supports elements that are arrayrefs
                   10423: and hashrefs
1.191     harris41 10424: 
                   10425: =item *
                   10426: 
1.243     albertel 10427: str2hash($string) : convert string to hash using unescaping and
                   10428: splitting on '=' and '&', supports elements that are arrayrefs and
                   10429: hashrefs
1.191     harris41 10430: 
                   10431: =item *
                   10432: 
1.243     albertel 10433: str2array($string) : convert string to hash using unescaping and
                   10434: splitting on '&', supports elements that are arrayrefs and hashrefs
                   10435: 
                   10436: =back
                   10437: 
                   10438: =head2 Logging Routines
                   10439: 
                   10440: =over 4
                   10441: 
                   10442: These routines allow one to make log messages in the lonnet.log and
                   10443: lonnet.perm logfiles.
1.191     harris41 10444: 
                   10445: =item *
                   10446: 
1.243     albertel 10447: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 10448: 
                   10449: =item *
                   10450: 
1.243     albertel 10451: logthis() : append message to the normal lonnet.log file, it gets
                   10452: preiodically rolled over and deleted.
1.191     harris41 10453: 
                   10454: =item *
                   10455: 
1.243     albertel 10456: logperm() : append a permanent message to lonnet.perm.log, this log
                   10457: file never gets deleted by any automated portion of the system, only
                   10458: messages of critical importance should go in here.
                   10459: 
                   10460: =back
                   10461: 
                   10462: =head2 General File Helper Routines
                   10463: 
                   10464: =over 4
1.191     harris41 10465: 
                   10466: =item *
                   10467: 
1.481     raeburn  10468: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   10469: (a) files in /uploaded
                   10470:   (i) If a local copy of the file exists - 
                   10471:       compares modification date of local copy with last-modified date for 
                   10472:       definitive version stored on home server for course. If local copy is 
                   10473:       stale, requests a new version from the home server and stores it. 
                   10474:       If the original has been removed from the home server, then local copy 
                   10475:       is unlinked.
                   10476:   (ii) If local copy does not exist -
                   10477:       requests the file from the home server and stores it. 
                   10478:   
                   10479:   If $caller is 'uploadrep':  
                   10480:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   10481:     for request for files originally uploaded via DOCS. 
                   10482:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   10483:   
                   10484:   Otherwise:
                   10485:      This indicates a call from the content generation phase of the request.
                   10486:      -  returns the entire contents of the file or -1.
                   10487:      
                   10488: (b) files in /res
                   10489:    - returns the entire contents of a file or -1; 
                   10490:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 10491: 
1.712     albertel 10492: 
                   10493: =item *
                   10494: 
                   10495: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   10496:                   reference
                   10497: 
                   10498: returns either a stat() list of data about the file or an empty list
                   10499: if the file doesn't exist or couldn't find out about it (connection
                   10500: problems or user unknown)
                   10501: 
1.191     harris41 10502: =item *
                   10503: 
1.243     albertel 10504: filelocation($dir,$file) : returns file system location of a file
                   10505: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   10506: directory that relative $file lookups are to looked in ($dir of /a/dir
                   10507: and a file of ../bob will become /a/bob)
1.191     harris41 10508: 
                   10509: =item *
                   10510: 
                   10511: hreflocation($dir,$file) : returns file system location or a URL; same as
                   10512: filelocation except for hrefs
                   10513: 
                   10514: =item *
                   10515: 
                   10516: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   10517: 
1.243     albertel 10518: =back
                   10519: 
1.608     albertel 10520: =head2 Usererfile file routines (/uploaded*)
                   10521: 
                   10522: =over 4
                   10523: 
                   10524: =item *
                   10525: 
                   10526: userfileupload(): main rotine for putting a file in a user or course's
                   10527:                   filespace, arguments are,
                   10528: 
1.620     albertel 10529:  formname - required - this is the name of the element in $env where the
1.608     albertel 10530:            filename, and the contents of the file to create/modifed exist
1.620     albertel 10531:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   10532:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 10533:  coursedoc - if true, store the file in the course of the active role
                   10534:              of the current user
                   10535:  subdir - required - subdirectory to put the file in under ../userfiles/
                   10536:          if undefined, it will be placed in "unknown"
                   10537: 
                   10538:  (This routine calls clean_filename() to remove any dangerous
                   10539:  characters from the filename, and then calls finuserfileupload() to
                   10540:  complete the transaction)
                   10541: 
                   10542:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10543:  and /adm/notfound.html if unsuccessful
                   10544: 
                   10545: =item *
                   10546: 
                   10547: clean_filename(): routine for cleaing a filename up for storage in
                   10548:                  userfile space, argument is:
                   10549: 
                   10550:  filename - proposed filename
                   10551: 
                   10552: returns: the new clean filename
                   10553: 
                   10554: =item *
                   10555: 
                   10556: finishuserfileupload(): routine that creaes and sends the file to
                   10557: userspace, probably shouldn't be called directly
                   10558: 
                   10559:   docuname: username or courseid of destination for the file
                   10560:   docudom: domain of user/course of destination for the file
                   10561:   formname: same as for userfileupload()
                   10562:   fname: filename (inculding subdirectories) for the file
                   10563: 
                   10564:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10565:  and /adm/notfound.html if unsuccessful
                   10566: 
                   10567: =item *
                   10568: 
                   10569: renameuserfile(): renames an existing userfile to a new name
                   10570: 
                   10571:   Args:
                   10572:    docuname: username or courseid of destination for the file
                   10573:    docudom: domain of user/course of destination for the file
                   10574:    old: current file name (including any subdirs under userfiles)
                   10575:    new: desired file name (including any subdirs under userfiles)
                   10576: 
                   10577: =item *
                   10578: 
                   10579: mkdiruserfile(): creates a directory is a userfiles dir
                   10580: 
                   10581:   Args:
                   10582:    docuname: username or courseid of destination for the file
                   10583:    docudom: domain of user/course of destination for the file
                   10584:    dir: dir to create (including any subdirs under userfiles)
                   10585: 
                   10586: =item *
                   10587: 
                   10588: removeuserfile(): removes a file that exists in userfiles
                   10589: 
                   10590:   Args:
                   10591:    docuname: username or courseid of destination for the file
                   10592:    docudom: domain of user/course of destination for the file
                   10593:    fname: filname to delete (including any subdirs under userfiles)
                   10594: 
                   10595: =item *
                   10596: 
                   10597: removeuploadedurl(): convience function for removeuserfile()
                   10598: 
                   10599:   Args:
                   10600:    url:  a full /uploaded/... url to delete
                   10601: 
1.747     albertel 10602: =item * 
                   10603: 
                   10604: get_portfile_permissions():
                   10605:   Args:
                   10606:     domain: domain of user or course contain the portfolio files
                   10607:     user: name of user or num of course contain the portfolio files
                   10608:   Returns:
                   10609:     hashref of a dump of the proper file_permissions.db
                   10610:    
                   10611: 
                   10612: =item * 
                   10613: 
                   10614: get_access_controls():
                   10615: 
                   10616: Args:
                   10617:   current_permissions: the hash ref returned from get_portfile_permissions()
                   10618:   group: (optional) the group you want the files associated with
                   10619:   file: (optional) the file you want access info on
                   10620: 
                   10621: Returns:
1.749     raeburn  10622:     a hash (keys are file names) of hashes containing
                   10623:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   10624:         values are XML containing access control settings (see below) 
1.747     albertel 10625: 
                   10626: Internal notes:
                   10627: 
1.749     raeburn  10628:  access controls are stored in file_permissions.db as key=value pairs.
                   10629:     key -> path to file/file_name\0uniqueID:scope_end_start
                   10630:         where scope -> public,guest,course,group,domains or users.
                   10631:               end -> UNIX time for end of access (0 -> no end date)
                   10632:               start -> UNIX time for start of access
                   10633: 
                   10634:     value -> XML description of access control
                   10635:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   10636:             <start></start>
                   10637:             <end></end>
                   10638: 
                   10639:             <password></password>  for scope type = guest
                   10640: 
                   10641:             <domain></domain>     for scope type = course or group
                   10642:             <number></number>
                   10643:             <roles id="">
                   10644:              <role></role>
                   10645:              <access></access>
                   10646:              <section></section>
                   10647:              <group></group>
                   10648:             </roles>
                   10649: 
                   10650:             <dom></dom>         for scope type = domains
                   10651: 
                   10652:             <users>             for scope type = users
                   10653:              <user>
                   10654:               <uname></uname>
                   10655:               <udom></udom>
                   10656:              </user>
                   10657:             </users>
                   10658:            </scope> 
                   10659:               
                   10660:  Access data is also aggregated for each file in an additional key=value pair:
                   10661:  key -> path to file/file_name\0accesscontrol 
                   10662:  value -> reference to hash
                   10663:           hash contains key = value pairs
                   10664:           where key = uniqueID:scope_end_start
                   10665:                 value = UNIX time record was last updated
                   10666: 
                   10667:           Used to improve speed of look-ups of access controls for each file.  
                   10668:  
                   10669:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   10670: 
                   10671: modify_access_controls():
                   10672: 
                   10673: Modifies access controls for a portfolio file
                   10674: Args
                   10675: 1. file name
                   10676: 2. reference to hash of required changes,
                   10677: 3. domain
                   10678: 4. username
                   10679:   where domain,username are the domain of the portfolio owner 
                   10680:   (either a user or a course) 
                   10681: 
                   10682: Returns:
                   10683: 1. result of additions or updates ('ok' or 'error', with error message). 
                   10684: 2. result of deletions ('ok' or 'error', with error message).
                   10685: 3. reference to hash of any new or updated access controls.
                   10686: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   10687:    key = integer (inbound ID)
                   10688:    value = uniqueID  
1.747     albertel 10689: 
1.608     albertel 10690: =back
                   10691: 
1.243     albertel 10692: =head2 HTTP Helper Routines
                   10693: 
                   10694: =over 4
                   10695: 
1.191     harris41 10696: =item *
                   10697: 
                   10698: escape() : unpack non-word characters into CGI-compatible hex codes
                   10699: 
                   10700: =item *
                   10701: 
                   10702: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   10703: 
1.243     albertel 10704: =back
                   10705: 
                   10706: =head1 PRIVATE SUBROUTINES
                   10707: 
                   10708: =head2 Underlying communication routines (Shouldn't call)
                   10709: 
                   10710: =over 4
                   10711: 
                   10712: =item *
                   10713: 
                   10714: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   10715: 
                   10716: =item *
                   10717: 
                   10718: reply() : uses subreply to send a message to remote machine, logs all failures
                   10719: 
                   10720: =item *
                   10721: 
                   10722: critical() : passes a critical message to another server; if cannot
                   10723: get through then place message in connection buffer directory and
                   10724: returns con_delayed, if incapable of saving message, returns
                   10725: con_failed
                   10726: 
                   10727: =item *
                   10728: 
                   10729: reconlonc() : tries to reconnect lonc client processes.
                   10730: 
                   10731: =back
                   10732: 
                   10733: =head2 Resource Access Logging
                   10734: 
                   10735: =over 4
                   10736: 
                   10737: =item *
                   10738: 
                   10739: flushcourselogs() : flush (save) buffer logs and access logs
                   10740: 
                   10741: =item *
                   10742: 
                   10743: courselog($what) : save message for course in hash
                   10744: 
                   10745: =item *
                   10746: 
                   10747: courseacclog($what) : save message for course using &courselog().  Perform
                   10748: special processing for specific resource types (problems, exams, quizzes, etc).
                   10749: 
1.191     harris41 10750: =item *
                   10751: 
                   10752: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   10753: as a PerlChildExitHandler
1.243     albertel 10754: 
                   10755: =back
                   10756: 
                   10757: =head2 Other
                   10758: 
                   10759: =over 4
                   10760: 
                   10761: =item *
                   10762: 
                   10763: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 10764: 
                   10765: =back
                   10766: 
                   10767: =cut
1.877     foxr     10768: 

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