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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1056.4.10! raeburn     4: # $Id: lonnet.pm,v 1.1056.4.9 2010/09/24 03:35:42 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.1056.4.5  raeburn    79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease);
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.1024    raeburn    95: use File::MMagic;
1.807     albertel   96: use LONCAPA qw(:DEFAULT :match);
1.740     www        97: use LONCAPA::Configuration;
1.676     albertel   98: 
1.195     www        99: my $readit;
1.550     foxr      100: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  101: 
1.619     albertel  102: require Exporter;
                    103: 
                    104: our @ISA = qw (Exporter);
                    105: our @EXPORT = qw(%env);
                    106: 
1.449     matthew   107: 
1.1       albertel  108: # --------------------------------------------------------------------- Logging
1.729     www       109: {
                    110:     my $logid;
                    111:     sub instructor_log {
1.957     raeburn   112: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    113:         if (($cnum eq '') || ($cdom eq '')) {
                    114:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    115:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    116:         }
1.729     www       117: 	$logid++;
1.957     raeburn   118:         my $now = time();
                    119: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       120: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       121: 				    { $id => {
                    122: 					'exe_uname' => $env{'user.name'},
                    123: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   124: 					'exe_time'  => $now,
1.730     www       125: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    126: 					'delflag'   => $delflag,
                    127: 					'logentry'  => $storehash,
                    128: 					'uname'     => $uname,
                    129: 					'udom'      => $udom,
                    130: 				    }
1.957     raeburn   131: 				  },$cdom,$cnum);
1.729     www       132:     }
                    133: }
1.1       albertel  134: 
1.163     harris41  135: sub logtouch {
                    136:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  137:     unless (-e "$execdir/logs/lonnet.log") {	
                    138: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  139: 	close $fh;
                    140:     }
                    141:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    142:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    143: }
                    144: 
1.1       albertel  145: sub logthis {
                    146:     my $message=shift;
                    147:     my $execdir=$perlvar{'lonDaemons'};
                    148:     my $now=time;
                    149:     my $local=localtime($now);
1.448     albertel  150:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      151: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    152: 	print $fh $logstring;
1.448     albertel  153: 	close($fh);
                    154:     }
1.1       albertel  155:     return 1;
                    156: }
                    157: 
                    158: sub logperm {
                    159:     my $message=shift;
                    160:     my $execdir=$perlvar{'lonDaemons'};
                    161:     my $now=time;
                    162:     my $local=localtime($now);
1.448     albertel  163:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    164: 	print $fh "$now:$message:$local\n";
                    165: 	close($fh);
                    166:     }
1.1       albertel  167:     return 1;
                    168: }
                    169: 
1.850     albertel  170: sub create_connection {
1.853     albertel  171:     my ($hostname,$lonid) = @_;
1.851     albertel  172:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  173: 				     Type    => SOCK_STREAM,
                    174: 				     Timeout => 10);
                    175:     return 0 if (!$client);
1.890     albertel  176:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  177:     my $result = <$client>;
                    178:     chomp($result);
                    179:     return 1 if ($result eq 'done');
                    180:     return 0;
                    181: }
                    182: 
1.983     raeburn   183: sub get_server_timezone {
                    184:     my ($cnum,$cdom) = @_;
                    185:     my $home=&homeserver($cnum,$cdom);
                    186:     if ($home ne 'no_host') {
                    187:         my $cachetime = 24*3600;
                    188:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    189:         if (defined($cached)) {
                    190:             return $timezone;
                    191:         } else {
                    192:             my $timezone = &reply('servertimezone',$home);
                    193:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    194:         }
                    195:     }
                    196: }
1.850     albertel  197: 
1.993     raeburn   198: sub get_server_loncaparev {
1.1056.4.3  raeburn   199:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   200:     if (defined($lonhost)) {
                    201:         if (!defined(&hostname($lonhost))) {
                    202:             undef($lonhost);
                    203:         }
                    204:     }
                    205:     if (!defined($lonhost)) {
                    206:         if (defined(&domain($dom,'primary'))) {
                    207:             $lonhost=&domain($dom,'primary');
                    208:             if ($lonhost eq 'no_host') {
                    209:                 undef($lonhost);
                    210:             }
                    211:         }
                    212:     }
                    213:     if (defined($lonhost)) {
1.1056.4.3  raeburn   214:         my $cachetime = 12*3600;
                    215:         if (!$ignore_cache) {
                    216:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    217:             if (defined($cached)) {
                    218:                 return $loncaparev;
                    219:             }
                    220:         }
                    221:         my ($answer,$loncaparev);
                    222:         my @ids=&current_machine_ids();
                    223:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    224:             $answer = $perlvar{'lonVersion'};
1.1056.4.7  raeburn   225:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1056.4.3  raeburn   226:                 $loncaparev = $1;
                    227:             }
                    228:         } else {
                    229:             $answer = &reply('serverloncaparev',$lonhost);
                    230:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    231:                 if ($caller eq 'loncron') {
                    232:                     my $ua=new LWP::UserAgent;
1.1056.4.8  raeburn   233:                     $ua->timeout(4);
1.1056.4.3  raeburn   234:                     my $protocol = $protocol{$lonhost};
                    235:                     $protocol = 'http' if ($protocol ne 'https');
                    236:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    237:                     my $request=new HTTP::Request('GET',$url);
                    238:                     my $response=$ua->request($request);
                    239:                     unless ($response->is_error()) {
                    240:                         my $content = $response->content;
1.1056.4.7  raeburn   241:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1056.4.3  raeburn   242:                             $loncaparev = $1;
                    243:                         }
                    244:                     }
                    245:                 } else {
                    246:                     $loncaparev = $loncaparevs{$lonhost};
                    247:                 }
1.1056.4.7  raeburn   248:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1056.4.3  raeburn   249:                 $loncaparev = $1;
                    250:             }
                    251:         }
                    252:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
                    253:     }
                    254: }
                    255: 
                    256: sub get_server_homeID {
                    257:     my ($hostname,$ignore_cache,$caller) = @_;
                    258:     unless ($ignore_cache) {
                    259:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
1.993     raeburn   260:         if (defined($cached)) {
1.1056.4.3  raeburn   261:             return $serverhomeID;
                    262:         }
                    263:     }
                    264:     my $cachetime = 12*3600;
                    265:     my $serverhomeID;
                    266:     if ($caller eq 'loncron') {
                    267:         my @machine_ids = &machine_ids($hostname);
                    268:         foreach my $id (@machine_ids) {
                    269:             my $response = &reply('serverhomeID',$id);
                    270:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    271:                 $serverhomeID = $response;
                    272:                 last;
                    273:             }
1.993     raeburn   274:         }
1.1056.4.3  raeburn   275:         if ($serverhomeID eq '') {
                    276:             $serverhomeID = $machine_ids[-1];
                    277:         }
                    278:     } else {
                    279:         $serverhomeID = $serverhomeIDs{$hostname};
1.993     raeburn   280:     }
1.1056.4.3  raeburn   281:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
1.993     raeburn   282: }
                    283: 
1.1       albertel  284: # -------------------------------------------------- Non-critical communication
                    285: sub subreply {
                    286:     my ($cmd,$server)=@_;
1.838     albertel  287:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      288:     #
                    289:     #  With loncnew process trimming, there's a timing hole between lonc server
                    290:     #  process exit and the master server picking up the listen on the AF_UNIX
                    291:     #  socket.  In that time interval, a lock file will exist:
                    292: 
                    293:     my $lockfile=$peerfile.".lock";
                    294:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    295: 	sleep(1);
                    296:     }
                    297:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      298:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      299:     #
1.550     foxr      300:     #   We'll give the connection a few tries before abandoning it.  If
                    301:     #   connection is not possible, we'll con_lost back to the client.
                    302:     #   
                    303:     my $client;
                    304:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    305: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    306: 				      Type    => SOCK_STREAM,
                    307: 				      Timeout => 10);
1.869     albertel  308: 	if ($client) {
1.550     foxr      309: 	    last;		# Connected!
1.850     albertel  310: 	} else {
1.853     albertel  311: 	    &create_connection(&hostname($server),$server);
1.550     foxr      312: 	}
1.850     albertel  313:         sleep(1);		# Try again later if failed connection.
1.550     foxr      314:     }
                    315:     my $answer;
                    316:     if ($client) {
1.704     albertel  317: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      318: 	$answer=<$client>;
                    319: 	if (!$answer) { $answer="con_lost"; }
                    320: 	chomp($answer);
                    321:     } else {
                    322: 	$answer = 'con_lost';	# Failed connection.
                    323:     }
1.1       albertel  324:     return $answer;
                    325: }
                    326: 
                    327: sub reply {
                    328:     my ($cmd,$server)=@_;
1.838     albertel  329:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  330:     my $answer=subreply($cmd,$server);
1.65      www       331:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  332:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       333:                 " $cmd to $server returned $answer</font>");
                    334:     }
1.1       albertel  335:     return $answer;
                    336: }
                    337: 
                    338: # ----------------------------------------------------------- Send USR1 to lonc
                    339: 
                    340: sub reconlonc {
1.891     albertel  341:     my ($lonid) = @_;
                    342:     my $hostname = &hostname($lonid);
                    343:     if ($lonid) {
                    344: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    345: 	if ($hostname && -e $peerfile) {
                    346: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    347: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    348: 					     Type    => SOCK_STREAM,
                    349: 					     Timeout => 10);
                    350: 	    if ($client) {
                    351: 		print $client ("reset_retries\n");
                    352: 		my $answer=<$client>;
                    353: 		#reset just this one.
                    354: 	    }
                    355: 	}
                    356: 	return;
                    357:     }
                    358: 
1.836     www       359:     &logthis("Trying to reconnect lonc");
1.1       albertel  360:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  361:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  362: 	my $loncpid=<$fh>;
                    363:         chomp($loncpid);
                    364:         if (kill 0 => $loncpid) {
                    365: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    366:             kill USR1 => $loncpid;
                    367:             sleep 1;
1.836     www       368:          } else {
1.12      www       369: 	    &logthis(
1.672     albertel  370:                "<font color=\"blue\">WARNING:".
1.12      www       371:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  372:         }
                    373:     } else {
1.836     www       374: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  375:     }
                    376: }
                    377: 
                    378: # ------------------------------------------------------ Critical communication
1.12      www       379: 
1.1       albertel  380: sub critical {
                    381:     my ($cmd,$server)=@_;
1.838     albertel  382:     unless (&hostname($server)) {
1.672     albertel  383:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       384:                " Critical message to unknown server ($server)</font>");
                    385:         return 'no_such_host';
                    386:     }
1.1       albertel  387:     my $answer=reply($cmd,$server);
                    388:     if ($answer eq 'con_lost') {
                    389: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  390: 	my $answer=reply($cmd,$server);
1.1       albertel  391:         if ($answer eq 'con_lost') {
                    392:             my $now=time;
                    393:             my $middlename=$cmd;
1.5       www       394:             $middlename=substr($middlename,0,16);
1.1       albertel  395:             $middlename=~s/\W//g;
                    396:             my $dfilename=
1.305     www       397:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    398:             $dumpcount++;
1.1       albertel  399:             {
1.448     albertel  400: 		my $dfh;
                    401: 		if (open($dfh,">$dfilename")) {
                    402: 		    print $dfh "$cmd\n"; 
                    403: 		    close($dfh);
                    404: 		}
1.1       albertel  405:             }
                    406:             sleep 2;
                    407:             my $wcmd='';
                    408:             {
1.448     albertel  409: 		my $dfh;
                    410: 		if (open($dfh,"<$dfilename")) {
                    411: 		    $wcmd=<$dfh>; 
                    412: 		    close($dfh);
                    413: 		}
1.1       albertel  414:             }
                    415:             chomp($wcmd);
1.7       www       416:             if ($wcmd eq $cmd) {
1.672     albertel  417: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       418:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  419:                 &logperm("D:$server:$cmd");
                    420: 	        return 'con_delayed';
                    421:             } else {
1.672     albertel  422:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       423:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  424:                 &logperm("F:$server:$cmd");
                    425:                 return 'con_failed';
                    426:             }
                    427:         }
                    428:     }
                    429:     return $answer;
1.405     albertel  430: }
                    431: 
1.755     albertel  432: # ------------------------------------------- check if return value is an error
                    433: 
                    434: sub error {
                    435:     my ($result) = @_;
1.756     albertel  436:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  437: 	if ($2 == 2) { return undef; }
                    438: 	return $1;
                    439:     }
                    440:     return undef;
                    441: }
                    442: 
1.783     albertel  443: sub convert_and_load_session_env {
                    444:     my ($lonidsdir,$handle)=@_;
                    445:     my @profile;
                    446:     {
1.917     albertel  447: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    448: 	if (!$opened) {
1.915     albertel  449: 	    return 0;
                    450: 	}
1.783     albertel  451: 	flock($idf,LOCK_SH);
                    452: 	@profile=<$idf>;
                    453: 	close($idf);
                    454:     }
                    455:     my %temp_env;
                    456:     foreach my $line (@profile) {
1.786     albertel  457: 	if ($line !~ m/=/) {
                    458: 	    return 0;
                    459: 	}
1.783     albertel  460: 	chomp($line);
                    461: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    462: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    463:     }
                    464:     unlink("$lonidsdir/$handle.id");
                    465:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    466: 	    0640)) {
                    467: 	%disk_env = %temp_env;
                    468: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    469: 	untie(%disk_env);
                    470:     }
1.786     albertel  471:     return 1;
1.783     albertel  472: }
                    473: 
1.374     www       474: # ------------------------------------------- Transfer profile into environment
1.780     albertel  475: my $env_loaded;
                    476: sub transfer_profile_to_env {
1.788     albertel  477:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    478:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       479: 
1.720     albertel  480:     if (!defined($lonidsdir)) {
                    481: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    482:     }
                    483:     if (!defined($handle)) {
                    484:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    485:     }
                    486: 
1.786     albertel  487:     my $convert;
                    488:     {
1.917     albertel  489:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    490: 	if (!$opened) {
1.915     albertel  491: 	    return;
                    492: 	}
1.786     albertel  493: 	flock($idf,LOCK_SH);
                    494: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    495: 		&GDBM_READER(),0640)) {
                    496: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    497: 	    untie(%disk_env);
                    498: 	} else {
                    499: 	    $convert = 1;
                    500: 	}
                    501:     }
                    502:     if ($convert) {
                    503: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    504: 	    &logthis("Failed to load session, or convert session.");
                    505: 	}
1.374     www       506:     }
1.783     albertel  507: 
1.786     albertel  508:     my %remove;
1.783     albertel  509:     while ( my $envname = each(%env) ) {
1.433     matthew   510:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    511:             if ($time < time-300) {
1.783     albertel  512:                 $remove{$key}++;
1.433     matthew   513:             }
                    514:         }
                    515:     }
1.783     albertel  516: 
1.619     albertel  517:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  518:     $env_loaded=1;
1.783     albertel  519:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   520:         &delenv($expired_key);
1.374     www       521:     }
1.1       albertel  522: }
                    523: 
1.916     albertel  524: # ---------------------------------------------------- Check for valid session 
                    525: sub check_for_valid_session {
                    526:     my ($r) = @_;
                    527:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    528:     my $lonid=$cookies{'lonID'};
                    529:     return undef if (!$lonid);
                    530: 
                    531:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    532:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    533:     return undef if (!-e "$lonidsdir/$handle.id");
                    534: 
1.917     albertel  535:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    536:     return undef if (!$opened);
1.916     albertel  537: 
                    538:     flock($idf,LOCK_SH);
                    539:     my %disk_env;
                    540:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    541: 	    &GDBM_READER(),0640)) {
                    542: 	return undef;	
                    543:     }
                    544: 
                    545:     if (!defined($disk_env{'user.name'})
                    546: 	|| !defined($disk_env{'user.domain'})) {
                    547: 	return undef;
                    548:     }
                    549:     return $handle;
                    550: }
                    551: 
1.830     albertel  552: sub timed_flock {
                    553:     my ($file,$lock_type) = @_;
                    554:     my $failed=0;
                    555:     eval {
                    556: 	local $SIG{__DIE__}='DEFAULT';
                    557: 	local $SIG{ALRM}=sub {
                    558: 	    $failed=1;
                    559: 	    die("failed lock");
                    560: 	};
                    561: 	alarm(13);
                    562: 	flock($file,$lock_type);
                    563: 	alarm(0);
                    564:     };
                    565:     if ($failed) {
                    566: 	return undef;
                    567:     } else {
                    568: 	return 1;
                    569:     }
                    570: }
                    571: 
1.5       www       572: # ---------------------------------------------------------- Append Environment
                    573: 
                    574: sub appenv {
1.949     raeburn   575:     my ($newenv,$roles) = @_;
                    576:     if (ref($newenv) eq 'HASH') {
                    577:         foreach my $key (keys(%{$newenv})) {
                    578:             my $refused = 0;
                    579: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    580:                 $refused = 1;
                    581:                 if (ref($roles) eq 'ARRAY') {
                    582:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    583:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    584:                         $refused = 0;
                    585:                     }
                    586:                 }
                    587:             }
                    588:             if ($refused) {
                    589:                 &logthis("<font color=\"blue\">WARNING: ".
                    590:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    591:                          .'</font>');
                    592: 	        delete($newenv->{$key});
                    593:             } else {
                    594:                 $env{$key}=$newenv->{$key};
                    595:             }
                    596:         }
                    597:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    598:         if ($opened
                    599: 	    && &timed_flock($env_file,LOCK_EX)
                    600: 	    &&
                    601: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    602: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    603: 	    while (my ($key,$value) = each(%{$newenv})) {
                    604: 	        $disk_env{$key} = $value;
                    605: 	    }
                    606: 	    untie(%disk_env);
1.35      www       607:         }
1.191     harris41  608:     }
1.56      www       609:     return 'ok';
                    610: }
                    611: # ----------------------------------------------------- Delete from Environment
                    612: 
                    613: sub delenv {
1.987     raeburn   614:     my ($delthis,$regexp) = @_;
1.56      www       615:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  616:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       617:                 "Attempt to delete from environment ".$delthis);
                    618:         return 'error';
                    619:     }
1.917     albertel  620:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    621:     if ($opened
1.915     albertel  622: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  623: 	&&
                    624: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    625: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  626: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   627: 	    if ($regexp) {
                    628:                 if ($key=~/^$delthis/) {
                    629:                     delete($env{$key});
                    630:                     delete($disk_env{$key});
                    631:                 } 
                    632:             } else {
                    633:                 if ($key=~/^\Q$delthis\E/) {
                    634: 		    delete($env{$key});
                    635: 		    delete($disk_env{$key});
                    636: 	        }
                    637:             }
1.448     albertel  638: 	}
1.783     albertel  639: 	untie(%disk_env);
1.5       www       640:     }
                    641:     return 'ok';
1.369     albertel  642: }
                    643: 
1.790     albertel  644: sub get_env_multiple {
                    645:     my ($name) = @_;
                    646:     my @values;
                    647:     if (defined($env{$name})) {
                    648:         # exists is it an array
                    649:         if (ref($env{$name})) {
                    650:             @values=@{ $env{$name} };
                    651:         } else {
                    652:             $values[0]=$env{$name};
                    653:         }
                    654:     }
                    655:     return(@values);
                    656: }
                    657: 
1.958     www       658: # ------------------------------------------------------------------- Locking
                    659: 
                    660: sub set_lock {
                    661:     my ($text)=@_;
                    662:     $locknum++;
                    663:     my $id=$$.'-'.$locknum;
                    664:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    665:              'session.lock.'.$id => $text});
                    666:     return $id;
                    667: }
                    668: 
                    669: sub get_locks {
                    670:     my $num=0;
                    671:     my %texts=();
                    672:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    673:        if ($lock=~/\w/) {
                    674:           $num++;
                    675:           $texts{$lock}=$env{'session.lock.'.$lock};
                    676:        }
                    677:    }
                    678:    return ($num,%texts);
                    679: }
                    680: 
                    681: sub remove_lock {
                    682:     my ($id)=@_;
                    683:     my $newlocks='';
                    684:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    685:        if (($lock=~/\w/) && ($lock ne $id)) {
                    686:           $newlocks.=','.$lock;
                    687:        }
                    688:     }
                    689:     &appenv({'session.locks' => $newlocks});
                    690:     &delenv('session.lock.'.$id);
                    691: }
                    692: 
                    693: sub remove_all_locks {
                    694:     my $activelocks=$env{'session.locks'};
                    695:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    696:        if ($lock=~/\w/) {
                    697:           &remove_lock($lock);
                    698:        }
                    699:     }
                    700: }
                    701: 
                    702: 
1.369     albertel  703: # ------------------------------------------ Find out current server userload
                    704: sub userload {
                    705:     my $numusers=0;
                    706:     {
                    707: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    708: 	my $filename;
                    709: 	my $curtime=time;
                    710: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  711: 	    next if ($filename eq '.' || $filename eq '..');
                    712: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  713: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  714: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  715: 	}
                    716: 	closedir(LONIDS);
                    717:     }
                    718:     my $userloadpercent=0;
                    719:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    720:     if ($maxuserload) {
1.371     albertel  721: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  722:     }
1.372     albertel  723:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  724:     return $userloadpercent;
1.283     www       725: }
                    726: 
                    727: # ------------------------------------------ Fight off request when overloaded
                    728: 
                    729: sub overloaderror {
                    730:     my ($r,$checkserver)=@_;
                    731:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    732:     my $loadavg;
                    733:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  734:        open(my $loadfile,'/proc/loadavg');
1.283     www       735:        $loadavg=<$loadfile>;
                    736:        $loadavg =~ s/\s.*//g;
1.285     matthew   737:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  738:        close($loadfile);
1.283     www       739:     } else {
                    740:        $loadavg=&reply('load',$checkserver);
                    741:     }
1.285     matthew   742:     my $overload=$loadavg-100;
1.283     www       743:     if ($overload>0) {
1.285     matthew   744: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       745:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       746:         return 413;
1.283     www       747:     }    
                    748:     return '';
1.5       www       749: }
1.1       albertel  750: 
                    751: # ------------------------------ Find server with least workload from spare.tab
1.11      www       752: 
1.1       albertel  753: sub spareserver {
1.670     albertel  754:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  755:     my $spare_server;
1.370     albertel  756:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  757:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    758:                                                      :  $userloadpercent;
1.1056.4.8  raeburn   759:     my ($uint_dom,$remotesessions);
                    760:     if ($env{'user.domain'}) {
                    761:         my $uprimary_id = &Apache::lonnet::domain($env{'user.domain'},'primary');
                    762:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    763:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                    764:         $remotesessions = $udomdefaults{'remotesessions'};
                    765:     }
1.784     albertel  766:     foreach my $try_server (@{ $spareid{'primary'} }) {
1.1056.4.8  raeburn   767:         if ($uint_dom) {
                    768:             next unless (&spare_can_host($env{'user.domain'},$uint_dom,
                    769:                                          $remotesessions,$try_server));
                    770:         }
1.784     albertel  771: 	($spare_server, $lowest_load) =
                    772: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    773:     }
                    774: 
                    775:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    776: 
                    777:     if (!$found_server) {
                    778: 	foreach my $try_server (@{ $spareid{'default'} }) {
1.1056.4.8  raeburn   779:             if ($uint_dom) {
                    780:                 next unless (&spare_can_host($env{'user.domain'},$uint_dom,
                    781:                                              $remotesessions,$try_server));
                    782:             }
1.784     albertel  783: 	    ($spare_server, $lowest_load) =
                    784: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    785: 	}
                    786:     }
                    787: 
                    788:     if (!$want_server_name) {
1.968     raeburn   789:         my $protocol = 'http';
                    790:         if ($protocol{$spare_server} eq 'https') {
                    791:             $protocol = $protocol{$spare_server};
                    792:         }
1.1001    raeburn   793:         if (defined($spare_server)) {
                    794:             my $hostname = &hostname($spare_server);
1.1056.4.8  raeburn   795:             if (defined($hostname)) {
1.1001    raeburn   796: 	        $spare_server = $protocol.'://'.$hostname;
                    797:             }
                    798:         }
1.784     albertel  799:     }
                    800:     return $spare_server;
                    801: }
                    802: 
                    803: sub compare_server_load {
                    804:     my ($try_server, $spare_server, $lowest_load) = @_;
                    805: 
                    806:     my $loadans     = &reply('load',    $try_server);
                    807:     my $userloadans = &reply('userload',$try_server);
                    808: 
                    809:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1056.4.3  raeburn   810:         return; #didn't get a number from the server
1.784     albertel  811:     }
                    812: 
                    813:     my $load;
                    814:     if ($loadans =~ /\d/) {
                    815: 	if ($userloadans =~ /\d/) {
                    816: 	    #both are numbers, pick the bigger one
                    817: 	    $load = ($loadans > $userloadans) ? $loadans 
                    818: 		                              : $userloadans;
1.411     albertel  819: 	} else {
1.784     albertel  820: 	    $load = $loadans;
1.411     albertel  821: 	}
1.784     albertel  822:     } else {
                    823: 	$load = $userloadans;
                    824:     }
                    825: 
                    826:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    827: 	$spare_server = $try_server;
                    828: 	$lowest_load  = $load;
1.370     albertel  829:     }
1.784     albertel  830:     return ($spare_server,$lowest_load);
1.202     matthew   831: }
1.914     albertel  832: 
                    833: # --------------------------- ask offload servers if user already has a session
                    834: sub find_existing_session {
                    835:     my ($udom,$uname) = @_;
                    836:     foreach my $try_server (@{ $spareid{'primary'} },
                    837: 			    @{ $spareid{'default'} }) {
                    838: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    839:     }
                    840:     return;
                    841: }
                    842: 
                    843: # -------------------------------- ask if server already has a session for user
                    844: sub has_user_session {
                    845:     my ($lonid,$udom,$uname) = @_;
                    846:     my $result = &reply(join(':','userhassession',
                    847: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    848:     return 1 if ($result eq 'ok');
                    849: 
                    850:     return 0;
                    851: }
                    852: 
1.1056.4.3  raeburn   853: # --------- determine least loaded server in a user's domain which allows login
                    854: 
                    855: sub choose_server {
                    856:     my ($udom) = @_;
                    857:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
                    858:     my %servers = &get_servers($udom);
                    859:     my $lowest_load = 30000;
                    860:     my ($login_host,$hostname);
                    861:     foreach my $lonhost (keys(%servers)) {
                    862:         my $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
                    863:         if ($loginvia eq '') {
                    864:             ($login_host, $lowest_load) =
                    865:             &compare_server_load($lonhost, $login_host, $lowest_load);
                    866:         }
                    867:     }
                    868:     if ($login_host ne '') {
                    869:         $hostname = $servers{$login_host};
                    870:     }
                    871:     return ($login_host,$hostname);
                    872: }
                    873: 
1.202     matthew   874: # --------------------------------------------- Try to change a user's password
                    875: 
                    876: sub changepass {
1.799     raeburn   877:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   878:     $currentpass = &escape($currentpass);
                    879:     $newpass     = &escape($newpass);
1.1030    raeburn   880:     my $lonhost = $perlvar{'lonHostID'};
                    881:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   882: 		       $server);
                    883:     if (! $answer) {
                    884: 	&logthis("No reply on password change request to $server ".
                    885: 		 "by $uname in domain $udom.");
                    886:     } elsif ($answer =~ "^ok") {
                    887:         &logthis("$uname in $udom successfully changed their password ".
                    888: 		 "on $server.");
                    889:     } elsif ($answer =~ "^pwchange_failure") {
                    890: 	&logthis("$uname in $udom was unable to change their password ".
                    891: 		 "on $server.  The action was blocked by either lcpasswd ".
                    892: 		 "or pwchange");
                    893:     } elsif ($answer =~ "^non_authorized") {
                    894:         &logthis("$uname in $udom did not get their password correct when ".
                    895: 		 "attempting to change it on $server.");
                    896:     } elsif ($answer =~ "^auth_mode_error") {
                    897:         &logthis("$uname in $udom attempted to change their password despite ".
                    898: 		 "not being locally or internally authenticated on $server.");
                    899:     } elsif ($answer =~ "^unknown_user") {
                    900:         &logthis("$uname in $udom attempted to change their password ".
                    901: 		 "on $server but were unable to because $server is not ".
                    902: 		 "their home server.");
                    903:     } elsif ($answer =~ "^refused") {
                    904: 	&logthis("$server refused to change $uname in $udom password because ".
                    905: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn   906:     } elsif ($answer =~ "invalid_client") {
                    907:         &logthis("$server refused to change $uname in $udom password because ".
                    908:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew   909:     }
                    910:     return $answer;
1.1       albertel  911: }
                    912: 
1.169     harris41  913: # ----------------------- Try to determine user's current authentication scheme
                    914: 
                    915: sub queryauthenticate {
                    916:     my ($uname,$udom)=@_;
1.456     albertel  917:     my $uhome=&homeserver($uname,$udom);
                    918:     if (!$uhome) {
                    919: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    920: 	return 'no_host';
                    921:     }
                    922:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    923:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    924: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  925:     }
1.456     albertel  926:     return $answer;
1.169     harris41  927: }
                    928: 
1.1       albertel  929: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       930: 
1.1       albertel  931: sub authenticate {
1.1056.4.3  raeburn   932:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel  933:     $upass=&escape($upass);
                    934:     $uname= &LONCAPA::clean_username($uname);
1.836     www       935:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   936:     my $newhome;
1.836     www       937:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    938: # Maybe the machine was offline and only re-appeared again recently?
                    939:         &reconlonc();
                    940: # One more
1.952     raeburn   941: 	$uhome=&homeserver($uname,$udom,1);
                    942:         if (($uhome eq 'no_host') && $checkdefauth) {
                    943:             if (defined(&domain($udom,'primary'))) {
                    944:                 $newhome=&domain($udom,'primary');
                    945:             }
                    946:             if ($newhome ne '') {
                    947:                 $uhome = $newhome;
                    948:             }
                    949:         }
1.836     www       950: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    951: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   952: 	    return 'no_host';
                    953:         }
1.1       albertel  954:     }
1.1056.4.3  raeburn   955:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel  956:     if ($answer eq 'authorized') {
1.952     raeburn   957:         if ($newhome) {
                    958:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    959:             return 'no_account_on_host'; 
                    960:         } else {
                    961:             &logthis("User $uname at $udom authorized by $uhome");
                    962:             return $uhome;
                    963:         }
1.471     albertel  964:     }
                    965:     if ($answer eq 'non_authorized') {
                    966: 	&logthis("User $uname at $udom rejected by $uhome");
                    967: 	return 'no_host'; 
1.9       www       968:     }
1.471     albertel  969:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  970:     return 'no_host';
                    971: }
                    972: 
1.1056.4.3  raeburn   973: sub can_host_session {
                    974:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
                    975:     my $canhost = 1;
                    976:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
                    977:     if (ref($remotesessions) eq 'HASH') {
                    978:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
                    979:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
                    980:                 $canhost = 0;
                    981:             } else {
                    982:                 $canhost = 1;
                    983:             }
                    984:         }
                    985:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
                    986:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
                    987:                 $canhost = 1;
                    988:             } else {
                    989:                 $canhost = 0;
                    990:             }
                    991:         }
                    992:         if ($canhost) {
                    993:             if ($remotesessions->{'version'} ne '') {
                    994:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                    995:                 if ($reqmajor ne '' && $reqminor ne '') {
                    996:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                    997:                         my $major = $1;
                    998:                         my $minor = $2;
                    999:                         if (($major < $reqmajor ) ||
                   1000:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1001:                             $canhost = 0;
                   1002:                         }
                   1003:                     } else {
                   1004:                         $canhost = 0;
                   1005:                     }
                   1006:                 }
                   1007:             }
                   1008:         }
                   1009:     }
                   1010:     if ($canhost) {
                   1011:         if (ref($hostedsessions) eq 'HASH') {
                   1012:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
                   1013:                 if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'excludedomain'}})) {
                   1014:                     $canhost = 0;
                   1015:                 } else {
                   1016:                     $canhost = 1;
                   1017:                 }
                   1018:             }
                   1019:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
                   1020:                 if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'includedomain'}})) {
                   1021:                     $canhost = 1;
                   1022:                 } else {
                   1023:                     $canhost = 0;
                   1024:                 }
                   1025:             }
                   1026:         }
                   1027:     }
                   1028:     return $canhost;
                   1029: }
                   1030: 
1.1056.4.8  raeburn  1031: sub spare_can_host {
                   1032:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1033:     my $canhost=1;
                   1034:     my @intdoms;
                   1035:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1036:     if (ref($internet_names) eq 'ARRAY') {
                   1037:         @intdoms = @{$internet_names};
                   1038:     }
                   1039:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1040:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1041:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1042:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1043:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1044:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1045:                                      $remotesessions,
                   1046:                                      $defdomdefaults{'hostedsessions'});
                   1047:     }
                   1048:     return $canhost;
                   1049: }
                   1050: 
1.1       albertel 1051: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1052: 
1.599     albertel 1053: my %homecache;
1.1       albertel 1054: sub homeserver {
1.230     stredwic 1055:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1056:     my $index="$uname:$udom";
1.426     albertel 1057: 
1.599     albertel 1058:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1059: 
                   1060:     my %servers = &get_servers($udom,'library');
                   1061:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1062:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1063: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1064: 
                   1065: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1066: 	if ($answer eq 'found') {
                   1067: 	    delete($badServerCache{$tryserver}); 
                   1068: 	    return $homecache{$index}=$tryserver;
                   1069: 	} elsif ($answer eq 'no_host') {
                   1070: 	    $badServerCache{$tryserver}=1;
                   1071: 	}
1.1       albertel 1072:     }    
                   1073:     return 'no_host';
1.70      www      1074: }
                   1075: 
                   1076: # ------------------------------------- Find the usernames behind a list of IDs
                   1077: 
                   1078: sub idget {
                   1079:     my ($udom,@ids)=@_;
                   1080:     my %returnhash=();
                   1081:     
1.841     albertel 1082:     my %servers = &get_servers($udom,'library');
                   1083:     foreach my $tryserver (keys(%servers)) {
                   1084: 	my $idlist=join('&',@ids);
                   1085: 	$idlist=~tr/A-Z/a-z/; 
                   1086: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1087: 	my @answer=();
                   1088: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1089: 	    @answer=split(/\&/,$reply);
                   1090: 	}                    ;
                   1091: 	my $i;
                   1092: 	for ($i=0;$i<=$#ids;$i++) {
                   1093: 	    if ($answer[$i]) {
                   1094: 		$returnhash{$ids[$i]}=$answer[$i];
                   1095: 	    } 
                   1096: 	}
                   1097:     } 
1.70      www      1098:     return %returnhash;
                   1099: }
                   1100: 
                   1101: # ------------------------------------- Find the IDs behind a list of usernames
                   1102: 
                   1103: sub idrget {
                   1104:     my ($udom,@unames)=@_;
                   1105:     my %returnhash=();
1.800     albertel 1106:     foreach my $uname (@unames) {
                   1107:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1108:     }
1.70      www      1109:     return %returnhash;
                   1110: }
                   1111: 
                   1112: # ------------------------------- Store away a list of names and associated IDs
                   1113: 
                   1114: sub idput {
                   1115:     my ($udom,%ids)=@_;
                   1116:     my %servers=();
1.800     albertel 1117:     foreach my $uname (keys(%ids)) {
                   1118: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1119:         my $uhom=&homeserver($uname,$udom);
1.70      www      1120:         if ($uhom ne 'no_host') {
1.800     albertel 1121:             my $id=&escape($ids{$uname});
1.70      www      1122:             $id=~tr/A-Z/a-z/;
1.800     albertel 1123:             my $esc_unam=&escape($uname);
1.70      www      1124: 	    if ($servers{$uhom}) {
1.800     albertel 1125: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1126:             } else {
1.800     albertel 1127:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1128:             }
                   1129:         }
1.191     harris41 1130:     }
1.800     albertel 1131:     foreach my $server (keys(%servers)) {
                   1132:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1133:     }
1.344     www      1134: }
                   1135: 
1.1023    raeburn  1136: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1137: sub dump_dom {
1.1023    raeburn  1138:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn  1139:     if (!$udom) {
                   1140:         $udom=$env{'user.domain'};
                   1141:     }
                   1142:     my %returnhash;
1.1023    raeburn  1143:     if ($udom) {
                   1144:         my $uname = &get_domainconfiguser($udom);
                   1145:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn  1146:     }
                   1147:     return %returnhash;
                   1148: }
                   1149: 
1.1023    raeburn  1150: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1151: 
                   1152: sub get_dom {
1.860     raeburn  1153:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1154:     my $items='';
                   1155:     foreach my $item (@$storearr) {
                   1156:         $items.=&escape($item).'&';
                   1157:     }
                   1158:     $items=~s/\&$//;
1.860     raeburn  1159:     if (!$udom) {
                   1160:         $udom=$env{'user.domain'};
                   1161:         if (defined(&domain($udom,'primary'))) {
                   1162:             $uhome=&domain($udom,'primary');
                   1163:         } else {
1.874     albertel 1164:             undef($uhome);
1.860     raeburn  1165:         }
                   1166:     } else {
                   1167:         if (!$uhome) {
                   1168:             if (defined(&domain($udom,'primary'))) {
                   1169:                 $uhome=&domain($udom,'primary');
                   1170:             }
                   1171:         }
                   1172:     }
                   1173:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1174:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1175:         my %returnhash;
1.875     albertel 1176:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1177:             return %returnhash;
                   1178:         }
1.806     raeburn  1179:         my @pairs=split(/\&/,$rep);
                   1180:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1181:             return @pairs;
                   1182:         }
                   1183:         my $i=0;
                   1184:         foreach my $item (@$storearr) {
                   1185:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1186:             $i++;
                   1187:         }
                   1188:         return %returnhash;
                   1189:     } else {
1.880     banghart 1190:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1191:     }
                   1192: }
                   1193: 
                   1194: # -------------------------------------------- put items in domain db files 
                   1195: 
                   1196: sub put_dom {
1.860     raeburn  1197:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1198:     if (!$udom) {
                   1199:         $udom=$env{'user.domain'};
                   1200:         if (defined(&domain($udom,'primary'))) {
                   1201:             $uhome=&domain($udom,'primary');
                   1202:         } else {
1.874     albertel 1203:             undef($uhome);
1.860     raeburn  1204:         }
                   1205:     } else {
                   1206:         if (!$uhome) {
                   1207:             if (defined(&domain($udom,'primary'))) {
                   1208:                 $uhome=&domain($udom,'primary');
                   1209:             }
                   1210:         }
                   1211:     } 
                   1212:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1213:         my $items='';
                   1214:         foreach my $item (keys(%$storehash)) {
                   1215:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1216:         }
                   1217:         $items=~s/\&$//;
                   1218:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1219:     } else {
1.860     raeburn  1220:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1221:     }
                   1222: }
                   1223: 
1.1023    raeburn  1224: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1225: sub newput_dom {
1.1023    raeburn  1226:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1227:     my $result;
                   1228:     if (!$udom) {
                   1229:         $udom=$env{'user.domain'};
                   1230:     }
1.1023    raeburn  1231:     if ($udom) {
                   1232:         my $uname = &get_domainconfiguser($udom);
                   1233:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1234:     }
                   1235:     return $result;
                   1236: }
                   1237: 
1.1023    raeburn  1238: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1239: sub del_dom {
1.1023    raeburn  1240:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1241:     if (ref($storearr) eq 'ARRAY') {
                   1242:         if (!$udom) {
                   1243:             $udom=$env{'user.domain'};
                   1244:         }
1.1023    raeburn  1245:         if ($udom) {
                   1246:             my $uname = &get_domainconfiguser($udom); 
                   1247:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1248:         }
                   1249:     }
                   1250: }
                   1251: 
1.1023    raeburn  1252: # ----------------------------------construct domainconfig user for a domain 
                   1253: sub get_domainconfiguser {
                   1254:     my ($udom) = @_;
                   1255:     return $udom.'-domainconfig';
                   1256: }
                   1257: 
1.837     raeburn  1258: sub retrieve_inst_usertypes {
                   1259:     my ($udom) = @_;
                   1260:     my (%returnhash,@order);
1.989     raeburn  1261:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1262:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1263:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1264:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1265:         @order = @{$domdefs{'inststatusorder'}};
                   1266:     } else {
                   1267:         if (defined(&domain($udom,'primary'))) {
                   1268:             my $uhome=&domain($udom,'primary');
                   1269:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1270:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1271:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1272:                 return (\%returnhash,\@order);
                   1273:             }
                   1274:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1275:             my @pairs=split(/\&/,$hashitems);
                   1276:             foreach my $item (@pairs) {
                   1277:                 my ($key,$value)=split(/=/,$item,2);
                   1278:                 $key = &unescape($key);
                   1279:                 next if ($key =~ /^error: 2 /);
                   1280:                 $returnhash{$key}=&thaw_unescape($value);
                   1281:             }
                   1282:             my @esc_order = split(/\&/,$orderitems);
                   1283:             foreach my $item (@esc_order) {
                   1284:                 push(@order,&unescape($item));
                   1285:             }
                   1286:         } else {
                   1287:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1288:         }
                   1289:     }
                   1290:     return (\%returnhash,\@order);
                   1291: }
                   1292: 
1.868     raeburn  1293: sub is_domainimage {
                   1294:     my ($url) = @_;
                   1295:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1296:         if (&domain($1) ne '') {
                   1297:             return '1';
                   1298:         }
                   1299:     }
                   1300:     return;
                   1301: }
                   1302: 
1.899     raeburn  1303: sub inst_directory_query {
                   1304:     my ($srch) = @_;
                   1305:     my $udom = $srch->{'srchdomain'};
                   1306:     my %results;
                   1307:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1308:     my $outcome;
1.899     raeburn  1309:     if ($homeserver ne '') {
1.904     albertel 1310: 	my $queryid=&reply("querysend:instdirsearch:".
                   1311: 			   &escape($srch->{'srchby'}).':'.
                   1312: 			   &escape($srch->{'srchterm'}).':'.
                   1313: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1314: 	my $host=&hostname($homeserver);
                   1315: 	if ($queryid !~/^\Q$host\E\_/) {
                   1316: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1317: 	    return;
                   1318: 	}
                   1319: 	my $response = &get_query_reply($queryid);
                   1320: 	my $maxtries = 5;
                   1321: 	my $tries = 1;
                   1322: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1323: 	    $response = &get_query_reply($queryid);
                   1324: 	    $tries ++;
                   1325: 	}
                   1326: 
                   1327:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1328:             if ($response eq 'unavailable') {
                   1329:                 $outcome = $response;
                   1330:             } else {
                   1331:                 $outcome = 'ok';
                   1332:                 my @matches = split(/\n/,$response);
                   1333:                 foreach my $match (@matches) {
                   1334:                     my ($key,$value) = split(/=/,$match);
                   1335:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1336:                 }
1.899     raeburn  1337:             }
                   1338:         }
                   1339:     }
1.909     raeburn  1340:     return ($outcome,%results);
1.899     raeburn  1341: }
                   1342: 
                   1343: sub usersearch {
                   1344:     my ($srch) = @_;
                   1345:     my $dom = $srch->{'srchdomain'};
                   1346:     my %results;
                   1347:     my %libserv = &all_library();
                   1348:     my $query = 'usersearch';
                   1349:     foreach my $tryserver (keys(%libserv)) {
                   1350:         if (&host_domain($tryserver) eq $dom) {
                   1351:             my $host=&hostname($tryserver);
                   1352:             my $queryid=
1.911     raeburn  1353:                 &reply("querysend:".&escape($query).':'.
                   1354:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1355:                        &escape($srch->{'srchtype'}).':'.
                   1356:                        &escape($srch->{'srchterm'}),$tryserver);
                   1357:             if ($queryid !~/^\Q$host\E\_/) {
                   1358:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1359:                 next;
1.899     raeburn  1360:             }
                   1361:             my $reply = &get_query_reply($queryid);
                   1362:             my $maxtries = 1;
                   1363:             my $tries = 1;
                   1364:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1365:                 $reply = &get_query_reply($queryid);
                   1366:                 $tries ++;
                   1367:             }
                   1368:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1369:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1370:             } else {
1.911     raeburn  1371:                 my @matches;
                   1372:                 if ($reply =~ /\n/) {
                   1373:                     @matches = split(/\n/,$reply);
                   1374:                 } else {
                   1375:                     @matches = split(/\&/,$reply);
                   1376:                 }
1.899     raeburn  1377:                 foreach my $match (@matches) {
                   1378:                     my ($uname,$udom,%userhash);
1.911     raeburn  1379:                     foreach my $entry (split(/:/,$match)) {
                   1380:                         my ($key,$value) =
                   1381:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1382:                         $userhash{$key} = $value;
                   1383:                         if ($key eq 'username') {
                   1384:                             $uname = $value;
                   1385:                         } elsif ($key eq 'domain') {
                   1386:                             $udom = $value;
1.911     raeburn  1387:                         }
1.899     raeburn  1388:                     }
                   1389:                     $results{$uname.':'.$udom} = \%userhash;
                   1390:                 }
                   1391:             }
                   1392:         }
                   1393:     }
                   1394:     return %results;
                   1395: }
                   1396: 
1.912     raeburn  1397: sub get_instuser {
                   1398:     my ($udom,$uname,$id) = @_;
                   1399:     my $homeserver = &domain($udom,'primary');
                   1400:     my ($outcome,%results);
                   1401:     if ($homeserver ne '') {
                   1402:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1403:                            &escape($id).':'.&escape($udom),$homeserver);
                   1404:         my $host=&hostname($homeserver);
                   1405:         if ($queryid !~/^\Q$host\E\_/) {
                   1406:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1407:             return;
                   1408:         }
                   1409:         my $response = &get_query_reply($queryid);
                   1410:         my $maxtries = 5;
                   1411:         my $tries = 1;
                   1412:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1413:             $response = &get_query_reply($queryid);
                   1414:             $tries ++;
                   1415:         }
                   1416:         if (!&error($response) && $response ne 'refused') {
                   1417:             if ($response eq 'unavailable') {
                   1418:                 $outcome = $response;
                   1419:             } else {
                   1420:                 $outcome = 'ok';
                   1421:                 my @matches = split(/\n/,$response);
                   1422:                 foreach my $match (@matches) {
                   1423:                     my ($key,$value) = split(/=/,$match);
                   1424:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1425:                 }
                   1426:             }
                   1427:         }
                   1428:     }
                   1429:     my %userinfo;
                   1430:     if (ref($results{$uname}) eq 'HASH') {
                   1431:         %userinfo = %{$results{$uname}};
                   1432:     } 
                   1433:     return ($outcome,%userinfo);
                   1434: }
                   1435: 
                   1436: sub inst_rulecheck {
1.923     raeburn  1437:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1438:     my %returnhash;
                   1439:     if ($udom ne '') {
                   1440:         if (ref($rules) eq 'ARRAY') {
                   1441:             @{$rules} = map {&escape($_);} (@{$rules});
                   1442:             my $rulestr = join(':',@{$rules});
                   1443:             my $homeserver=&domain($udom,'primary');
                   1444:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1445:                 my $response;
                   1446:                 if ($item eq 'username') {                
                   1447:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1448:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1449:                                               $homeserver));
1.923     raeburn  1450:                 } elsif ($item eq 'id') {
                   1451:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1452:                                               ':'.&escape($id).':'.$rulestr,
                   1453:                                               $homeserver));
1.945     raeburn  1454:                 } elsif ($item eq 'selfcreate') {
                   1455:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1456:                                                &escape($udom).':'.&escape($uname).
                   1457:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1458:                 }
1.912     raeburn  1459:                 if ($response ne 'refused') {
                   1460:                     my @pairs=split(/\&/,$response);
                   1461:                     foreach my $item (@pairs) {
                   1462:                         my ($key,$value)=split(/=/,$item,2);
                   1463:                         $key = &unescape($key);
                   1464:                         next if ($key =~ /^error: 2 /);
                   1465:                         $returnhash{$key}=&thaw_unescape($value);
                   1466:                     }
                   1467:                 }
                   1468:             }
                   1469:         }
                   1470:     }
                   1471:     return %returnhash;
                   1472: }
                   1473: 
                   1474: sub inst_userrules {
1.923     raeburn  1475:     my ($udom,$check) = @_;
1.912     raeburn  1476:     my (%ruleshash,@ruleorder);
                   1477:     if ($udom ne '') {
                   1478:         my $homeserver=&domain($udom,'primary');
                   1479:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1480:             my $response;
                   1481:             if ($check eq 'id') {
                   1482:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1483:                                  $homeserver);
1.943     raeburn  1484:             } elsif ($check eq 'email') {
                   1485:                 $response=&reply('instemailrules:'.&escape($udom),
                   1486:                                  $homeserver);
1.923     raeburn  1487:             } else {
                   1488:                 $response=&reply('instuserrules:'.&escape($udom),
                   1489:                                  $homeserver);
                   1490:             }
1.912     raeburn  1491:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1492:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1493:                 ($response ne 'no_such_host')) {
                   1494:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1495:                 my @pairs=split(/\&/,$hashitems);
                   1496:                 foreach my $item (@pairs) {
                   1497:                     my ($key,$value)=split(/=/,$item,2);
                   1498:                     $key = &unescape($key);
                   1499:                     next if ($key =~ /^error: 2 /);
                   1500:                     $ruleshash{$key}=&thaw_unescape($value);
                   1501:                 }
                   1502:                 my @esc_order = split(/\&/,$orderitems);
                   1503:                 foreach my $item (@esc_order) {
                   1504:                     push(@ruleorder,&unescape($item));
                   1505:                 }
                   1506:             }
                   1507:         }
                   1508:     }
                   1509:     return (\%ruleshash,\@ruleorder);
                   1510: }
                   1511: 
1.976     raeburn  1512: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1513: 
                   1514: sub get_domain_defaults {
                   1515:     my ($domain) = @_;
                   1516:     my $cachetime = 60*60*24;
                   1517:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1518:     if (defined($cached)) {
                   1519:         if (ref($result) eq 'HASH') {
                   1520:             return %{$result};
                   1521:         }
                   1522:     }
                   1523:     my %domdefaults;
                   1524:     my %domconfig =
1.989     raeburn  1525:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1526:                                   'requestcourses','inststatus',
1.1056.4.3  raeburn  1527:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1528:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1529:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1530:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1531:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1532:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1533:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1534:     } else {
                   1535:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1536:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1537:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1538:     }
1.976     raeburn  1539:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1540:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1541:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1542:         } else {
                   1543:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1544:         } 
                   1545:         my @usertools = ('aboutme','blog','portfolio');
                   1546:         foreach my $item (@usertools) {
                   1547:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1548:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1549:             }
                   1550:         }
                   1551:     }
1.985     raeburn  1552:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1553:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1554:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1555:         }
                   1556:     }
1.989     raeburn  1557:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1558:         foreach my $item ('inststatustypes','inststatusorder') {
                   1559:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1560:         }
                   1561:     }
1.1047    raeburn  1562:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1563:         foreach my $item ('canuse_pdfforms') {
                   1564:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1565:         }
                   1566:     }
1.1056.4.3  raeburn  1567:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1568:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1569:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1570:         }
                   1571:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1572:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1573:         }
                   1574:     }
1.943     raeburn  1575:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1576:                                   $cachetime);
                   1577:     return %domdefaults;
                   1578: }
                   1579: 
1.344     www      1580: # --------------------------------------------------- Assign a key to a student
                   1581: 
                   1582: sub assign_access_key {
1.364     www      1583: #
                   1584: # a valid key looks like uname:udom#comments
                   1585: # comments are being appended
                   1586: #
1.498     www      1587:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1588:     $kdom=
1.620     albertel 1589:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1590:     $knum=
1.620     albertel 1591:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1592:     $cdom=
1.620     albertel 1593:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1594:     $cnum=
1.620     albertel 1595:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1596:     $udom=$env{'user.name'} unless (defined($udom));
                   1597:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1598:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1599:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1600:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1601:                                                   # assigned to this person
                   1602:                                                   # - this should not happen,
1.345     www      1603:                                                   # unless something went wrong
                   1604:                                                   # the first time around
                   1605: # ready to assign
1.364     www      1606:         $logentry=$1.'; '.$logentry;
1.496     www      1607:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1608:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1609: # key now belongs to user
1.346     www      1610: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1611:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1612:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1613:                 return 'ok';
                   1614:             } else {
                   1615:                 return 
                   1616:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1617: 	    }
                   1618:         } else {
                   1619:             return 'error: Could not assign key, try again later.';
                   1620:         }
1.364     www      1621:     } elsif (!$existing{$ckey}) {
1.345     www      1622: # the key does not exist
                   1623: 	return 'error: The key does not exist';
                   1624:     } else {
                   1625: # the key is somebody else's
                   1626: 	return 'error: The key is already in use';
                   1627:     }
1.344     www      1628: }
                   1629: 
1.364     www      1630: # ------------------------------------------ put an additional comment on a key
                   1631: 
                   1632: sub comment_access_key {
                   1633: #
                   1634: # a valid key looks like uname:udom#comments
                   1635: # comments are being appended
                   1636: #
                   1637:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1638:     $cdom=
1.620     albertel 1639:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1640:     $cnum=
1.620     albertel 1641:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1642:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1643:     if ($existing{$ckey}) {
                   1644:         $existing{$ckey}.='; '.$logentry;
                   1645: # ready to assign
1.367     www      1646:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1647:                                                  $cdom,$cnum) eq 'ok') {
                   1648: 	    return 'ok';
                   1649:         } else {
                   1650: 	    return 'error: Count not store comment.';
                   1651:         }
                   1652:     } else {
                   1653: # the key does not exist
                   1654: 	return 'error: The key does not exist';
                   1655:     }
                   1656: }
                   1657: 
1.344     www      1658: # ------------------------------------------------------ Generate a set of keys
                   1659: 
                   1660: sub generate_access_keys {
1.364     www      1661:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1662:     $cdom=
1.620     albertel 1663:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1664:     $cnum=
1.620     albertel 1665:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1666:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1667:     unless (($cdom) && ($cnum)) { return 0; }
                   1668:     if ($number>10000) { return 0; }
                   1669:     sleep(2); # make sure don't get same seed twice
                   1670:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1671:     my $total=0;
                   1672:     for (my $i=1;$i<=$number;$i++) {
                   1673:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1674:                   sprintf("%lx",int(100000*rand)).'-'.
                   1675:                   sprintf("%lx",int(100000*rand));
                   1676:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1677:        $newkey=~s/0/h/g; # and also 0 and O
                   1678:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1679:        if ($existing{$newkey}) {
                   1680:            $i--;
                   1681:        } else {
1.364     www      1682: 	  if (&put('accesskeys',
                   1683:               { $newkey => '# generated '.localtime().
1.620     albertel 1684:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1685:                            '; '.$logentry },
                   1686: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1687:               $total++;
                   1688: 	  }
                   1689:        }
                   1690:     }
1.620     albertel 1691:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1692:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1693:     return $total;
                   1694: }
                   1695: 
                   1696: # ------------------------------------------------------- Validate an accesskey
                   1697: 
                   1698: sub validate_access_key {
                   1699:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1700:     $cdom=
1.620     albertel 1701:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1702:     $cnum=
1.620     albertel 1703:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1704:     $udom=$env{'user.domain'} unless (defined($udom));
                   1705:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1706:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1707:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1708: }
                   1709: 
                   1710: # ------------------------------------- Find the section of student in a course
1.652     albertel 1711: sub devalidate_getsection_cache {
                   1712:     my ($udom,$unam,$courseid)=@_;
                   1713:     my $hashid="$udom:$unam:$courseid";
                   1714:     &devalidate_cache_new('getsection',$hashid);
                   1715: }
1.298     matthew  1716: 
1.815     albertel 1717: sub courseid_to_courseurl {
                   1718:     my ($courseid) = @_;
                   1719:     #already url style courseid
                   1720:     return $courseid if ($courseid =~ m{^/});
                   1721: 
                   1722:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1723: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1724: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1725: 	return "/$cdom/$cnum";
                   1726:     }
                   1727: 
                   1728:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1729:     if (exists($courseinfo{'num'})) {
                   1730: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1731:     }
                   1732: 
                   1733:     return undef;
                   1734: }
                   1735: 
1.298     matthew  1736: sub getsection {
                   1737:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1738:     my $cachetime=1800;
1.551     albertel 1739: 
                   1740:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1741:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1742:     if (defined($cached)) { return $result; }
                   1743: 
1.298     matthew  1744:     my %Pending; 
                   1745:     my %Expired;
                   1746:     #
                   1747:     # Each role can either have not started yet (pending), be active, 
                   1748:     #    or have expired.
                   1749:     #
                   1750:     # If there is an active role, we are done.
                   1751:     #
                   1752:     # If there is more than one role which has not started yet, 
                   1753:     #     choose the one which will start sooner
                   1754:     # If there is one role which has not started yet, return it.
                   1755:     #
                   1756:     # If there is more than one expired role, choose the one which ended last.
                   1757:     # If there is a role which has expired, return it.
                   1758:     #
1.815     albertel 1759:     $courseid = &courseid_to_courseurl($courseid);
1.1056.4.10! raeburn  1760:     my $extra = &freeze_escape({'skipcheck' => 1});
        !          1761:     my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817     raeburn  1762:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1763:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1764:         my $section=$1;
                   1765:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1766:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1767:         my $now=time;
1.548     albertel 1768:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1769:             $Expired{$end}=$section;
                   1770:             next;
                   1771:         }
1.548     albertel 1772:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1773:             $Pending{$start}=$section;
                   1774:             next;
                   1775:         }
1.599     albertel 1776:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1777:     }
                   1778:     #
                   1779:     # Presumedly there will be few matching roles from the above
                   1780:     # loop and the sorting time will be negligible.
                   1781:     if (scalar(keys(%Pending))) {
                   1782:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1783:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1784:     } 
                   1785:     if (scalar(keys(%Expired))) {
                   1786:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1787:         my $time = pop(@sorted);
1.599     albertel 1788:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1789:     }
1.599     albertel 1790:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1791: }
1.70      www      1792: 
1.599     albertel 1793: sub save_cache {
                   1794:     &purge_remembered();
1.722     albertel 1795:     #&Apache::loncommon::validate_page();
1.620     albertel 1796:     undef(%env);
1.780     albertel 1797:     undef($env_loaded);
1.599     albertel 1798: }
1.452     albertel 1799: 
1.599     albertel 1800: my $to_remember=-1;
                   1801: my %remembered;
                   1802: my %accessed;
                   1803: my $kicks=0;
                   1804: my $hits=0;
1.849     albertel 1805: sub make_key {
                   1806:     my ($name,$id) = @_;
1.872     albertel 1807:     if (length($id) > 65 
                   1808: 	&& length(&escape($id)) > 200) {
                   1809: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1810:     }
1.849     albertel 1811:     return &escape($name.':'.$id);
                   1812: }
                   1813: 
1.599     albertel 1814: sub devalidate_cache_new {
                   1815:     my ($name,$id,$debug) = @_;
                   1816:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1817:     $id=&make_key($name,$id);
1.599     albertel 1818:     $memcache->delete($id);
                   1819:     delete($remembered{$id});
                   1820:     delete($accessed{$id});
                   1821: }
                   1822: 
                   1823: sub is_cached_new {
                   1824:     my ($name,$id,$debug) = @_;
1.849     albertel 1825:     $id=&make_key($name,$id);
1.599     albertel 1826:     if (exists($remembered{$id})) {
                   1827: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1828: 	$accessed{$id}=[&gettimeofday()];
                   1829: 	$hits++;
                   1830: 	return ($remembered{$id},1);
                   1831:     }
                   1832:     my $value = $memcache->get($id);
                   1833:     if (!(defined($value))) {
                   1834: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1835: 	return (undef,undef);
1.416     albertel 1836:     }
1.599     albertel 1837:     if ($value eq '__undef__') {
                   1838: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1839: 	$value=undef;
                   1840:     }
                   1841:     &make_room($id,$value,$debug);
                   1842:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1843:     return ($value,1);
                   1844: }
                   1845: 
                   1846: sub do_cache_new {
                   1847:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1848:     $id=&make_key($name,$id);
1.599     albertel 1849:     my $setvalue=$value;
                   1850:     if (!defined($setvalue)) {
                   1851: 	$setvalue='__undef__';
                   1852:     }
1.623     albertel 1853:     if (!defined($time) ) {
                   1854: 	$time=600;
                   1855:     }
1.599     albertel 1856:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1857:     my $result = $memcache->set($id,$setvalue,$time);
                   1858:     if (! $result) {
1.872     albertel 1859: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1860: 	$memcache->disconnect_all();
1.872     albertel 1861:     }
1.600     albertel 1862:     # need to make a copy of $value
1.919     albertel 1863:     &make_room($id,$value,$debug);
1.599     albertel 1864:     return $value;
                   1865: }
                   1866: 
                   1867: sub make_room {
                   1868:     my ($id,$value,$debug)=@_;
1.919     albertel 1869: 
                   1870:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1871:                                     : $value;
1.599     albertel 1872:     if ($to_remember<0) { return; }
                   1873:     $accessed{$id}=[&gettimeofday()];
                   1874:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1875:     my $to_kick;
                   1876:     my $max_time=0;
                   1877:     foreach my $other (keys(%accessed)) {
                   1878: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1879: 	    $to_kick=$other;
                   1880: 	    $max_time=&tv_interval($accessed{$other});
                   1881: 	}
                   1882:     }
                   1883:     delete($remembered{$to_kick});
                   1884:     delete($accessed{$to_kick});
                   1885:     $kicks++;
                   1886:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1887:     return;
                   1888: }
                   1889: 
1.599     albertel 1890: sub purge_remembered {
1.604     albertel 1891:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1892:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1893:     undef(%remembered);
                   1894:     undef(%accessed);
1.428     albertel 1895: }
1.70      www      1896: # ------------------------------------- Read an entry from a user's environment
                   1897: 
                   1898: sub userenvironment {
                   1899:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1900:     my $items;
                   1901:     foreach my $item (@what) {
                   1902:         $items.=&escape($item).'&';
                   1903:     }
                   1904:     $items=~s/\&$//;
1.70      www      1905:     my %returnhash=();
1.1009    raeburn  1906:     my $uhome = &homeserver($unam,$udom);
                   1907:     unless ($uhome eq 'no_host') {
                   1908:         my @answer=split(/\&/, 
                   1909:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  1910:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   1911:             return %returnhash;
                   1912:         }
1.1009    raeburn  1913:         my $i;
                   1914:         for ($i=0;$i<=$#what;$i++) {
                   1915: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   1916:         }
1.70      www      1917:     }
                   1918:     return %returnhash;
1.1       albertel 1919: }
                   1920: 
1.617     albertel 1921: # ---------------------------------------------------------- Get a studentphoto
                   1922: sub studentphoto {
                   1923:     my ($udom,$unam,$ext) = @_;
                   1924:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1925:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1926:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1927:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1928:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1929:             } else {
                   1930:                 my ($result,$perm_reqd)=
1.707     albertel 1931: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1932:                 if ($result eq 'ok') {
                   1933:                     if (!($perm_reqd eq 'yes')) {
                   1934:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1935:                     }
                   1936:                 }
                   1937:             }
                   1938:         }
                   1939:     } else {
                   1940:         my ($result,$perm_reqd) = 
1.707     albertel 1941: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1942:         if ($result eq 'ok') {
                   1943:             if (!($perm_reqd eq 'yes')) {
                   1944:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1945:             }
                   1946:         }
                   1947:     }
                   1948:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1949: }
                   1950: 
                   1951: sub retrievestudentphoto {
                   1952:     my ($udom,$unam,$ext,$type) = @_;
                   1953:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1954:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1955:     if ($ret eq 'ok') {
                   1956:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1957:         if ($type eq 'thumbnail') {
                   1958:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1959:         }
                   1960:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1961:         return $tokenurl;
                   1962:     } else {
                   1963:         if ($type eq 'thumbnail') {
                   1964:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1965:         } else { 
                   1966:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1967:         }
1.617     albertel 1968:     }
                   1969: }
                   1970: 
1.263     www      1971: # -------------------------------------------------------------------- New chat
                   1972: 
                   1973: sub chatsend {
1.724     raeburn  1974:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1975:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1976:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1977:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1978:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1979: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1980: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1981: }
                   1982: 
                   1983: # ------------------------------------------ Find current version of a resource
                   1984: 
                   1985: sub getversion {
                   1986:     my $fname=&clutter(shift);
                   1987:     unless ($fname=~/^\/res\//) { return -1; }
                   1988:     return &currentversion(&filelocation('',$fname));
                   1989: }
                   1990: 
                   1991: sub currentversion {
                   1992:     my $fname=shift;
1.599     albertel 1993:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1994:     if (defined($cached)) { return $result; }
1.292     www      1995:     my $author=$fname;
                   1996:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1997:     my ($udom,$uname)=split(/\//,$author);
                   1998:     my $home=homeserver($uname,$udom);
                   1999:     if ($home eq 'no_host') { 
                   2000:         return -1; 
                   2001:     }
                   2002:     my $answer=reply("currentversion:$fname",$home);
                   2003:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2004: 	return -1;
                   2005:     }
1.599     albertel 2006:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      2007: }
                   2008: 
1.1       albertel 2009: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2010: 
1.1       albertel 2011: sub subscribe {
                   2012:     my $fname=shift;
1.761     raeburn  2013:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2014:     $fname=~s/[\n\r]//g;
1.1       albertel 2015:     my $author=$fname;
                   2016:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2017:     my ($udom,$uname)=split(/\//,$author);
                   2018:     my $home=homeserver($uname,$udom);
1.335     albertel 2019:     if ($home eq 'no_host') {
                   2020:         return 'not_found';
1.1       albertel 2021:     }
                   2022:     my $answer=reply("sub:$fname",$home);
1.64      www      2023:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2024: 	$answer.=' by '.$home;
                   2025:     }
1.1       albertel 2026:     return $answer;
                   2027: }
                   2028:     
1.8       www      2029: # -------------------------------------------------------------- Replicate file
                   2030: 
                   2031: sub repcopy {
                   2032:     my $filename=shift;
1.23      www      2033:     $filename=~s/\/+/\//g;
1.607     raeburn  2034:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   2035:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 2036:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 2037: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 2038: 	return &repcopy_userfile($filename);
                   2039:     }
1.532     albertel 2040:     $filename=~s/[\n\r]//g;
1.8       www      2041:     my $transname="$filename.in.transfer";
1.828     www      2042: # FIXME: this should flock
1.607     raeburn  2043:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2044:     my $remoteurl=subscribe($filename);
1.64      www      2045:     if ($remoteurl =~ /^con_lost by/) {
                   2046: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2047:            return 'unavailable';
1.8       www      2048:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2049: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2050: 	   return 'not_found';
1.64      www      2051:     } elsif ($remoteurl =~ /^rejected by/) {
                   2052: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2053:            return 'forbidden';
1.20      www      2054:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2055:            return 'ok';
1.8       www      2056:     } else {
1.290     www      2057:         my $author=$filename;
                   2058:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2059:         my ($udom,$uname)=split(/\//,$author);
                   2060:         my $home=homeserver($uname,$udom);
                   2061:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2062:            my @parts=split(/\//,$filename);
                   2063:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   2064:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   2065:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2066: 	       return 'bad_request';
1.8       www      2067:            }
                   2068:            my $count;
                   2069:            for ($count=5;$count<$#parts;$count++) {
                   2070:                $path.="/$parts[$count]";
                   2071:                if ((-e $path)!=1) {
                   2072: 		   mkdir($path,0777);
                   2073:                }
                   2074:            }
                   2075:            my $ua=new LWP::UserAgent;
                   2076:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2077:            my $response=$ua->request($request,$transname);
                   2078:            if ($response->is_error()) {
                   2079: 	       unlink($transname);
                   2080:                my $message=$response->status_line;
1.672     albertel 2081:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2082:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2083:                return 'unavailable';
1.8       www      2084:            } else {
1.16      www      2085: 	       if ($remoteurl!~/\.meta$/) {
                   2086:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2087:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2088:                   if ($mresponse->is_error()) {
                   2089: 		      unlink($filename.'.meta');
                   2090:                       &logthis(
1.672     albertel 2091:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2092:                   }
                   2093: 	       }
1.8       www      2094:                rename($transname,$filename);
1.607     raeburn  2095:                return 'ok';
1.8       www      2096:            }
1.290     www      2097:        }
1.8       www      2098:     }
1.330     www      2099: }
                   2100: 
                   2101: # ------------------------------------------------ Get server side include body
                   2102: sub ssi_body {
1.381     albertel 2103:     my ($filelink,%form)=@_;
1.606     matthew  2104:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2105:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2106:     }
1.953     www      2107:     my $output='';
                   2108:     my $response;
1.980     raeburn  2109:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2110:        ($output,$response)=&externalssi($filelink);
1.953     www      2111:     } else {
1.1004    droeschl 2112:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2113:        $filelink .= 'inhibitmenu=yes';
1.953     www      2114:        ($output,$response)=&ssi($filelink,%form);
                   2115:     }
1.778     albertel 2116:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2117:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2118:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2119:     if (wantarray) {
                   2120:         return ($output, $response);
                   2121:     } else {
                   2122:         return $output;
                   2123:     }
1.8       www      2124: }
                   2125: 
1.15      www      2126: # --------------------------------------------------------- Server Side Include
                   2127: 
1.782     albertel 2128: sub absolute_url {
                   2129:     my ($host_name) = @_;
                   2130:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2131:     if ($host_name eq '') {
                   2132: 	$host_name = $ENV{'SERVER_NAME'};
                   2133:     }
                   2134:     return $protocol.$host_name;
                   2135: }
                   2136: 
1.942     foxr     2137: #
                   2138: #   Server side include.
                   2139: # Parameters:
                   2140: #  fn     Possibly encrypted resource name/id.
                   2141: #  form   Hash that describes how the rendering should be done
                   2142: #         and other things.
1.944     foxr     2143: # Returns:
1.950     raeburn  2144: #   Scalar context: The content of the response.
                   2145: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2146: #     
1.15      www      2147: sub ssi {
                   2148: 
1.944     foxr     2149:     my ($fn,%form)=@_;
1.15      www      2150:     my $ua=new LWP::UserAgent;
1.23      www      2151:     my $request;
1.711     albertel 2152: 
                   2153:     $form{'no_update_last_known'}=1;
1.895     albertel 2154:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2155:     if (%form) {
1.782     albertel 2156:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2157:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2158:     } else {
1.782     albertel 2159:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2160:     }
                   2161: 
1.15      www      2162:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   2163:     my $response=$ua->request($request);
                   2164: 
1.944     foxr     2165:     if (wantarray) {
                   2166: 	return ($response->content, $response);
                   2167:     } else {
                   2168: 	return $response->content;
1.942     foxr     2169:     }
1.324     www      2170: }
                   2171: 
                   2172: sub externalssi {
                   2173:     my ($url)=@_;
                   2174:     my $ua=new LWP::UserAgent;
                   2175:     my $request=new HTTP::Request('GET',$url);
                   2176:     my $response=$ua->request($request);
1.954     raeburn  2177:     if (wantarray) {
                   2178:         return ($response->content, $response);
                   2179:     } else {
                   2180:         return $response->content;
                   2181:     }
1.15      www      2182: }
1.254     www      2183: 
1.492     albertel 2184: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2185: 
                   2186: sub allowuploaded {
                   2187:     my ($srcurl,$url)=@_;
                   2188:     $url=&clutter(&declutter($url));
                   2189:     my $dir=$url;
                   2190:     $dir=~s/\/[^\/]+$//;
                   2191:     my %httpref=();
                   2192:     my $httpurl=&hreflocation('',$url);
                   2193:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2194:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2195: }
1.477     raeburn  2196: 
1.478     albertel 2197: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2198: # input: action, courseID, current domain, intended
1.637     raeburn  2199: #        path to file, source of file, instruction to parse file for objects,
                   2200: #        ref to hash for embedded objects,
                   2201: #        ref to hash for codebase of java objects.
                   2202: #
1.485     raeburn  2203: # output: url to file (if action was uploaddoc), 
                   2204: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2205: #
1.478     albertel 2206: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2207: # course.
1.477     raeburn  2208: #
1.478     albertel 2209: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2210: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2211: #          course's home server.
1.477     raeburn  2212: #
1.478     albertel 2213: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2214: #          be copied from $source (current location) to 
                   2215: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2216: #         and will then be copied to
                   2217: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2218: #         course's home server.
1.485     raeburn  2219: #
1.481     raeburn  2220: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2221: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2222: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2223: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2224: #         in course's home server.
1.637     raeburn  2225: #
1.477     raeburn  2226: 
                   2227: sub process_coursefile {
1.638     albertel 2228:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  2229:     my $fetchresult;
1.638     albertel 2230:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2231:     if ($action eq 'propagate') {
1.638     albertel 2232:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2233: 			     $home);
1.481     raeburn  2234:     } else {
1.477     raeburn  2235:         my $fpath = '';
                   2236:         my $fname = $file;
1.478     albertel 2237:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2238:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2239:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2240:         if ($action eq 'copy') {
                   2241:             if ($source eq '') {
                   2242:                 $fetchresult = 'no source file';
                   2243:                 return $fetchresult;
                   2244:             } else {
                   2245:                 my $destination = $filepath.'/'.$fname;
                   2246:                 rename($source,$destination);
                   2247:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2248:                                  $home);
1.481     raeburn  2249:             }
                   2250:         } elsif ($action eq 'uploaddoc') {
                   2251:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2252:             print $fh $env{'form.'.$source};
1.481     raeburn  2253:             close($fh);
1.637     raeburn  2254:             if ($parser eq 'parse') {
1.1024    raeburn  2255:                 my $mm = new File::MMagic;
                   2256:                 my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
                   2257:                 if ($mime_type eq 'text/html') {
                   2258:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2259:                     unless ($parse_result eq 'ok') {
                   2260:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2261:                     }
1.637     raeburn  2262:                 }
                   2263:             }
1.477     raeburn  2264:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2265:                                  $home);
1.481     raeburn  2266:             if ($fetchresult eq 'ok') {
                   2267:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2268:             } else {
                   2269:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2270:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2271:                 return '/adm/notfound.html';
                   2272:             }
1.477     raeburn  2273:         }
                   2274:     }
1.485     raeburn  2275:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2276:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2277:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2278:     }
                   2279:     return $fetchresult;
                   2280: }
                   2281: 
1.637     raeburn  2282: sub build_filepath {
                   2283:     my ($fpath) = @_;
                   2284:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2285:     unless ($fpath eq '') {
                   2286:         my @parts=split('/',$fpath);
                   2287:         foreach my $part (@parts) {
                   2288:             $filepath.= '/'.$part;
                   2289:             if ((-e $filepath)!=1) {
                   2290:                 mkdir($filepath,0777);
                   2291:             }
                   2292:         }
                   2293:     }
                   2294:     return $filepath;
                   2295: }
                   2296: 
                   2297: sub store_edited_file {
1.638     albertel 2298:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2299:     my $file = $primary_url;
                   2300:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2301:     my $fpath = '';
                   2302:     my $fname = $file;
                   2303:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2304:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2305:     my $filepath = &build_filepath($fpath);
                   2306:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2307:     print $fh $content;
                   2308:     close($fh);
1.638     albertel 2309:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2310:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2311: 			  $home);
1.637     raeburn  2312:     if ($$fetchresult eq 'ok') {
                   2313:         return '/uploaded/'.$fpath.'/'.$fname;
                   2314:     } else {
1.638     albertel 2315:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2316: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2317:         return '/adm/notfound.html';
                   2318:     }
                   2319: }
                   2320: 
1.531     albertel 2321: sub clean_filename {
1.831     albertel 2322:     my ($fname,$args)=@_;
1.315     www      2323: # Replace Windows backslashes by forward slashes
1.257     www      2324:     $fname=~s/\\/\//g;
1.831     albertel 2325:     if (!$args->{'keep_path'}) {
                   2326:         # Get rid of everything but the actual filename
                   2327: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2328:     }
1.315     www      2329: # Replace spaces by underscores
                   2330:     $fname=~s/\s+/\_/g;
                   2331: # Replace all other weird characters by nothing
1.831     albertel 2332:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2333: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2334: # numbers
                   2335:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2336:     return $fname;
                   2337: }
1.1051    raeburn  2338: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2339: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2340: # image with the same aspect ratio as the original, but with dimensions which do 
                   2341: # not exceed $resizewidth and $resizeheight.
                   2342:  
1.984     neumanie 2343: sub resizeImage {
1.1051    raeburn  2344:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2345:     my $ima = Image::Magick->new;
                   2346:     my $resized;
                   2347:     if (-e $img_path) {
                   2348:         $ima->Read($img_path);
                   2349:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2350:             my $width = $ima->Get('width');
                   2351:             my $height = $ima->Get('height');
                   2352:             if ($width > $resizewidth) {
                   2353: 	        my $factor = $width/$resizewidth;
                   2354:                 my $newheight = $height/$factor;
                   2355:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2356:                 $resized = 1;
                   2357:             }
                   2358:         }
                   2359:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2360:             my $width = $ima->Get('width');
                   2361:             my $height = $ima->Get('height');
                   2362:             if ($height > $resizeheight) {
                   2363:                 my $factor = $height/$resizeheight;
                   2364:                 my $newwidth = $width/$factor;
                   2365:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2366:                 $resized = 1;
                   2367:             }
                   2368:         }
                   2369:         if ($resized) {
                   2370:             $ima->Write($img_path);
                   2371:         }
                   2372:     }
                   2373:     return;
1.977     amueller 2374: }
                   2375: 
1.608     albertel 2376: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2377: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 2378: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 2379: #        $coursedoc - if true up to the current course
                   2380: #                     if false
                   2381: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2382: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2383: #        $allfiles - reference to hash for embedded objects
                   2384: #        $codebase - reference to hash for codebase of java objects
                   2385: #        $desuname - username for permanent storage of uploaded file
                   2386: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2387: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2388: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2389: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2390: #        $resizeheight - height (pixels) to which to resize uploaded image
1.858     raeburn  2391: # 
1.686     albertel 2392: # output: url of file in userspace, or error: <message> 
                   2393: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2394: 
1.531     albertel 2395: sub userfileupload {
1.860     raeburn  2396:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1051    raeburn  2397:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight)=@_;
1.531     albertel 2398:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2399:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2400:     $fname=&clean_filename($fname);
1.315     www      2401: # See if there is anything left
1.257     www      2402:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2403:     chop($env{'form.'.$formname});
1.523     raeburn  2404:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2405:         my $now = time;
                   2406:         my $filepath = 'tmp/helprequests/'.$now;
                   2407:         my @parts=split(/\//,$filepath);
                   2408:         my $fullpath = $perlvar{'lonDaemons'};
                   2409:         for (my $i=0;$i<@parts;$i++) {
                   2410:             $fullpath .= '/'.$parts[$i];
                   2411:             if ((-e $fullpath)!=1) {
                   2412:                 mkdir($fullpath,0777);
                   2413:             }
                   2414:         }
                   2415:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2416:         print $fh $env{'form.'.$formname};
1.523     raeburn  2417:         close($fh);
1.741     raeburn  2418:         return $fullpath.'/'.$fname;
                   2419:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2420:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2421:                        '_'.$env{'user.domain'}.'/pending';
                   2422:         my @parts=split(/\//,$filepath);
                   2423:         my $fullpath = $perlvar{'lonDaemons'};
                   2424:         for (my $i=0;$i<@parts;$i++) {
                   2425:             $fullpath .= '/'.$parts[$i];
                   2426:             if ((-e $fullpath)!=1) {
                   2427:                 mkdir($fullpath,0777);
                   2428:             }
                   2429:         }
                   2430:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2431:         print $fh $env{'form.'.$formname};
                   2432:         close($fh);
                   2433:         return $fullpath.'/'.$fname;
1.523     raeburn  2434:     }
1.995     raeburn  2435:     if ($subdir eq 'scantron') {
                   2436:         $fname = 'scantron_orig_'.$fname;
                   2437:     } else {   
1.258     www      2438: # Create the directory if not present
1.995     raeburn  2439:         $fname="$subdir/$fname";
                   2440:     }
1.259     www      2441:     if ($coursedoc) {
1.638     albertel 2442: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2443: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2444:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2445:             return &finishuserfileupload($docuname,$docudom,
                   2446: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2447: 					 $codebase,$thumbwidth,$thumbheight,
                   2448:                                          $resizewidth,$resizeheight);
1.481     raeburn  2449:         } else {
1.620     albertel 2450:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2451:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2452: 				       $fname,$formname,$parser,
                   2453: 				       $allfiles,$codebase);
1.481     raeburn  2454:         }
1.719     banghart 2455:     } elsif (defined($destuname)) {
                   2456:         my $docuname=$destuname;
                   2457:         my $docudom=$destudom;
1.860     raeburn  2458: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2459: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2460:                                      $thumbwidth,$thumbheight,
                   2461:                                      $resizewidth,$resizeheight);
1.719     banghart 2462:         
1.259     www      2463:     } else {
1.638     albertel 2464:         my $docuname=$env{'user.name'};
                   2465:         my $docudom=$env{'user.domain'};
1.714     raeburn  2466:         if (exists($env{'form.group'})) {
                   2467:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2468:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2469:         }
1.860     raeburn  2470: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2471: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2472:                                      $thumbwidth,$thumbheight,
                   2473:                                      $resizewidth,$resizeheight);
1.259     www      2474:     }
1.271     www      2475: }
                   2476: 
                   2477: sub finishuserfileupload {
1.860     raeburn  2478:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1051    raeburn  2479:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight) = @_;
1.477     raeburn  2480:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2481:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2482:   
1.860     raeburn  2483:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2484:     $file=$fname;
                   2485:     if ($fname=~m|/|) {
                   2486:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2487: 	$path.=$fnamepath.'/';
                   2488:     }
1.259     www      2489:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2490:     my $count;
                   2491:     for ($count=4;$count<=$#parts;$count++) {
                   2492:         $filepath.="/$parts[$count]";
                   2493:         if ((-e $filepath)!=1) {
                   2494: 	    mkdir($filepath,0777);
                   2495:         }
                   2496:     }
1.984     neumanie 2497: 
1.258     www      2498: # Save the file
                   2499:     {
1.701     albertel 2500: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2501: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2502: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2503: 	    return '/adm/notfound.html';
                   2504: 	}
                   2505: 	if (!print FH ($env{'form.'.$formname})) {
                   2506: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2507: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2508: 	    return '/adm/notfound.html';
                   2509: 	}
1.570     albertel 2510: 	close(FH);
1.1051    raeburn  2511:         if ($resizewidth && $resizeheight) {
                   2512:             my $mm = new File::MMagic;
                   2513:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2514:             if ($mime_type =~ m{^image/}) {
                   2515: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2516:             }  
1.977     amueller 2517: 	}
1.258     www      2518:     }
1.637     raeburn  2519:     if ($parser eq 'parse') {
1.1024    raeburn  2520:         my $mm = new File::MMagic;
                   2521:         my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2522:         if ($mime_type eq 'text/html') {
                   2523:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2524:                                                        $allfiles,$codebase);
                   2525:             unless ($parse_result eq 'ok') {
                   2526:                 &logthis('Failed to parse '.$filepath.$file.
                   2527: 	   	         ' for embedded media: '.$parse_result); 
                   2528:             }
1.637     raeburn  2529:         }
                   2530:     }
1.860     raeburn  2531:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2532:         my $input = $filepath.'/'.$file;
                   2533:         my $output = $filepath.'/'.'tn-'.$file;
                   2534:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2535:         system("convert -sample $thumbsize $input $output");
                   2536:         if (-e $filepath.'/'.'tn-'.$file) {
                   2537:             $fetchthumb  = 1; 
                   2538:         }
                   2539:     }
1.858     raeburn  2540:  
1.259     www      2541: # Notify homeserver to grep it
                   2542: #
1.984     neumanie 2543:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2544:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2545:     if ($fetchresult eq 'ok') {
1.860     raeburn  2546:         if ($fetchthumb) {
                   2547:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2548:             if ($thumbresult ne 'ok') {
                   2549:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2550:                          $docuhome.': '.$thumbresult);
                   2551:             }
                   2552:         }
1.259     www      2553: #
1.258     www      2554: # Return the URL to it
1.494     albertel 2555:         return '/uploaded/'.$path.$file;
1.263     www      2556:     } else {
1.494     albertel 2557:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2558: 		 ': '.$fetchresult);
1.263     www      2559:         return '/adm/notfound.html';
1.858     raeburn  2560:     }
1.493     albertel 2561: }
                   2562: 
1.637     raeburn  2563: sub extract_embedded_items {
1.961     raeburn  2564:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2565:     my @state = ();
                   2566:     my %javafiles = (
                   2567:                       codebase => '',
                   2568:                       code => '',
                   2569:                       archive => ''
                   2570:                     );
                   2571:     my %mediafiles = (
                   2572:                       src => '',
                   2573:                       movie => '',
                   2574:                      );
1.648     raeburn  2575:     my $p;
                   2576:     if ($content) {
                   2577:         $p = HTML::LCParser->new($content);
                   2578:     } else {
1.961     raeburn  2579:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2580:     }
1.641     albertel 2581:     while (my $t=$p->get_token()) {
1.640     albertel 2582: 	if ($t->[0] eq 'S') {
                   2583: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2584: 	    push(@state, $tagname);
1.648     raeburn  2585:             if (lc($tagname) eq 'allow') {
                   2586:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2587:             }
1.640     albertel 2588: 	    if (lc($tagname) eq 'img') {
                   2589: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2590: 	    }
1.886     albertel 2591: 	    if (lc($tagname) eq 'a') {
                   2592: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2593: 	    }
1.645     raeburn  2594:             if (lc($tagname) eq 'script') {
                   2595:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2596:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2597:                 } else {
                   2598:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2599:                 }
                   2600:             }
                   2601:             if (lc($tagname) eq 'link') {
                   2602:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2603:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2604:                 }
                   2605:             }
1.640     albertel 2606: 	    if (lc($tagname) eq 'object' ||
                   2607: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2608: 		foreach my $item (keys(%javafiles)) {
                   2609: 		    $javafiles{$item} = '';
                   2610: 		}
                   2611: 	    }
                   2612: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2613: 		my $name = lc($attr->{'name'});
                   2614: 		foreach my $item (keys(%javafiles)) {
                   2615: 		    if ($name eq $item) {
                   2616: 			$javafiles{$item} = $attr->{'value'};
                   2617: 			last;
                   2618: 		    }
                   2619: 		}
                   2620: 		foreach my $item (keys(%mediafiles)) {
                   2621: 		    if ($name eq $item) {
                   2622: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2623: 			last;
                   2624: 		    }
                   2625: 		}
                   2626: 	    }
                   2627: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2628: 		foreach my $item (keys(%javafiles)) {
                   2629: 		    if ($attr->{$item}) {
                   2630: 			$javafiles{$item} = $attr->{$item};
                   2631: 			last;
                   2632: 		    }
                   2633: 		}
                   2634: 		foreach my $item (keys(%mediafiles)) {
                   2635: 		    if ($attr->{$item}) {
                   2636: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2637: 			last;
                   2638: 		    }
                   2639: 		}
                   2640: 	    }
                   2641: 	} elsif ($t->[0] eq 'E') {
                   2642: 	    my ($tagname) = ($t->[1]);
                   2643: 	    if ($javafiles{'codebase'} ne '') {
                   2644: 		$javafiles{'codebase'} .= '/';
                   2645: 	    }  
                   2646: 	    if (lc($tagname) eq 'applet' ||
                   2647: 		lc($tagname) eq 'object' ||
                   2648: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2649: 		) {
                   2650: 		foreach my $item (keys(%javafiles)) {
                   2651: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2652: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2653: 			&add_filetype($allfiles,$file,$item);
                   2654: 		    }
                   2655: 		}
                   2656: 	    } 
                   2657: 	    pop @state;
                   2658: 	}
                   2659:     }
1.637     raeburn  2660:     return 'ok';
                   2661: }
                   2662: 
1.639     albertel 2663: sub add_filetype {
                   2664:     my ($allfiles,$file,$type)=@_;
                   2665:     if (exists($allfiles->{$file})) {
                   2666: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2667: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2668: 	}
                   2669:     } else {
                   2670: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2671:     }
                   2672: }
                   2673: 
1.493     albertel 2674: sub removeuploadedurl {
1.984     neumanie 2675:     my ($url)=@_;	
                   2676:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2677:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2678: }
                   2679: 
                   2680: sub removeuserfile {
                   2681:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2682:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2683:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2684:     if ($result eq 'ok') {	
1.798     raeburn  2685:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2686:             my $metafile = $fname.'.meta';
                   2687:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2688: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2689:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2690:             my $sqlresult = 
1.823     albertel 2691:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2692:                                         'portfolio_metadata',$group,
                   2693:                                         'delete');
1.798     raeburn  2694:         }
                   2695:     }
                   2696:     return $result;
1.257     www      2697: }
1.15      www      2698: 
1.530     albertel 2699: sub mkdiruserfile {
                   2700:     my ($docuname,$docudom,$dir)=@_;
                   2701:     my $home=&homeserver($docuname,$docudom);
                   2702:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2703: }
                   2704: 
1.531     albertel 2705: sub renameuserfile {
                   2706:     my ($docuname,$docudom,$old,$new)=@_;
                   2707:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2708:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2709:                         &escape("$old").':'.&escape("$new"),$home);
                   2710:     if ($result eq 'ok') {
                   2711:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2712:             my $oldmeta = $old.'.meta';
                   2713:             my $newmeta = $new.'.meta';
                   2714:             my $metaresult = 
                   2715:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2716: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2717:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2718:             my $sqlresult = 
1.823     albertel 2719:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2720:                                         'portfolio_metadata',$group,
                   2721:                                         'delete');
1.798     raeburn  2722:         }
                   2723:     }
                   2724:     return $result;
1.531     albertel 2725: }
                   2726: 
1.14      www      2727: # ------------------------------------------------------------------------- Log
                   2728: 
                   2729: sub log {
                   2730:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2731:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2732: }
                   2733: 
                   2734: # ------------------------------------------------------------------ Course Log
1.352     www      2735: #
                   2736: # This routine flushes several buffers of non-mission-critical nature
                   2737: #
1.157     www      2738: 
                   2739: sub flushcourselogs {
1.352     www      2740:     &logthis('Flushing log buffers');
                   2741: #
                   2742: # course logs
                   2743: # This is a log of all transactions in a course, which can be used
                   2744: # for data mining purposes
                   2745: #
                   2746: # It also collects the courseid database, which lists last transaction
                   2747: # times and course titles for all courseids
                   2748: #
                   2749:     my %courseidbuffer=();
1.921     raeburn  2750:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2751:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2752: 		          &escape($courselogs{$crsid}),
                   2753: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2754: 	    delete $courselogs{$crsid};
                   2755:         } else {
                   2756:             &logthis('Failed to flush log buffer for '.$crsid);
                   2757:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2758:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2759:                         " exceeded maximum size, deleting.</font>");
                   2760:                delete $courselogs{$crsid};
                   2761:             }
1.352     www      2762:         }
1.920     raeburn  2763:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2764:             'description' => $coursedescrbuf{$crsid},
                   2765:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2766:             'type'        => $coursetypebuf{$crsid},
                   2767:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2768:         };
1.191     harris41 2769:     }
1.352     www      2770: #
                   2771: # Write course id database (reverse lookup) to homeserver of courses 
                   2772: # Is used in pickcourse
                   2773: #
1.840     albertel 2774:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2775:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2776:                                     $courseidbuffer{$crs_home},
                   2777:                                     $crs_home,'timeonly');
1.352     www      2778:     }
                   2779: #
                   2780: # File accesses
                   2781: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2782: #
1.449     matthew  2783:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2784:         if ($entry =~ /___count$/) {
                   2785:             my ($dom,$name);
1.807     albertel 2786:             ($dom,$name,undef)=
1.811     albertel 2787: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2788:             if (! defined($dom) || $dom eq '' || 
                   2789:                 ! defined($name) || $name eq '') {
1.620     albertel 2790:                 my $cid = $env{'request.course.id'};
                   2791:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2792:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2793:             }
1.450     matthew  2794:             my $value = $accesshash{$entry};
                   2795:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2796:             my %temphash=($url => $value);
1.449     matthew  2797:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2798:             if ($result eq 'ok') {
                   2799:                 delete $accesshash{$entry};
                   2800:             } elsif ($result eq 'unknown_cmd') {
                   2801:                 # Target server has old code running on it.
1.450     matthew  2802:                 my %temphash=($entry => $value);
1.449     matthew  2803:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2804:                     delete $accesshash{$entry};
                   2805:                 }
                   2806:             }
                   2807:         } else {
1.811     albertel 2808:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2809:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2810:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2811:                 delete $accesshash{$entry};
                   2812:             }
1.185     www      2813:         }
1.191     harris41 2814:     }
1.352     www      2815: #
                   2816: # Roles
                   2817: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2818: #
1.800     albertel 2819:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2820:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2821: 	    split(/\:/,$entry);
                   2822:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2823:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2824:                 $rudom,$runame) eq 'ok') {
                   2825: 	    delete $userrolehash{$entry};
                   2826:         }
                   2827:     }
1.662     raeburn  2828: #
                   2829: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2830: #
                   2831:     my %domrolebuffer = ();
1.1000    raeburn  2832:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 2833:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2834:         if ($domrolebuffer{$rudom}) {
                   2835:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2836:                       '='.&escape($domainrolehash{$entry});
                   2837:         } else {
                   2838:             $domrolebuffer{$rudom}.=&escape($entry).
                   2839:                       '='.&escape($domainrolehash{$entry});
                   2840:         }
                   2841:         delete $domainrolehash{$entry};
                   2842:     }
                   2843:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2844: 	my %servers = &get_servers($dom,'library');
                   2845: 	foreach my $tryserver (keys(%servers)) {
                   2846: 	    unless (&reply('domroleput:'.$dom.':'.
                   2847: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2848: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2849: 	    }
1.662     raeburn  2850:         }
                   2851:     }
1.186     www      2852:     $dumpcount++;
1.157     www      2853: }
                   2854: 
                   2855: sub courselog {
                   2856:     my $what=shift;
1.158     www      2857:     $what=time.':'.$what;
1.620     albertel 2858:     unless ($env{'request.course.id'}) { return ''; }
                   2859:     $coursedombuf{$env{'request.course.id'}}=
                   2860:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2861:     $coursenumbuf{$env{'request.course.id'}}=
                   2862:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2863:     $coursehombuf{$env{'request.course.id'}}=
                   2864:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2865:     $coursedescrbuf{$env{'request.course.id'}}=
                   2866:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2867:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2868:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2869:     $courseownerbuf{$env{'request.course.id'}}=
                   2870:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2871:     $coursetypebuf{$env{'request.course.id'}}=
                   2872:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2873:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2874: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2875:     } else {
1.620     albertel 2876: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2877:     }
1.620     albertel 2878:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2879: 	&flushcourselogs();
                   2880:     }
1.158     www      2881: }
                   2882: 
                   2883: sub courseacclog {
                   2884:     my $fnsymb=shift;
1.620     albertel 2885:     unless ($env{'request.course.id'}) { return ''; }
                   2886:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2887:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2888:         $what.=':POST';
1.583     matthew  2889:         # FIXME: Probably ought to escape things....
1.800     albertel 2890: 	foreach my $key (keys(%env)) {
                   2891:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2892:                 my $formitem = $1;
                   2893:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2894:                     $what.=':'.$formitem.'='.$env{$key};
                   2895:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2896:                     $what.=':'.$formitem.'='.$env{$key};
                   2897:                 }
1.158     www      2898:             }
1.191     harris41 2899:         }
1.583     matthew  2900:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2901:         # FIXME: We should not be depending on a form parameter that someone
                   2902:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2903:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2904:             $what.= ':POST';
                   2905:             # FIXME: Probably ought to escape things....
                   2906:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2907:                                  'crsdiscuss') {
1.620     albertel 2908:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2909:             }
                   2910:         }
1.158     www      2911:     }
                   2912:     &courselog($what);
1.149     www      2913: }
                   2914: 
1.185     www      2915: sub countacc {
                   2916:     my $url=&declutter(shift);
1.458     matthew  2917:     return if (! defined($url) || $url eq '');
1.620     albertel 2918:     unless ($env{'request.course.id'}) { return ''; }
                   2919:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2920:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2921:     $accesshash{$key}++;
1.185     www      2922: }
1.349     www      2923: 
1.361     www      2924: sub linklog {
                   2925:     my ($from,$to)=@_;
                   2926:     $from=&declutter($from);
                   2927:     $to=&declutter($to);
                   2928:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2929:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2930: }
                   2931:   
1.349     www      2932: sub userrolelog {
                   2933:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2934:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2935:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2936:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  2937:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      2938:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2939:        $userrolehash
                   2940:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2941:                     =$tend.':'.$tstart;
1.662     raeburn  2942:     }
1.898     albertel 2943:     if (($env{'request.role'} =~ /dc\./) &&
                   2944: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2945: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  2946: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   2947:          ($trole=~/^co/))) {
1.898     albertel 2948:        $userrolehash
                   2949:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2950:                     =$tend.':'.$tstart;
                   2951:     }
1.662     raeburn  2952:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2953:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2954:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2955:         ($trole=~/^sc/)) {
                   2956:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2957:        $domainrolehash
                   2958:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2959:                     = $tend.':'.$tstart;
                   2960:     }
1.351     www      2961: }
                   2962: 
1.957     raeburn  2963: sub courserolelog {
                   2964:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2965:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2966:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2967:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  2968:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   2969:         ($trole eq 'co')) {
1.957     raeburn  2970:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2971:             my $cdom = $1;
                   2972:             my $cnum = $2;
                   2973:             my $sec = $3;
                   2974:             my $namespace = 'rolelog';
                   2975:             my %storehash = (
                   2976:                                role    => $trole,
                   2977:                                start   => $tstart,
                   2978:                                end     => $tend,
                   2979:                                selfenroll => $selfenroll,
                   2980:                                context    => $context,
                   2981:                             );
                   2982:             if ($trole eq 'gr') {
                   2983:                 $namespace = 'groupslog';
                   2984:                 $storehash{'group'} = $sec;
                   2985:             } else {
                   2986:                 $storehash{'section'} = $sec;
                   2987:             }
                   2988:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  2989:             if (($trole ne 'st') || ($sec ne '')) {
                   2990:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   2991:             }
1.957     raeburn  2992:         }
                   2993:     }
                   2994:     return;
                   2995: }
                   2996: 
1.351     www      2997: sub get_course_adv_roles {
1.948     raeburn  2998:     my ($cid,$codes) = @_;
1.620     albertel 2999:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3000:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3001:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3002:     my %nothide=();
1.800     albertel 3003:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3004:         if ($user !~ /:/) {
                   3005: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3006:         } else {
                   3007:             $nothide{$user}=1;
                   3008:         }
1.470     www      3009:     }
1.351     www      3010:     my %returnhash=();
                   3011:     my %dumphash=
                   3012:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3013:     my $now=time;
1.997     raeburn  3014:     my %privileged;
1.1000    raeburn  3015:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3016: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3017:         if (($tstart) && ($tstart<0)) { next; }
                   3018:         if (($tend) && ($tend<$now)) { next; }
                   3019:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3020:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3021: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3022:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3023:             my %dompersonnel =
1.998     raeburn  3024:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3025:             $privileged{$domain} = {};
                   3026:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3027:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3028:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3029:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3030:                         $privileged{$udom}{$uname} = 1;
                   3031:                     }
                   3032:                 }
                   3033:             }
                   3034:         }
                   3035:         if ((exists($privileged{$domain}{$username})) && 
                   3036:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3037: 	if ($role eq 'cr') { next; }
1.948     raeburn  3038:         if ($codes) {
                   3039:             if ($section) { $role .= ':'.$section; }
                   3040:             if ($returnhash{$role}) {
                   3041:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3042:             } else {
                   3043:                 $returnhash{$role}=$username.':'.$domain;
                   3044:             }
1.351     www      3045:         } else {
1.988     raeburn  3046:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3047:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3048:             if ($returnhash{$key}) {
                   3049: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3050:             } else {
                   3051:                 $returnhash{$key}=$username.':'.$domain;
                   3052:             }
1.351     www      3053:         }
1.948     raeburn  3054:     }
1.400     www      3055:     return %returnhash;
                   3056: }
                   3057: 
                   3058: sub get_my_roles {
1.937     raeburn  3059:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3060:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3061:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3062:     my (%dumphash,%nothide);
1.858     raeburn  3063:     if ($context eq 'userroles') { 
1.1056.4.10! raeburn  3064:         my $extra = &freeze_escape({'skipcheck' => 1});
        !          3065:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858     raeburn  3066:     } else {
                   3067:         %dumphash=
1.400     www      3068:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3069:         if ($hidepriv) {
                   3070:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3071:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3072:                 if ($user !~ /:/) {
                   3073:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3074:                 } else {
                   3075:                     $nothide{$user} = 1;
                   3076:                 }
                   3077:             }
                   3078:         }
1.858     raeburn  3079:     }
1.400     www      3080:     my %returnhash=();
                   3081:     my $now=time;
1.999     raeburn  3082:     my %privileged;
1.800     albertel 3083:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3084:         my ($role,$tend,$tstart);
                   3085:         if ($context eq 'userroles') {
                   3086: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3087:         } else {
                   3088:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3089:         }
1.400     www      3090:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3091:         my $status = 'active';
1.939     raeburn  3092:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3093:             $status = 'previous';
                   3094:         } 
                   3095:         if (($tstart) && ($now<$tstart)) {
                   3096:             $status = 'future';
                   3097:         }
                   3098:         if (ref($types) eq 'ARRAY') {
                   3099:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3100:                 next;
                   3101:             } 
                   3102:         } else {
                   3103:             if ($status ne 'active') {
                   3104:                 next;
                   3105:             }
                   3106:         }
1.867     raeburn  3107:         my ($rolecode,$username,$domain,$section,$area);
                   3108:         if ($context eq 'userroles') {
                   3109:             ($area,$rolecode) = split(/_/,$entry);
                   3110:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3111:         } else {
                   3112:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3113:         }
1.832     raeburn  3114:         if (ref($roledoms) eq 'ARRAY') {
                   3115:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3116:                 next;
                   3117:             }
                   3118:         }
                   3119:         if (ref($roles) eq 'ARRAY') {
                   3120:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3121:                 if ($role =~ /^cr\//) {
                   3122:                     if (!grep(/^cr$/,@{$roles})) {
                   3123:                         next;
                   3124:                     }
                   3125:                 } else {
                   3126:                     next;
                   3127:                 }
1.832     raeburn  3128:             }
1.867     raeburn  3129:         }
1.937     raeburn  3130:         if ($hidepriv) {
1.999     raeburn  3131:             if ($context eq 'userroles') {
                   3132:                 if ((&privileged($username,$domain)) &&
                   3133:                     (!$nothide{$username.':'.$domain})) {
                   3134:                     next;
                   3135:                 }
                   3136:             } else {
                   3137:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3138:                     my %dompersonnel =
                   3139:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3140:                     $privileged{$domain} = {};
                   3141:                     if (keys(%dompersonnel)) {
                   3142:                         foreach my $server (keys(%dompersonnel)) {
                   3143:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3144:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3145:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3146:                                     $privileged{$udom}{$uname} = $trole;
                   3147:                                 }
                   3148:                             }
                   3149:                         }
                   3150:                     }
                   3151:                 }
                   3152:                 if (exists($privileged{$domain}{$username})) {
                   3153:                     if (!$nothide{$username.':'.$domain}) {
                   3154:                         next;
                   3155:                     }
                   3156:                 }
1.937     raeburn  3157:             }
                   3158:         }
1.933     raeburn  3159:         if ($withsec) {
                   3160:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3161:                 $tstart.':'.$tend;
                   3162:         } else {
                   3163:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3164:         }
1.832     raeburn  3165:     }
1.373     www      3166:     return %returnhash;
1.399     www      3167: }
                   3168: 
                   3169: # ----------------------------------------------------- Frontpage Announcements
                   3170: #
                   3171: #
                   3172: 
                   3173: sub postannounce {
                   3174:     my ($server,$text)=@_;
1.844     albertel 3175:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3176:     unless ($text=~/\w/) { $text=''; }
                   3177:     return &reply('setannounce:'.&escape($text),$server);
                   3178: }
                   3179: 
                   3180: sub getannounce {
1.448     albertel 3181: 
                   3182:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3183: 	my $announcement='';
1.800     albertel 3184: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3185: 	close($fh);
1.399     www      3186: 	if ($announcement=~/\w/) { 
                   3187: 	    return 
                   3188:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3189:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3190: 	} else {
                   3191: 	    return '';
                   3192: 	}
                   3193:     } else {
                   3194: 	return '';
                   3195:     }
1.351     www      3196: }
1.353     www      3197: 
                   3198: # ---------------------------------------------------------- Course ID routines
                   3199: # Deal with domain's nohist_courseid.db files
                   3200: #
                   3201: 
                   3202: sub courseidput {
1.921     raeburn  3203:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3204:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3205:     my $outcome;
                   3206:     if ($caller eq 'timeonly') {
                   3207:         my $cids = '';
                   3208:         foreach my $item (keys(%$storehash)) {
                   3209:             $cids.=&escape($item).'&';
                   3210:         }
                   3211:         $cids=~s/\&$//;
                   3212:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3213:                           $coursehome);       
                   3214:     } else {
                   3215:         my $items = '';
                   3216:         foreach my $item (keys(%$storehash)) {
                   3217:             $items.= &escape($item).'='.
                   3218:                      &freeze_escape($$storehash{$item}).'&';
                   3219:         }
                   3220:         $items=~s/\&$//;
                   3221:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3222:                           $coursehome);
1.918     raeburn  3223:     }
                   3224:     if ($outcome eq 'unknown_cmd') {
                   3225:         my $what;
                   3226:         foreach my $cid (keys(%$storehash)) {
                   3227:             $what .= &escape($cid).'=';
1.921     raeburn  3228:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3229:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3230:             }
                   3231:             $what =~ s/\:$/&/;
                   3232:         }
                   3233:         $what =~ s/\&$//;  
                   3234:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3235:     } else {
                   3236:         return $outcome;
                   3237:     }
1.353     www      3238: }
                   3239: 
                   3240: sub courseiddump {
1.921     raeburn  3241:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3242:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3243:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1056.4.3  raeburn  3244:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3245:     my $as_hash = 1;
                   3246:     my %returnhash;
                   3247:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3248:     my %libserv = &all_library();
                   3249:     foreach my $tryserver (keys(%libserv)) {
                   3250:         if ( (  $hostidflag == 1 
                   3251: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3252: 	     || (!defined($hostidflag)) ) {
                   3253: 
1.918     raeburn  3254: 	    if (($domfilter eq '') ||
                   3255: 		(&host_domain($tryserver) eq $domfilter)) {
                   3256:                 my $rep = 
                   3257:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3258:                          $sincefilter.':'.&escape($descfilter).':'.
                   3259:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3260:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3261:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3262:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3263:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3264:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3265:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1056.4.3  raeburn  3266:                          &escape($creationcontext).':'.$domcloner,
                   3267:                          $tryserver);
1.918     raeburn  3268:                 my @pairs=split(/\&/,$rep);
                   3269:                 foreach my $item (@pairs) {
                   3270:                     my ($key,$value)=split(/\=/,$item,2);
                   3271:                     $key = &unescape($key);
                   3272:                     next if ($key =~ /^error: 2 /);
                   3273:                     my $result = &thaw_unescape($value);
                   3274:                     if (ref($result) eq 'HASH') {
                   3275:                         $returnhash{$key}=$result;
                   3276:                     } else {
1.921     raeburn  3277:                         my @responses = split(/:/,$value);
                   3278:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3279:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3280:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3281:                         }
1.1008    raeburn  3282:                     }
1.353     www      3283:                 }
                   3284:             }
                   3285:         }
                   3286:     }
                   3287:     return %returnhash;
                   3288: }
                   3289: 
1.1055    raeburn  3290: sub courselastaccess {
                   3291:     my ($cdom,$cnum,$hostidref) = @_;
                   3292:     my %returnhash;
                   3293:     if ($cdom && $cnum) {
                   3294:         my $chome = &homeserver($cnum,$cdom);
                   3295:         if ($chome ne 'no_host') {
                   3296:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3297:             &extract_lastaccess(\%returnhash,$rep);
                   3298:         }
                   3299:     } else {
                   3300:         if (!$cdom) { $cdom=''; }
                   3301:         my %libserv = &all_library();
                   3302:         foreach my $tryserver (keys(%libserv)) {
                   3303:             if (ref($hostidref) eq 'ARRAY') {
                   3304:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3305:             } 
                   3306:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3307:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3308:                 &extract_lastaccess(\%returnhash,$rep);
                   3309:             }
                   3310:         }
                   3311:     }
                   3312:     return %returnhash;
                   3313: }
                   3314: 
                   3315: sub extract_lastaccess {
                   3316:     my ($returnhash,$rep) = @_;
                   3317:     if (ref($returnhash) eq 'HASH') {
                   3318:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3319:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3320:                  $rep eq '') {
                   3321:             my @pairs=split(/\&/,$rep);
                   3322:             foreach my $item (@pairs) {
                   3323:                 my ($key,$value)=split(/\=/,$item,2);
                   3324:                 $key = &unescape($key);
                   3325:                 next if ($key =~ /^error: 2 /);
                   3326:                 $returnhash->{$key} = &thaw_unescape($value);
                   3327:             }
                   3328:         }
                   3329:     }
                   3330:     return;
                   3331: }
                   3332: 
1.658     raeburn  3333: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3334: 
                   3335: sub dcmailput {
1.685     raeburn  3336:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3337:     my $status = &Apache::lonnet::critical(
1.740     www      3338:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3339:        &escape($message),$server);
1.662     raeburn  3340:     return $status;
                   3341: }
                   3342: 
1.658     raeburn  3343: sub dcmaildump {
                   3344:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3345:     my %returnhash=();
1.846     albertel 3346: 
                   3347:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3348:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3349:                                                          &escape($enddate).':';
                   3350: 	my @esc_senders=map { &escape($_)} @$senders;
                   3351: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3352: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3353:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3354:             if (($key) && ($value)) {
                   3355:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3356:             }
                   3357:         }
                   3358:     }
                   3359:     return %returnhash;
                   3360: }
1.662     raeburn  3361: # ---------------------------------------------------------- Domain roles
                   3362: 
                   3363: sub get_domain_roles {
                   3364:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3365:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3366:         $startdate = '.';
                   3367:     }
1.1018    raeburn  3368:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3369:         $enddate = '.';
                   3370:     }
1.922     raeburn  3371:     my $rolelist;
                   3372:     if (ref($roles) eq 'ARRAY') {
                   3373:         $rolelist = join(':',@{$roles});
                   3374:     }
1.662     raeburn  3375:     my %personnel = ();
1.841     albertel 3376: 
                   3377:     my %servers = &get_servers($dom,'library');
                   3378:     foreach my $tryserver (keys(%servers)) {
                   3379: 	%{$personnel{$tryserver}}=();
                   3380: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3381: 					    &escape($startdate).':'.
                   3382: 					    &escape($enddate).':'.
                   3383: 					    &escape($rolelist), $tryserver))) {
                   3384: 	    my ($key,$value) = split(/\=/,$line,2);
                   3385: 	    if (($key) && ($value)) {
                   3386: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3387: 	    }
                   3388: 	}
1.662     raeburn  3389:     }
                   3390:     return %personnel;
                   3391: }
1.658     raeburn  3392: 
1.149     www      3393: # ----------------------------------------------------------- Check out an item
                   3394: 
1.504     albertel 3395: sub get_first_access {
                   3396:     my ($type,$argsymb)=@_;
1.790     albertel 3397:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3398:     if ($argsymb) { $symb=$argsymb; }
                   3399:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3400:     if ($type eq 'course') {
                   3401: 	$res='course';
                   3402:     } elsif ($type eq 'map') {
1.588     albertel 3403: 	$res=&symbread($map);
                   3404:     } else {
                   3405: 	$res=$symb;
                   3406:     }
                   3407:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3408:     return $times{"$courseid\0$res"};
1.504     albertel 3409: }
                   3410: 
                   3411: sub set_first_access {
                   3412:     my ($type)=@_;
1.790     albertel 3413:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3414:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3415:     if ($type eq 'course') {
                   3416: 	$res='course';
                   3417:     } elsif ($type eq 'map') {
1.588     albertel 3418: 	$res=&symbread($map);
                   3419:     } else {
                   3420: 	$res=$symb;
                   3421:     }
                   3422:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3423:     if (!$firstaccess) {
1.588     albertel 3424: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3425:     }
                   3426:     return 'already_set';
1.504     albertel 3427: }
                   3428: 
1.149     www      3429: sub checkout {
                   3430:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   3431:     my $now=time;
                   3432:     my $lonhost=$perlvar{'lonHostID'};
                   3433:     my $infostr=&escape(
1.234     www      3434:                  'CHECKOUTTOKEN&'.
1.149     www      3435:                  $tuname.'&'.
                   3436:                  $tudom.'&'.
                   3437:                  $tcrsid.'&'.
                   3438:                  $symb.'&'.
                   3439: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   3440:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      3441:     if ($token=~/^error\:/) { 
1.672     albertel 3442:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3443:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3444:                  "</font>");
                   3445:         return ''; 
                   3446:     }
                   3447: 
1.149     www      3448:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   3449:     $token=~tr/a-z/A-Z/;
                   3450: 
1.153     www      3451:     my %infohash=('resource.0.outtoken' => $token,
                   3452:                   'resource.0.checkouttime' => $now,
                   3453:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      3454: 
                   3455:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3456:        return '';
1.151     www      3457:     } else {
1.672     albertel 3458:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3459:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3460:                  "</font>");
1.149     www      3461:     }    
                   3462: 
                   3463:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3464:                          &escape('Checkout '.$infostr.' - '.
                   3465:                                                  $token)) ne 'ok') {
                   3466: 	return '';
1.151     www      3467:     } else {
1.672     albertel 3468:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3469:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3470:                  "</font>");
1.149     www      3471:     }
1.151     www      3472:     return $token;
1.149     www      3473: }
                   3474: 
                   3475: # ------------------------------------------------------------ Check in an item
                   3476: 
                   3477: sub checkin {
                   3478:     my $token=shift;
1.150     www      3479:     my $now=time;
                   3480:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3481:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3482:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3483:     $dtoken=~s/\W/\_/g;
1.234     www      3484:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3485:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3486: 
1.154     www      3487:     unless (($tuname) && ($tudom)) {
                   3488:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3489:         return '';
                   3490:     }
                   3491:     
                   3492:     unless (&allowed('mgr',$tcrsid)) {
                   3493:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3494:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3495:         return '';
                   3496:     }
                   3497: 
1.153     www      3498:     my %infohash=('resource.0.intoken' => $token,
                   3499:                   'resource.0.checkintime' => $now,
                   3500:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3501: 
                   3502:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3503:        return '';
                   3504:     }    
                   3505: 
                   3506:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3507:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3508: 	return '';
                   3509:     }
                   3510: 
                   3511:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3512: }
                   3513: 
                   3514: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3515: 
                   3516: sub expirespread {
                   3517:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3518:     my $cid=$env{'request.course.id'}; 
1.110     www      3519:     if ($cid) {
                   3520:        my $now=time;
                   3521:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3522:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3523:                             $env{'course.'.$cid.'.num'}.
1.110     www      3524: 	        	    ':nohist_expirationdates:'.
                   3525:                             &escape($key).'='.$now,
1.620     albertel 3526:                             $env{'course.'.$cid.'.home'})
1.110     www      3527:     }
                   3528:     return 'ok';
1.14      www      3529: }
                   3530: 
1.109     www      3531: # ----------------------------------------------------- Devalidate Spreadsheets
                   3532: 
                   3533: sub devalidate {
1.325     www      3534:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3535:     my $cid=$env{'request.course.id'}; 
1.109     www      3536:     if ($cid) {
1.391     matthew  3537:         # delete the stored spreadsheets for
                   3538:         # - the student level sheet of this user in course's homespace
                   3539:         # - the assessment level sheet for this resource 
                   3540:         #   for this user in user's homespace
1.553     albertel 3541: 	# - current conditional state info
1.325     www      3542: 	my $key=$uname.':'.$udom.':';
1.109     www      3543:         my $status=
1.299     matthew  3544: 	    &del('nohist_calculatedsheets',
1.391     matthew  3545: 		 [$key.'studentcalc:'],
1.620     albertel 3546: 		 $env{'course.'.$cid.'.domain'},
                   3547: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3548: 		.' '.
                   3549: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3550: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3551:         unless ($status eq 'ok ok') {
                   3552:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3553:                     $uname.' at '.$udom.' for '.
1.109     www      3554: 		    $symb.': '.$status);
1.133     albertel 3555:         }
1.553     albertel 3556: 	&delenv('user.state.'.$cid);
1.109     www      3557:     }
                   3558: }
                   3559: 
1.265     albertel 3560: sub get_scalar {
                   3561:     my ($string,$end) = @_;
                   3562:     my $value;
                   3563:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3564: 	$value = $1;
                   3565:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3566: 	$value = $1;
                   3567:     }
                   3568:     return &unescape($value);
                   3569: }
                   3570: 
                   3571: sub array2str {
                   3572:   my (@array) = @_;
                   3573:   my $result=&arrayref2str(\@array);
                   3574:   $result=~s/^__ARRAY_REF__//;
                   3575:   $result=~s/__END_ARRAY_REF__$//;
                   3576:   return $result;
                   3577: }
                   3578: 
1.204     albertel 3579: sub arrayref2str {
                   3580:   my ($arrayref) = @_;
1.265     albertel 3581:   my $result='__ARRAY_REF__';
1.204     albertel 3582:   foreach my $elem (@$arrayref) {
1.265     albertel 3583:     if(ref($elem) eq 'ARRAY') {
                   3584:       $result.=&arrayref2str($elem).'&';
                   3585:     } elsif(ref($elem) eq 'HASH') {
                   3586:       $result.=&hashref2str($elem).'&';
                   3587:     } elsif(ref($elem)) {
                   3588:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3589:     } else {
                   3590:       $result.=&escape($elem).'&';
                   3591:     }
                   3592:   }
                   3593:   $result=~s/\&$//;
1.265     albertel 3594:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3595:   return $result;
                   3596: }
                   3597: 
1.168     albertel 3598: sub hash2str {
1.204     albertel 3599:   my (%hash) = @_;
                   3600:   my $result=&hashref2str(\%hash);
1.265     albertel 3601:   $result=~s/^__HASH_REF__//;
                   3602:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3603:   return $result;
                   3604: }
                   3605: 
                   3606: sub hashref2str {
                   3607:   my ($hashref)=@_;
1.265     albertel 3608:   my $result='__HASH_REF__';
1.800     albertel 3609:   foreach my $key (sort(keys(%$hashref))) {
                   3610:     if (ref($key) eq 'ARRAY') {
                   3611:       $result.=&arrayref2str($key).'=';
                   3612:     } elsif (ref($key) eq 'HASH') {
                   3613:       $result.=&hashref2str($key).'=';
                   3614:     } elsif (ref($key)) {
1.265     albertel 3615:       $result.='=';
1.800     albertel 3616:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3617:     } else {
1.800     albertel 3618: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3619:     }
                   3620: 
1.800     albertel 3621:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3622:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3623:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3624:       $result.=&hashref2str($hashref->{$key}).'&';
                   3625:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3626:        $result.='&';
1.800     albertel 3627:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3628:     } else {
1.800     albertel 3629:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3630:     }
                   3631:   }
1.168     albertel 3632:   $result=~s/\&$//;
1.265     albertel 3633:   $result .= '__END_HASH_REF__';
1.168     albertel 3634:   return $result;
                   3635: }
                   3636: 
                   3637: sub str2hash {
1.265     albertel 3638:     my ($string)=@_;
                   3639:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3640:     return %$hash;
                   3641: }
                   3642: 
                   3643: sub str2hashref {
1.168     albertel 3644:   my ($string) = @_;
1.265     albertel 3645: 
                   3646:   my %hash;
                   3647: 
                   3648:   if($string !~ /^__HASH_REF__/) {
                   3649:       if (! ($string eq '' || !defined($string))) {
                   3650: 	  $hash{'error'}='Not hash reference';
                   3651:       }
                   3652:       return (\%hash, $string);
                   3653:   }
                   3654: 
                   3655:   $string =~ s/^__HASH_REF__//;
                   3656: 
                   3657:   while($string !~ /^__END_HASH_REF__/) {
                   3658:       #key
                   3659:       my $key='';
                   3660:       if($string =~ /^__HASH_REF__/) {
                   3661:           ($key, $string)=&str2hashref($string);
                   3662:           if(defined($key->{'error'})) {
                   3663:               $hash{'error'}='Bad data';
                   3664:               return (\%hash, $string);
                   3665:           }
                   3666:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3667:           ($key, $string)=&str2arrayref($string);
                   3668:           if($key->[0] eq 'Array reference error') {
                   3669:               $hash{'error'}='Bad data';
                   3670:               return (\%hash, $string);
                   3671:           }
                   3672:       } else {
                   3673:           $string =~ s/^(.*?)=//;
1.267     albertel 3674: 	  $key=&unescape($1);
1.265     albertel 3675:       }
                   3676:       $string =~ s/^=//;
                   3677: 
                   3678:       #value
                   3679:       my $value='';
                   3680:       if($string =~ /^__HASH_REF__/) {
                   3681:           ($value, $string)=&str2hashref($string);
                   3682:           if(defined($value->{'error'})) {
                   3683:               $hash{'error'}='Bad data';
                   3684:               return (\%hash, $string);
                   3685:           }
                   3686:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3687:           ($value, $string)=&str2arrayref($string);
                   3688:           if($value->[0] eq 'Array reference error') {
                   3689:               $hash{'error'}='Bad data';
                   3690:               return (\%hash, $string);
                   3691:           }
                   3692:       } else {
                   3693: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3694:       }
                   3695:       $string =~ s/^&//;
                   3696: 
                   3697:       $hash{$key}=$value;
1.204     albertel 3698:   }
1.265     albertel 3699: 
                   3700:   $string =~ s/^__END_HASH_REF__//;
                   3701: 
                   3702:   return (\%hash, $string);
1.204     albertel 3703: }
                   3704: 
                   3705: sub str2array {
1.265     albertel 3706:     my ($string)=@_;
                   3707:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3708:     return @$array;
                   3709: }
                   3710: 
                   3711: sub str2arrayref {
1.204     albertel 3712:   my ($string) = @_;
1.265     albertel 3713:   my @array;
                   3714: 
                   3715:   if($string !~ /^__ARRAY_REF__/) {
                   3716:       if (! ($string eq '' || !defined($string))) {
                   3717: 	  $array[0]='Array reference error';
                   3718:       }
                   3719:       return (\@array, $string);
                   3720:   }
                   3721: 
                   3722:   $string =~ s/^__ARRAY_REF__//;
                   3723: 
                   3724:   while($string !~ /^__END_ARRAY_REF__/) {
                   3725:       my $value='';
                   3726:       if($string =~ /^__HASH_REF__/) {
                   3727:           ($value, $string)=&str2hashref($string);
                   3728:           if(defined($value->{'error'})) {
                   3729:               $array[0] ='Array reference error';
                   3730:               return (\@array, $string);
                   3731:           }
                   3732:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3733:           ($value, $string)=&str2arrayref($string);
                   3734:           if($value->[0] eq 'Array reference error') {
                   3735:               $array[0] ='Array reference error';
                   3736:               return (\@array, $string);
                   3737:           }
                   3738:       } else {
                   3739: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3740:       }
                   3741:       $string =~ s/^&//;
                   3742: 
                   3743:       push(@array, $value);
1.191     harris41 3744:   }
1.265     albertel 3745: 
                   3746:   $string =~ s/^__END_ARRAY_REF__//;
                   3747: 
                   3748:   return (\@array, $string);
1.168     albertel 3749: }
                   3750: 
1.167     albertel 3751: # -------------------------------------------------------------------Temp Store
                   3752: 
1.168     albertel 3753: sub tmpreset {
                   3754:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3755:   if (!$symb) {
                   3756:     $symb=&symbread();
1.620     albertel 3757:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3758:   }
                   3759:   $symb=escape($symb);
                   3760: 
1.620     albertel 3761:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3762:   $namespace=~s/\//\_/g;
                   3763:   $namespace=~s/\W//g;
                   3764: 
1.620     albertel 3765:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3766:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3767:   if ($domain eq 'public' && $stuname eq 'public') {
                   3768:       $stuname=$ENV{'REMOTE_ADDR'};
                   3769:   }
1.168     albertel 3770:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3771:   my %hash;
                   3772:   if (tie(%hash,'GDBM_File',
                   3773: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3774: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3775:     foreach my $key (keys(%hash)) {
1.180     albertel 3776:       if ($key=~ /:$symb/) {
1.168     albertel 3777: 	delete($hash{$key});
                   3778:       }
                   3779:     }
                   3780:   }
                   3781: }
                   3782: 
1.167     albertel 3783: sub tmpstore {
1.168     albertel 3784:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3785: 
                   3786:   if (!$symb) {
                   3787:     $symb=&symbread();
1.620     albertel 3788:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3789:   }
                   3790:   $symb=escape($symb);
                   3791: 
                   3792:   if (!$namespace) {
                   3793:     # I don't think we would ever want to store this for a course.
                   3794:     # it seems this will only be used if we don't have a course.
1.620     albertel 3795:     #$namespace=$env{'request.course.id'};
1.168     albertel 3796:     #if (!$namespace) {
1.620     albertel 3797:       $namespace=$env{'request.state'};
1.168     albertel 3798:     #}
                   3799:   }
                   3800:   $namespace=~s/\//\_/g;
                   3801:   $namespace=~s/\W//g;
1.620     albertel 3802:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3803:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3804:   if ($domain eq 'public' && $stuname eq 'public') {
                   3805:       $stuname=$ENV{'REMOTE_ADDR'};
                   3806:   }
1.168     albertel 3807:   my $now=time;
                   3808:   my %hash;
                   3809:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3810:   if (tie(%hash,'GDBM_File',
                   3811: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3812: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3813:     $hash{"version:$symb"}++;
                   3814:     my $version=$hash{"version:$symb"};
                   3815:     my $allkeys=''; 
                   3816:     foreach my $key (keys(%$storehash)) {
                   3817:       $allkeys.=$key.':';
1.591     albertel 3818:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3819:     }
                   3820:     $hash{"$version:$symb:timestamp"}=$now;
                   3821:     $allkeys.='timestamp';
                   3822:     $hash{"$version:keys:$symb"}=$allkeys;
                   3823:     if (untie(%hash)) {
                   3824:       return 'ok';
                   3825:     } else {
                   3826:       return "error:$!";
                   3827:     }
                   3828:   } else {
                   3829:     return "error:$!";
                   3830:   }
                   3831: }
1.167     albertel 3832: 
1.168     albertel 3833: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3834: 
1.168     albertel 3835: sub tmprestore {
                   3836:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3837: 
1.168     albertel 3838:   if (!$symb) {
                   3839:     $symb=&symbread();
1.620     albertel 3840:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3841:   }
                   3842:   $symb=escape($symb);
                   3843: 
1.620     albertel 3844:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3845: 
1.620     albertel 3846:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3847:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3848:   if ($domain eq 'public' && $stuname eq 'public') {
                   3849:       $stuname=$ENV{'REMOTE_ADDR'};
                   3850:   }
1.168     albertel 3851:   my %returnhash;
                   3852:   $namespace=~s/\//\_/g;
                   3853:   $namespace=~s/\W//g;
                   3854:   my %hash;
                   3855:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3856:   if (tie(%hash,'GDBM_File',
                   3857: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3858: 	  &GDBM_READER(),0640)) {
1.168     albertel 3859:     my $version=$hash{"version:$symb"};
                   3860:     $returnhash{'version'}=$version;
                   3861:     my $scope;
                   3862:     for ($scope=1;$scope<=$version;$scope++) {
                   3863:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3864:       my @keys=split(/:/,$vkeys);
                   3865:       my $key;
                   3866:       $returnhash{"$scope:keys"}=$vkeys;
                   3867:       foreach $key (@keys) {
1.591     albertel 3868: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3869: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3870:       }
                   3871:     }
1.168     albertel 3872:     if (!(untie(%hash))) {
                   3873:       return "error:$!";
                   3874:     }
                   3875:   } else {
                   3876:     return "error:$!";
                   3877:   }
                   3878:   return %returnhash;
1.167     albertel 3879: }
                   3880: 
1.9       www      3881: # ----------------------------------------------------------------------- Store
                   3882: 
                   3883: sub store {
1.124     www      3884:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3885:     my $home='';
                   3886: 
1.168     albertel 3887:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3888: 
1.213     www      3889:     $symb=&symbclean($symb);
1.122     albertel 3890:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3891: 
1.620     albertel 3892:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3893:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3894: 
                   3895:     &devalidate($symb,$stuname,$domain);
1.109     www      3896: 
                   3897:     $symb=escape($symb);
1.187     www      3898:     if (!$namespace) { 
1.620     albertel 3899:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3900:           return ''; 
                   3901:        } 
                   3902:     }
1.620     albertel 3903:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3904: 
                   3905:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3906:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3907: 
1.12      www      3908:     my $namevalue='';
1.800     albertel 3909:     foreach my $key (keys(%$storehash)) {
                   3910:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3911:     }
1.12      www      3912:     $namevalue=~s/\&$//;
1.187     www      3913:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3914:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3915: }
                   3916: 
1.47      www      3917: # -------------------------------------------------------------- Critical Store
                   3918: 
                   3919: sub cstore {
1.124     www      3920:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3921:     my $home='';
                   3922: 
1.168     albertel 3923:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3924: 
1.213     www      3925:     $symb=&symbclean($symb);
1.122     albertel 3926:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3927: 
1.620     albertel 3928:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3929:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3930: 
                   3931:     &devalidate($symb,$stuname,$domain);
1.109     www      3932: 
                   3933:     $symb=escape($symb);
1.187     www      3934:     if (!$namespace) { 
1.620     albertel 3935:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3936:           return ''; 
                   3937:        } 
                   3938:     }
1.620     albertel 3939:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3940: 
                   3941:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3942:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3943: 
1.47      www      3944:     my $namevalue='';
1.800     albertel 3945:     foreach my $key (keys(%$storehash)) {
                   3946:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3947:     }
1.47      www      3948:     $namevalue=~s/\&$//;
1.187     www      3949:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3950:     return critical
                   3951:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3952: }
                   3953: 
1.9       www      3954: # --------------------------------------------------------------------- Restore
                   3955: 
                   3956: sub restore {
1.124     www      3957:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3958:     my $home='';
                   3959: 
1.168     albertel 3960:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3961: 
1.122     albertel 3962:     if (!$symb) {
                   3963:       unless ($symb=escape(&symbread())) { return ''; }
                   3964:     } else {
1.213     www      3965:       $symb=&escape(&symbclean($symb));
1.122     albertel 3966:     }
1.188     www      3967:     if (!$namespace) { 
1.620     albertel 3968:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3969:           return ''; 
                   3970:        } 
                   3971:     }
1.620     albertel 3972:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3973:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3974:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3975:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3976: 
1.12      www      3977:     my %returnhash=();
1.800     albertel 3978:     foreach my $line (split(/\&/,$answer)) {
                   3979: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3980:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3981:     }
1.75      www      3982:     my $version;
                   3983:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3984:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3985:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3986:        }
1.75      www      3987:     }
1.13      www      3988:     return %returnhash;
1.34      www      3989: }
                   3990: 
                   3991: # ---------------------------------------------------------- Course Description
                   3992: 
                   3993: sub coursedescription {
1.731     albertel 3994:     my ($courseid,$args)=@_;
1.34      www      3995:     $courseid=~s/^\///;
1.49      www      3996:     $courseid=~s/\_/\//g;
1.34      www      3997:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3998:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3999:     my $normalid=$cdomain.'_'.$cnum;
                   4000:     # need to always cache even if we get errors otherwise we keep 
                   4001:     # trying and trying and trying to get the course description.
                   4002:     my %envhash=();
                   4003:     my %returnhash=();
1.731     albertel 4004:     
                   4005:     my $expiretime=600;
                   4006:     if ($env{'request.course.id'} eq $normalid) {
                   4007: 	$expiretime=120;
                   4008:     }
                   4009: 
                   4010:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4011:     if (!$args->{'freshen_cache'}
                   4012: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4013: 	foreach my $key (keys(%env)) {
                   4014: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4015: 	    my ($setting) = $1;
                   4016: 	    $returnhash{$setting} = $env{$key};
                   4017: 	}
                   4018: 	return %returnhash;
                   4019:     }
                   4020: 
                   4021:     # get the data agin
                   4022:     if (!$args->{'one_time'}) {
                   4023: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4024:     }
1.811     albertel 4025: 
1.34      www      4026:     if ($chome ne 'no_host') {
1.302     albertel 4027:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4028:        if (!exists($returnhash{'con_lost'})) {
                   4029:            $returnhash{'home'}= $chome;
                   4030: 	   $returnhash{'domain'} = $cdomain;
                   4031: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4032:            if (!defined($returnhash{'type'})) {
                   4033:                $returnhash{'type'} = 'Course';
                   4034:            }
1.130     albertel 4035:            while (my ($name,$value) = each %returnhash) {
1.53      www      4036:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4037:            }
1.270     www      4038:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      4039:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 4040: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      4041:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4042:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4043:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4044:        }
                   4045:     }
1.731     albertel 4046:     if (!$args->{'one_time'}) {
1.949     raeburn  4047: 	&appenv(\%envhash);
1.731     albertel 4048:     }
1.302     albertel 4049:     return %returnhash;
1.461     www      4050: }
                   4051: 
1.1056.4.5  raeburn  4052: sub update_released_required {
                   4053:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4054:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4055:         $cid = $env{'request.course.id'};
                   4056:         $cdom = $env{'course.'.$cid.'.domain'};
                   4057:         $cnum = $env{'course.'.$cid.'.num'};
                   4058:         $chome = $env{'course.'.$cid.'.home'};
                   4059:     }
                   4060:     if ($needsrelease) {
                   4061:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4062:         my $needsupdate;
                   4063:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4064:             $needsupdate = 1;
                   4065:         } else {
                   4066:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4067:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4068:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4069:                 $needsupdate = 1;
                   4070:             }
                   4071:         }
                   4072:         if ($needsupdate) {
                   4073:             my %needshash = (
                   4074:                              'internal.releaserequired' => $needsrelease,
                   4075:                             );
                   4076:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4077:             if ($putresult eq 'ok') {
                   4078:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4079:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4080:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4081:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4082:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4083:                 }
                   4084:             }
                   4085:         }
                   4086:     }
                   4087:     return;
                   4088: }
                   4089: 
1.461     www      4090: # -------------------------------------------------See if a user is privileged
                   4091: 
                   4092: sub privileged {
                   4093:     my ($username,$domain)=@_;
                   4094:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   4095: 			&homeserver($username,$domain));
1.1033    raeburn  4096:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   4097:         ($rolesdump =~ /^error:/)) {
                   4098:         return 0;
                   4099:     }
1.461     www      4100:     my $now=time;
                   4101:     if ($rolesdump ne '') {
1.800     albertel 4102:         foreach my $entry (split(/&/,$rolesdump)) {
                   4103: 	    if ($entry!~/^rolesdef_/) {
                   4104: 		my ($area,$role)=split(/=/,$entry);
1.461     www      4105: 		$area=~s/\_\w\w$//;
                   4106: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   4107: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   4108: 		    my $active=1;
                   4109: 		    if ($tend) {
                   4110: 			if ($tend<$now) { $active=0; }
                   4111: 		    }
                   4112: 		    if ($tstart) {
                   4113: 			if ($tstart>$now) { $active=0; }
                   4114: 		    }
                   4115: 		    if ($active) { return 1; }
                   4116: 		}
                   4117: 	    }
                   4118: 	}
                   4119:     }
                   4120:     return 0;
1.9       www      4121: }
1.1       albertel 4122: 
1.103     harris41 4123: # -------------------------------------------------------- Get user privileges
1.11      www      4124: 
                   4125: sub rolesinit {
                   4126:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  4127:     my $now=time;
                   4128:     my %userroles = ('user.login.time' => $now);
1.1056.4.10! raeburn  4129:     my $extra = &freeze_escape({'skipcheck' => 1});
1.1056.4.3  raeburn  4130:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033    raeburn  4131:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
1.1056.4.3  raeburn  4132:         ($rolesdump =~ /^error:/)) {
1.1033    raeburn  4133:         return \%userroles;
                   4134:     }
1.11      www      4135:     my %allroles=();
1.678     raeburn  4136:     my %allgroups=();   
                   4137:     my $group_privs;
1.11      www      4138: 
                   4139:     if ($rolesdump ne '') {
1.800     albertel 4140:         foreach my $entry (split(/&/,$rolesdump)) {
                   4141: 	  if ($entry!~/^rolesdef_/) {
                   4142:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 4143: 	    $area=~s/\_\w\w$//;
1.678     raeburn  4144:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 4145: 	    if ($role=~/^cr/) { 
1.807     albertel 4146: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4147: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 4148: 		    ($tend,$tstart)=split('_',$trest);
                   4149: 		} else {
                   4150: 		    $trole=$role;
                   4151: 		}
1.678     raeburn  4152:             } elsif ($role =~ m|^gr/|) {
                   4153:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   4154:                 ($trole,$group_privs) = split(/\//,$trole);
                   4155:                 $group_privs = &unescape($group_privs);
1.587     albertel 4156: 	    } else {
                   4157: 		($trole,$tend,$tstart)=split(/_/,$role);
                   4158: 	    }
1.743     albertel 4159: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4160: 					 $username);
                   4161: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  4162:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   4163:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      4164:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 4165: 		my $spec=$trole.'.'.$area;
                   4166: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   4167: 		if ($trole =~ /^cr\//) {
1.567     raeburn  4168:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  4169:                 } elsif ($trole eq 'gr') {
                   4170:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 4171: 		} else {
1.567     raeburn  4172:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 4173: 		}
1.12      www      4174:             }
1.662     raeburn  4175:           }
1.191     harris41 4176:         }
1.743     albertel 4177:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4178:         $userroles{'user.adv'}    = $adv;
                   4179: 	$userroles{'user.author'} = $author;
1.620     albertel 4180:         $env{'user.adv'}=$adv;
1.11      www      4181:     }
1.743     albertel 4182:     return \%userroles;  
1.11      www      4183: }
                   4184: 
1.567     raeburn  4185: sub set_arearole {
                   4186:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4187: # log the associated role with the area
                   4188:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4189:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4190: }
                   4191: 
                   4192: sub custom_roleprivs {
                   4193:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4194:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4195:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4196:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4197:         my ($rdummy,$roledef)=
                   4198:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4199:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4200:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4201:             if (defined($syspriv)) {
1.1043    raeburn  4202:                 if ($trest =~ /^$match_community$/) {
                   4203:                     $syspriv =~ s/bre\&S//; 
                   4204:                 }
1.567     raeburn  4205:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4206:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4207:             }
                   4208:             if ($tdomain ne '') {
                   4209:                 if (defined($dompriv)) {
                   4210:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4211:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4212:                 }
                   4213:                 if (($trest ne '') && (defined($coursepriv))) {
                   4214:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4215:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4216:                 }
                   4217:             }
                   4218:         }
                   4219:     }
                   4220: }
                   4221: 
1.678     raeburn  4222: sub group_roleprivs {
                   4223:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4224:     my $access = 1;
                   4225:     my $now = time;
                   4226:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4227:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4228:     if ($access) {
1.811     albertel 4229:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4230:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4231:     }
                   4232: }
1.567     raeburn  4233: 
                   4234: sub standard_roleprivs {
                   4235:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4236:     if (defined($pr{$trole.':s'})) {
                   4237:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4238:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4239:     }
                   4240:     if ($tdomain ne '') {
                   4241:         if (defined($pr{$trole.':d'})) {
                   4242:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4243:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4244:         }
                   4245:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4246:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4247:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4248:         }
                   4249:     }
                   4250: }
                   4251: 
                   4252: sub set_userprivs {
1.1056.4.2  raeburn  4253:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4254:     my $author=0;
                   4255:     my $adv=0;
1.678     raeburn  4256:     my %grouproles = ();
                   4257:     if (keys(%{$allgroups}) > 0) {
1.1056.4.2  raeburn  4258:         my @groupkeys;
1.1000    raeburn  4259:         foreach my $role (keys(%{$allroles})) {
1.1056.4.2  raeburn  4260:             push(@groupkeys,$role);
                   4261:         }
                   4262:         if (ref($groups_roles) eq 'HASH') {
                   4263:             foreach my $key (keys(%{$groups_roles})) {
                   4264:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4265:                     push(@groupkeys,$key);
                   4266:                 }
                   4267:             }
                   4268:         }
                   4269:         if (@groupkeys > 0) {
                   4270:             foreach my $role (@groupkeys) {
                   4271:                 my ($trole,$area,$sec,$extendedarea);
                   4272:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4273:                     $trole = $1;
                   4274:                     $area = $2;
                   4275:                     $sec = $3;
                   4276:                     $extendedarea = $area.$sec;
                   4277:                     if (exists($$allgroups{$area})) {
                   4278:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4279:                             my $spec = $trole.'.'.$extendedarea;
                   4280:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4281:                                                 $$allgroups{$area}{$group};
1.1056.4.2  raeburn  4282:                         }
1.678     raeburn  4283:                     }
                   4284:                 }
                   4285:             }
                   4286:         }
                   4287:     }
1.800     albertel 4288:     foreach my $group (keys(%grouproles)) {
                   4289:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4290:     }
1.800     albertel 4291:     foreach my $role (keys(%{$allroles})) {
                   4292:         my %thesepriv;
1.941     raeburn  4293:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4294:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4295:             if ($item ne '') {
                   4296:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4297:                 if ($restrictions eq '') {
                   4298:                     $thesepriv{$privilege}='F';
                   4299:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4300:                     $thesepriv{$privilege}.=$restrictions;
                   4301:                 }
                   4302:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4303:             }
                   4304:         }
                   4305:         my $thesestr='';
1.800     albertel 4306:         foreach my $priv (keys(%thesepriv)) {
                   4307: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4308: 	}
                   4309:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4310:     }
                   4311:     return ($author,$adv);
                   4312: }
                   4313: 
1.994     raeburn  4314: sub role_status {
1.1002    raeburn  4315:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4316:     my @pwhere = ();
                   4317:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4318:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4319:         unless (!defined($$role) || $$role eq '') {
                   4320:             $$where=join('.',@pwhere);
                   4321:             $$trolecode=$$role.'.'.$$where;
                   4322:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4323:             $$tstatus='is';
                   4324:             if ($$tstart && $$tstart>$then) {
                   4325:                 $$tstatus='future';
1.1034    raeburn  4326:                 if ($$tstart<$now) {
                   4327:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4328:                         if (($$where ne '') && ($$role ne '')) {
1.1056.4.2  raeburn  4329:                             my (%allroles,%allgroups,$group_privs,
                   4330:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4331:                             my %userroles = (
                   4332:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4333:                             );
1.1056.4.2  raeburn  4334:                             @rolecodes = ('cm');
1.1002    raeburn  4335:                             my $spec=$$role.'.'.$$where;
                   4336:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4337:                             if ($$role =~ /^cr\//) {
                   4338:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1056.4.2  raeburn  4339:                                 push(@rolecodes,'cr');
1.1002    raeburn  4340:                             } elsif ($$role eq 'gr') {
1.1056.4.2  raeburn  4341:                                 push(@rolecodes,$$role);
1.1002    raeburn  4342:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4343:                                                     $env{'user.name'});
1.1056.4.2  raeburn  4344:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4345:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4346:                                 $group_privs = &unescape($group_privs);
                   4347:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1056.4.2  raeburn  4348:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
                   4349:                                 if (keys(%course_roles) > 0) {
                   4350:                                     my ($tnum) = ($trest =~ /^($match_courseid)/);
                   4351:                                     if ($tdomain ne '' && $tnum ne '') {
                   4352:                                         foreach my $key (keys(%course_roles)) {
                   4353:                                             if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
                   4354:                                                 my $crsrole = $1;
                   4355:                                                 my $crssec = $2;
                   4356:                                                 if ($crsrole =~ /^cr/) {
                   4357:                                                     unless (grep(/^cr$/,@rolecodes)) {
                   4358:                                                         push(@rolecodes,'cr');
                   4359:                                                     }
                   4360:                                                 } else {
                   4361:                                                     unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
                   4362:                                                         push(@rolecodes,$crsrole);
                   4363:                                                     }
                   4364:                                                 }
                   4365:                                                 my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
                   4366:                                                 if ($crssec ne '') {
                   4367:                                                     $rolekey .= '/'.$crssec;
                   4368:                                                 }
                   4369:                                                 $rolekey .= './';
                   4370:                                                 $groups_roles{$rolekey} = \@rolecodes;
                   4371:                                             }
                   4372:                                         }
                   4373:                                     }
                   4374:                                 }
1.1002    raeburn  4375:                             } else {
1.1056.4.2  raeburn  4376:                                 push(@rolecodes,$$role);
1.1002    raeburn  4377:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4378:                             }
1.1056.4.2  raeburn  4379:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4380:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4381:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4382:                         }
                   4383:                     }
1.1034    raeburn  4384:                     $$tstatus = 'is';
1.1002    raeburn  4385:                 }
1.994     raeburn  4386:             }
                   4387:             if ($$tend) {
                   4388:                 if ($$tend<$then) {
                   4389:                     $$tstatus='expired';
                   4390:                 } elsif ($$tend<$now) {
                   4391:                     $$tstatus='will_not';
                   4392:                 }
                   4393:             }
                   4394:         }
                   4395:     }
                   4396: }
                   4397: 
                   4398: sub check_adhoc_privs {
1.1002    raeburn  4399:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
1.994     raeburn  4400:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4401:     if ($env{$cckey}) {
                   4402:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002    raeburn  4403:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4404:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
                   4405:             &set_adhoc_privileges($cdom,$cnum,$checkrole);
                   4406:         }
                   4407:     } else {
                   4408:         &set_adhoc_privileges($cdom,$cnum,$checkrole);
                   4409:     }
                   4410: }
                   4411: 
                   4412: sub set_adhoc_privileges {
                   4413: # role can be cc or ca
                   4414:     my ($dcdom,$pickedcourse,$role) = @_;
                   4415:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4416:     my $spec = $role.'.'.$area;
                   4417:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4418:                                   $env{'user.name'});
                   4419:     my %ccrole = ();
                   4420:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4421:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4422:     &appenv(\%userroles,[$role,'cm']);
                   4423:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4424:     &appenv( {'request.role'        => $spec,
                   4425:               'request.role.domain' => $dcdom,
                   4426:               'request.course.sec'  => ''
                   4427:              }
                   4428:            );
                   4429:     my $tadv=0;
                   4430:     if (&allowed('adv') eq 'F') { $tadv=1; }
                   4431:     &appenv({'request.role.adv'    => $tadv});
                   4432: }
                   4433: 
1.12      www      4434: # --------------------------------------------------------------- get interface
                   4435: 
                   4436: sub get {
1.131     albertel 4437:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4438:    my $items='';
1.800     albertel 4439:    foreach my $item (@$storearr) {
                   4440:        $items.=&escape($item).'&';
1.191     harris41 4441:    }
1.12      www      4442:    $items=~s/\&$//;
1.620     albertel 4443:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4444:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4445:    my $uhome=&homeserver($uname,$udomain);
                   4446: 
1.133     albertel 4447:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4448:    my @pairs=split(/\&/,$rep);
1.273     albertel 4449:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4450:      return @pairs;
                   4451:    }
1.15      www      4452:    my %returnhash=();
1.42      www      4453:    my $i=0;
1.800     albertel 4454:    foreach my $item (@$storearr) {
                   4455:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4456:       $i++;
1.191     harris41 4457:    }
1.15      www      4458:    return %returnhash;
1.27      www      4459: }
                   4460: 
                   4461: # --------------------------------------------------------------- del interface
                   4462: 
                   4463: sub del {
1.133     albertel 4464:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4465:    my $items='';
1.800     albertel 4466:    foreach my $item (@$storearr) {
                   4467:        $items.=&escape($item).'&';
1.191     harris41 4468:    }
1.984     neumanie 4469: 
1.27      www      4470:    $items=~s/\&$//;
1.620     albertel 4471:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4472:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4473:    my $uhome=&homeserver($uname,$udomain);
                   4474:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4475: }
                   4476: 
                   4477: # -------------------------------------------------------------- dump interface
                   4478: 
                   4479: sub dump {
1.1056.4.10! raeburn  4480:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755     albertel 4481:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4482:     if (!$uname) { $uname=$env{'user.name'}; }
                   4483:     my $uhome=&homeserver($uname,$udomain);
                   4484:     if ($regexp) {
                   4485: 	$regexp=&escape($regexp);
                   4486:     } else {
                   4487: 	$regexp='.';
                   4488:     }
1.1056.4.10! raeburn  4489:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755     albertel 4490:     my @pairs=split(/\&/,$rep);
                   4491:     my %returnhash=();
                   4492:     foreach my $item (@pairs) {
                   4493: 	my ($key,$value)=split(/=/,$item,2);
                   4494: 	$key = &unescape($key);
                   4495: 	next if ($key =~ /^error: 2 /);
                   4496: 	$returnhash{$key}=&thaw_unescape($value);
                   4497:     }
                   4498:     return %returnhash;
1.407     www      4499: }
                   4500: 
1.717     albertel 4501: # --------------------------------------------------------- dumpstore interface
                   4502: 
                   4503: sub dumpstore {
                   4504:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4505:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4506:    if (!$uname) { $uname=$env{'user.name'}; }
                   4507:    my $uhome=&homeserver($uname,$udomain);
                   4508:    if ($regexp) {
                   4509:        $regexp=&escape($regexp);
                   4510:    } else {
                   4511:        $regexp='.';
                   4512:    }
                   4513:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4514:    my @pairs=split(/\&/,$rep);
                   4515:    my %returnhash=();
                   4516:    foreach my $item (@pairs) {
                   4517:        my ($key,$value)=split(/=/,$item,2);
                   4518:        next if ($key =~ /^error: 2 /);
                   4519:        $returnhash{$key}=&thaw_unescape($value);
                   4520:    }
                   4521:    return %returnhash;
1.717     albertel 4522: }
                   4523: 
1.407     www      4524: # -------------------------------------------------------------- keys interface
                   4525: 
                   4526: sub getkeys {
                   4527:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4528:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4529:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4530:    my $uhome=&homeserver($uname,$udomain);
                   4531:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4532:    my @keyarray=();
1.800     albertel 4533:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4534:       next if ($key =~ /^error: 2 /);
1.800     albertel 4535:       push(@keyarray,&unescape($key));
1.407     www      4536:    }
                   4537:    return @keyarray;
1.318     matthew  4538: }
                   4539: 
1.319     matthew  4540: # --------------------------------------------------------------- currentdump
                   4541: sub currentdump {
1.328     matthew  4542:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4543:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4544:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4545:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4546:    my $uhome = &homeserver($sname,$sdom);
                   4547:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4548:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4549:    #
1.318     matthew  4550:    my %returnhash=();
1.319     matthew  4551:    #
                   4552:    if ($rep eq "unknown_cmd") { 
                   4553:        # an old lond will not know currentdump
                   4554:        # Do a dump and make it look like a currentdump
1.822     albertel 4555:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4556:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4557:        my %hash = @tmp;
                   4558:        @tmp=();
1.424     matthew  4559:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4560:    } else {
                   4561:        my @pairs=split(/\&/,$rep);
1.800     albertel 4562:        foreach my $pair (@pairs) {
                   4563:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4564:            my ($symb,$param) = split(/:/,$key);
                   4565:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4566:                                                         &thaw_unescape($value);
1.319     matthew  4567:        }
1.191     harris41 4568:    }
1.12      www      4569:    return %returnhash;
1.424     matthew  4570: }
                   4571: 
                   4572: sub convert_dump_to_currentdump{
                   4573:     my %hash = %{shift()};
                   4574:     my %returnhash;
                   4575:     # Code ripped from lond, essentially.  The only difference
                   4576:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4577:     # we might run in to problems with parameter names =~ /^v\./
                   4578:     while (my ($key,$value) = each(%hash)) {
                   4579:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4580: 	$symb  = &unescape($symb);
                   4581: 	$param = &unescape($param);
1.424     matthew  4582:         next if ($v eq 'version' || $symb eq 'keys');
                   4583:         next if (exists($returnhash{$symb}) &&
                   4584:                  exists($returnhash{$symb}->{$param}) &&
                   4585:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4586:         $returnhash{$symb}->{$param}=$value;
                   4587:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4588:     }
                   4589:     #
                   4590:     # Remove all of the keys in the hashes which keep track of
                   4591:     # the version of the parameter.
                   4592:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4593:         # use a foreach because we are going to delete from the hash.
                   4594:         foreach my $key (keys(%$param_hash)) {
                   4595:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4596:         }
                   4597:     }
                   4598:     return \%returnhash;
1.12      www      4599: }
                   4600: 
1.627     albertel 4601: # ------------------------------------------------------ critical inc interface
                   4602: 
                   4603: sub cinc {
                   4604:     return &inc(@_,'critical');
                   4605: }
                   4606: 
1.449     matthew  4607: # --------------------------------------------------------------- inc interface
                   4608: 
                   4609: sub inc {
1.627     albertel 4610:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4611:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4612:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4613:     my $uhome=&homeserver($uname,$udomain);
                   4614:     my $items='';
                   4615:     if (! ref($store)) {
                   4616:         # got a single value, so use that instead
                   4617:         $items = &escape($store).'=&';
                   4618:     } elsif (ref($store) eq 'SCALAR') {
                   4619:         $items = &escape($$store).'=&';        
                   4620:     } elsif (ref($store) eq 'ARRAY') {
                   4621:         $items = join('=&',map {&escape($_);} @{$store});
                   4622:     } elsif (ref($store) eq 'HASH') {
                   4623:         while (my($key,$value) = each(%{$store})) {
                   4624:             $items.= &escape($key).'='.&escape($value).'&';
                   4625:         }
                   4626:     }
                   4627:     $items=~s/\&$//;
1.627     albertel 4628:     if ($critical) {
                   4629: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4630:     } else {
                   4631: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4632:     }
1.449     matthew  4633: }
                   4634: 
1.12      www      4635: # --------------------------------------------------------------- put interface
                   4636: 
                   4637: sub put {
1.134     albertel 4638:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4639:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4640:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4641:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4642:    my $items='';
1.800     albertel 4643:    foreach my $item (keys(%$storehash)) {
                   4644:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4645:    }
1.12      www      4646:    $items=~s/\&$//;
1.134     albertel 4647:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4648: }
                   4649: 
1.631     albertel 4650: # ------------------------------------------------------------ newput interface
                   4651: 
                   4652: sub newput {
                   4653:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4654:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4655:    if (!$uname) { $uname=$env{'user.name'}; }
                   4656:    my $uhome=&homeserver($uname,$udomain);
                   4657:    my $items='';
                   4658:    foreach my $key (keys(%$storehash)) {
                   4659:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4660:    }
                   4661:    $items=~s/\&$//;
                   4662:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4663: }
                   4664: 
                   4665: # ---------------------------------------------------------  putstore interface
                   4666: 
1.524     raeburn  4667: sub putstore {
1.715     albertel 4668:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4669:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4670:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4671:    my $uhome=&homeserver($uname,$udomain);
                   4672:    my $items='';
1.715     albertel 4673:    foreach my $key (keys(%$storehash)) {
                   4674:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4675:    }
1.715     albertel 4676:    $items=~s/\&$//;
1.716     albertel 4677:    my $esc_symb=&escape($symb);
                   4678:    my $esc_v=&escape($version);
1.715     albertel 4679:    my $reply =
1.716     albertel 4680:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4681: 	      $uhome);
                   4682:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4683:        # gfall back to way things use to be done
1.715     albertel 4684:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4685: 			    $uname);
1.524     raeburn  4686:    }
1.715     albertel 4687:    return $reply;
                   4688: }
                   4689: 
                   4690: sub old_putstore {
1.716     albertel 4691:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4692:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4693:     if (!$uname) { $uname=$env{'user.name'}; }
                   4694:     my $uhome=&homeserver($uname,$udomain);
                   4695:     my %newstorehash;
1.800     albertel 4696:     foreach my $item (keys(%$storehash)) {
                   4697: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4698: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4699:     }
                   4700:     my $items='';
                   4701:     my %allitems = ();
1.800     albertel 4702:     foreach my $item (keys(%newstorehash)) {
                   4703: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4704: 	    my $key = $1.':keys:'.$2;
                   4705: 	    $allitems{$key} .= $3.':';
                   4706: 	}
1.800     albertel 4707: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4708:     }
1.800     albertel 4709:     foreach my $item (keys(%allitems)) {
                   4710: 	$allitems{$item} =~ s/\:$//;
                   4711: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4712:     }
                   4713:     $items=~s/\&$//;
                   4714:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4715: }
                   4716: 
1.47      www      4717: # ------------------------------------------------------ critical put interface
                   4718: 
                   4719: sub cput {
1.134     albertel 4720:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4721:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4722:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4723:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4724:    my $items='';
1.800     albertel 4725:    foreach my $item (keys(%$storehash)) {
                   4726:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4727:    }
1.47      www      4728:    $items=~s/\&$//;
1.134     albertel 4729:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4730: }
                   4731: 
                   4732: # -------------------------------------------------------------- eget interface
                   4733: 
                   4734: sub eget {
1.133     albertel 4735:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4736:    my $items='';
1.800     albertel 4737:    foreach my $item (@$storearr) {
                   4738:        $items.=&escape($item).'&';
1.191     harris41 4739:    }
1.12      www      4740:    $items=~s/\&$//;
1.620     albertel 4741:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4742:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4743:    my $uhome=&homeserver($uname,$udomain);
                   4744:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4745:    my @pairs=split(/\&/,$rep);
                   4746:    my %returnhash=();
1.42      www      4747:    my $i=0;
1.800     albertel 4748:    foreach my $item (@$storearr) {
                   4749:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4750:       $i++;
1.191     harris41 4751:    }
1.12      www      4752:    return %returnhash;
                   4753: }
                   4754: 
1.667     albertel 4755: # ------------------------------------------------------------ tmpput interface
                   4756: sub tmpput {
1.802     raeburn  4757:     my ($storehash,$server,$context)=@_;
1.667     albertel 4758:     my $items='';
1.800     albertel 4759:     foreach my $item (keys(%$storehash)) {
                   4760: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4761:     }
                   4762:     $items=~s/\&$//;
1.802     raeburn  4763:     if (defined($context)) {
                   4764:         $items .= ':'.&escape($context);
                   4765:     }
1.667     albertel 4766:     return &reply("tmpput:$items",$server);
                   4767: }
                   4768: 
                   4769: # ------------------------------------------------------------ tmpget interface
                   4770: sub tmpget {
1.688     albertel 4771:     my ($token,$server)=@_;
                   4772:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4773:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4774:     my %returnhash;
                   4775:     foreach my $item (split(/\&/,$rep)) {
                   4776: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4777:         next if ($key =~ /^error: 2 /);
1.667     albertel 4778: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4779:     }
                   4780:     return %returnhash;
                   4781: }
                   4782: 
1.688     albertel 4783: # ------------------------------------------------------------ tmpget interface
                   4784: sub tmpdel {
                   4785:     my ($token,$server)=@_;
                   4786:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4787:     return &reply("tmpdel:$token",$server);
                   4788: }
                   4789: 
1.765     albertel 4790: # -------------------------------------------------- portfolio access checking
                   4791: 
                   4792: sub portfolio_access {
1.766     albertel 4793:     my ($requrl) = @_;
1.765     albertel 4794:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4795:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4796:     if ($result) {
                   4797:         my %setters;
                   4798:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4799:             my ($startblock,$endblock) =
                   4800:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4801:             if ($startblock && $endblock) {
                   4802:                 return 'B';
                   4803:             }
                   4804:         } else {
                   4805:             my ($startblock,$endblock) =
                   4806:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4807:             if ($startblock && $endblock) {
                   4808:                 return 'B';
                   4809:             }
                   4810:         }
                   4811:     }
1.765     albertel 4812:     if ($result eq 'ok') {
1.766     albertel 4813:        return 'F';
1.765     albertel 4814:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4815:        return 'A';
1.765     albertel 4816:     }
1.766     albertel 4817:     return '';
1.765     albertel 4818: }
                   4819: 
                   4820: sub get_portfolio_access {
1.767     albertel 4821:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4822: 
                   4823:     if (!ref($access_hash)) {
                   4824: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4825: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4826: 						   $file_name);
                   4827: 	$access_hash = $access_controls{$file_name};
                   4828:     }
                   4829: 
1.765     albertel 4830:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4831:     my $now = time;
                   4832:     if (ref($access_hash) eq 'HASH') {
                   4833:         foreach my $key (keys(%{$access_hash})) {
                   4834:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4835:             if ($start > $now) {
                   4836:                 next;
                   4837:             }
                   4838:             if ($end && $end<$now) {
                   4839:                 next;
                   4840:             }
                   4841:             if ($scope eq 'public') {
                   4842:                 $public = $key;
                   4843:                 last;
                   4844:             } elsif ($scope eq 'guest') {
                   4845:                 $guest = $key;
                   4846:             } elsif ($scope eq 'domains') {
                   4847:                 push(@domains,$key);
                   4848:             } elsif ($scope eq 'users') {
                   4849:                 push(@users,$key);
                   4850:             } elsif ($scope eq 'course') {
                   4851:                 push(@courses,$key);
                   4852:             } elsif ($scope eq 'group') {
                   4853:                 push(@groups,$key);
                   4854:             }
                   4855:         }
                   4856:         if ($public) {
                   4857:             return 'ok';
                   4858:         }
                   4859:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4860:             if ($guest) {
                   4861:                 return $guest;
                   4862:             }
                   4863:         } else {
                   4864:             if (@domains > 0) {
                   4865:                 foreach my $domkey (@domains) {
                   4866:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4867:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4868:                             return 'ok';
                   4869:                         }
                   4870:                     }
                   4871:                 }
                   4872:             }
                   4873:             if (@users > 0) {
                   4874:                 foreach my $userkey (@users) {
1.865     raeburn  4875:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4876:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4877:                             if (ref($item) eq 'HASH') {
                   4878:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4879:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4880:                                     return 'ok';
                   4881:                                 }
                   4882:                             }
                   4883:                         }
                   4884:                     } 
1.765     albertel 4885:                 }
                   4886:             }
                   4887:             my %roleshash;
                   4888:             my @courses_and_groups = @courses;
                   4889:             push(@courses_and_groups,@groups); 
                   4890:             if (@courses_and_groups > 0) {
                   4891:                 my (%allgroups,%allroles); 
                   4892:                 my ($start,$end,$role,$sec,$group);
                   4893:                 foreach my $envkey (%env) {
1.1056.4.1  raeburn  4894:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4895:                         my $cid = $2.'_'.$3; 
                   4896:                         if ($1 eq 'gr') {
                   4897:                             $group = $4;
                   4898:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4899:                         } else {
                   4900:                             if ($4 eq '') {
                   4901:                                 $sec = 'none';
                   4902:                             } else {
                   4903:                                 $sec = $4;
                   4904:                             }
                   4905:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4906:                         }
1.811     albertel 4907:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4908:                         my $cid = $2.'_'.$3;
                   4909:                         if ($4 eq '') {
                   4910:                             $sec = 'none';
                   4911:                         } else {
                   4912:                             $sec = $4;
                   4913:                         }
                   4914:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4915:                     }
                   4916:                 }
                   4917:                 if (keys(%allroles) == 0) {
                   4918:                     return;
                   4919:                 }
                   4920:                 foreach my $key (@courses_and_groups) {
                   4921:                     my %content = %{$$access_hash{$key}};
                   4922:                     my $cnum = $content{'number'};
                   4923:                     my $cdom = $content{'domain'};
                   4924:                     my $cid = $cdom.'_'.$cnum;
                   4925:                     if (!exists($allroles{$cid})) {
                   4926:                         next;
                   4927:                     }    
                   4928:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4929:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4930:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4931:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4932:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4933:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4934:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4935:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4936:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4937:                                         if (grep/^all$/,@sections) {
                   4938:                                             return 'ok';
                   4939:                                         } else {
                   4940:                                             if (grep/^$sec$/,@sections) {
                   4941:                                                 return 'ok';
                   4942:                                             }
                   4943:                                         }
                   4944:                                     }
                   4945:                                 }
                   4946:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4947:                                     if (grep/^none$/,@groups) {
                   4948:                                         return 'ok';
                   4949:                                     }
                   4950:                                 } else {
                   4951:                                     if (grep/^all$/,@groups) {
                   4952:                                         return 'ok';
                   4953:                                     } 
                   4954:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4955:                                         if (grep/^$group$/,@groups) {
                   4956:                                             return 'ok';
                   4957:                                         }
                   4958:                                     }
                   4959:                                 } 
                   4960:                             }
                   4961:                         }
                   4962:                     }
                   4963:                 }
                   4964:             }
                   4965:             if ($guest) {
                   4966:                 return $guest;
                   4967:             }
                   4968:         }
                   4969:     }
                   4970:     return;
                   4971: }
                   4972: 
                   4973: sub course_group_datechecker {
                   4974:     my ($dates,$now,$status) = @_;
                   4975:     my ($start,$end) = split(/\./,$dates);
                   4976:     if (!$start && !$end) {
                   4977:         return 'ok';
                   4978:     }
                   4979:     if (grep/^active$/,@{$status}) {
                   4980:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4981:             return 'ok';
                   4982:         }
                   4983:     }
                   4984:     if (grep/^previous$/,@{$status}) {
                   4985:         if ($end > $now ) {
                   4986:             return 'ok';
                   4987:         }
                   4988:     }
                   4989:     if (grep/^future$/,@{$status}) {
                   4990:         if ($start > $now) {
                   4991:             return 'ok';
                   4992:         }
                   4993:     }
                   4994:     return; 
                   4995: }
                   4996: 
                   4997: sub parse_portfolio_url {
                   4998:     my ($url) = @_;
                   4999: 
                   5000:     my ($type,$udom,$unum,$group,$file_name);
                   5001:     
1.823     albertel 5002:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5003: 	$type = 1;
                   5004:         $udom = $1;
                   5005:         $unum = $2;
                   5006:         $file_name = $3;
1.823     albertel 5007:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5008: 	$type = 2;
                   5009:         $udom = $1;
                   5010:         $unum = $2;
                   5011:         $group = $3;
                   5012:         $file_name = $3.'/'.$4;
                   5013:     }
                   5014:     if (wantarray) {
                   5015: 	return ($type,$udom,$unum,$file_name,$group);
                   5016:     }
                   5017:     return $type;
                   5018: }
                   5019: 
                   5020: sub is_portfolio_url {
                   5021:     my ($url) = @_;
                   5022:     return scalar(&parse_portfolio_url($url));
                   5023: }
                   5024: 
1.798     raeburn  5025: sub is_portfolio_file {
                   5026:     my ($file) = @_;
1.820     raeburn  5027:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5028:         return 1;
                   5029:     }
                   5030:     return;
                   5031: }
                   5032: 
1.976     raeburn  5033: sub usertools_access {
1.1056.4.9  raeburn  5034:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref) = @_;
1.985     raeburn  5035:     my ($access,%tools);
                   5036:     if ($context eq '') {
                   5037:         $context = 'tools';
                   5038:     }
                   5039:     if ($context eq 'requestcourses') {
                   5040:         %tools = (
                   5041:                       official   => 1,
                   5042:                       unofficial => 1,
1.1006    raeburn  5043:                       community  => 1,
1.985     raeburn  5044:                  );
                   5045:     } else {
                   5046:         %tools = (
                   5047:                       aboutme   => 1,
                   5048:                       blog      => 1,
                   5049:                       portfolio => 1,
                   5050:                  );
                   5051:     }
1.976     raeburn  5052:     return if (!defined($tools{$tool}));
                   5053: 
                   5054:     if ((!defined($udom)) || (!defined($uname))) {
                   5055:         $udom = $env{'user.domain'};
                   5056:         $uname = $env{'user.name'};
                   5057:     }
                   5058: 
1.978     raeburn  5059:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5060:         if ($action ne 'reload') {
1.985     raeburn  5061:             if ($context eq 'requestcourses') {
                   5062:                 return $env{'environment.canrequest.'.$tool};
                   5063:             } else {
                   5064:                 return $env{'environment.availabletools.'.$tool};
                   5065:             }
                   5066:         }
1.976     raeburn  5067:     }
                   5068: 
                   5069:     my ($toolstatus,$inststatus);
                   5070: 
1.985     raeburn  5071:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5072:          ($action ne 'reload')) {
                   5073:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5074:         $inststatus = $env{'environment.inststatus'};
                   5075:     } else {
1.1056.4.9  raeburn  5076:         if (ref($userenvref) eq 'HASH') {
                   5077:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   5078:             $inststatus = $userenvref->{'inststatus'};
                   5079:         } else {
                   5080:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   5081:             $toolstatus = $userenv{$context.'.'.$tool};
                   5082:             $inststatus = $userenv{'inststatus'};
                   5083:         }
1.976     raeburn  5084:     }
                   5085: 
                   5086:     if ($toolstatus ne '') {
                   5087:         if ($toolstatus) {
                   5088:             $access = 1;
                   5089:         } else {
                   5090:             $access = 0;
                   5091:         }
                   5092:         return $access;
                   5093:     }
                   5094: 
1.1056.4.9  raeburn  5095:     my ($is_adv,%domdef);
                   5096:     if (ref($is_advref) eq 'HASH') {
                   5097:         $is_adv = $is_advref->{'is_adv'};
                   5098:     } else {
                   5099:         $is_adv = &is_advanced_user($udom,$uname);
                   5100:     }
                   5101:     if (ref($domdefref) eq 'HASH') {
                   5102:         %domdef = %{$domdefref};
                   5103:     } else {
                   5104:         %domdef = &get_domain_defaults($udom);
                   5105:     }
1.976     raeburn  5106:     if (ref($domdef{$tool}) eq 'HASH') {
                   5107:         if ($is_adv) {
                   5108:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5109:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5110:                     $access = 1;
                   5111:                 } else {
                   5112:                     $access = 0;
                   5113:                 }
                   5114:                 return $access;
                   5115:             }
                   5116:         }
                   5117:         if ($inststatus ne '') {
                   5118:             my ($hasaccess,$hasnoaccess);
                   5119:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5120:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5121:                     if ($domdef{$tool}{$affiliation}) {
                   5122:                         $hasaccess = 1;
                   5123:                     } else {
                   5124:                         $hasnoaccess = 1;
                   5125:                     }
                   5126:                 }
                   5127:             }
                   5128:             if ($hasaccess || $hasnoaccess) {
                   5129:                 if ($hasaccess) {
                   5130:                     $access = 1;
                   5131:                 } elsif ($hasnoaccess) {
                   5132:                     $access = 0; 
                   5133:                 }
                   5134:                 return $access;
                   5135:             }
                   5136:         } else {
                   5137:             if ($domdef{$tool}{'default'} ne '') {
                   5138:                 if ($domdef{$tool}{'default'}) {
                   5139:                     $access = 1;
                   5140:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5141:                     $access = 0;
                   5142:                 }
                   5143:                 return $access;
                   5144:             }
                   5145:         }
                   5146:     } else {
1.985     raeburn  5147:         if ($context eq 'tools') {
                   5148:             $access = 1;
                   5149:         } else {
                   5150:             $access = 0;
                   5151:         }
1.976     raeburn  5152:         return $access;
                   5153:     }
                   5154: }
                   5155: 
1.1050    raeburn  5156: sub is_course_owner {
                   5157:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5158:     if (($udom eq '') || ($uname eq '')) {
                   5159:         $udom = $env{'user.domain'};
                   5160:         $uname = $env{'user.name'};
                   5161:     }
                   5162:     unless (($udom eq '') || ($uname eq '')) {
                   5163:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5164:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5165:                 return 1;
                   5166:             } else {
                   5167:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5168:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5169:                     return 1;
                   5170:                 }
                   5171:             }
                   5172:         }
                   5173:     }
                   5174:     return;
                   5175: }
                   5176: 
1.976     raeburn  5177: sub is_advanced_user {
                   5178:     my ($udom,$uname) = @_;
1.1056.4.10! raeburn  5179:     if ($udom ne '' && $uname ne '') {
        !          5180:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
        !          5181:             return $env{'user.adv'};
        !          5182:         }
        !          5183:     }
1.976     raeburn  5184:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5185:     my %allroles;
                   5186:     my $is_adv;
                   5187:     foreach my $role (keys(%roleshash)) {
                   5188:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5189:         my $area = '/'.$tdomain.'/'.$trest;
                   5190:         if ($sec ne '') {
                   5191:             $area .= '/'.$sec;
                   5192:         }
                   5193:         if (($area ne '') && ($trole ne '')) {
                   5194:             my $spec=$trole.'.'.$area;
                   5195:             if ($trole =~ /^cr\//) {
                   5196:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5197:             } elsif ($trole ne 'gr') {
                   5198:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5199:             }
                   5200:         }
                   5201:     }
                   5202:     foreach my $role (keys(%allroles)) {
                   5203:         last if ($is_adv);
                   5204:         foreach my $item (split(/:/,$allroles{$role})) {
                   5205:             if ($item ne '') {
                   5206:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5207:                 if ($privilege eq 'adv') {
                   5208:                     $is_adv = 1;
                   5209:                     last;
                   5210:                 }
                   5211:             }
                   5212:         }
                   5213:     }
                   5214:     return $is_adv;
                   5215: }
1.798     raeburn  5216: 
1.1035    raeburn  5217: sub check_can_request {
1.1036    raeburn  5218:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5219:     my $canreq = 0;
                   5220:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5221:     my @options = ('approval','validate','autolimit');
                   5222:     my $optregex = join('|',@options);
                   5223:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5224:         foreach my $type (@{$types}) {
                   5225:             if (&usertools_access($env{'user.name'},
                   5226:                                   $env{'user.domain'},
                   5227:                                   $type,undef,'requestcourses')) {
                   5228:                 $canreq ++;
1.1036    raeburn  5229:                 if (ref($request_domains) eq 'HASH') {
                   5230:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5231:                 }
1.1035    raeburn  5232:                 if ($dom eq $env{'user.domain'}) {
                   5233:                     $can_request->{$type} = 1;
                   5234:                 }
                   5235:             }
                   5236:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5237:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5238:                 if (@curr > 0) {
1.1036    raeburn  5239:                     foreach my $item (@curr) {
                   5240:                         if (ref($request_domains) eq 'HASH') {
                   5241:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5242:                             if ($otherdom ne '') {
                   5243:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5244:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5245:                                         push(@{$request_domains->{$type}},$otherdom);
                   5246:                                     }
                   5247:                                 } else {
                   5248:                                     push(@{$request_domains->{$type}},$otherdom);
                   5249:                                 }
                   5250:                             }
                   5251:                         }
                   5252:                     }
                   5253:                     unless($dom eq $env{'user.domain'}) {
                   5254:                         $canreq ++;
1.1035    raeburn  5255:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5256:                             $can_request->{$type} = 1;
                   5257:                         }
                   5258:                     }
                   5259:                 }
                   5260:             }
                   5261:         }
                   5262:     }
                   5263:     return $canreq;
                   5264: }
                   5265: 
1.341     www      5266: # ---------------------------------------------- Custom access rule evaluation
                   5267: 
                   5268: sub customaccess {
                   5269:     my ($priv,$uri)=@_;
1.807     albertel 5270:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5271:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5272:     $udom = &LONCAPA::clean_domain($udom);
                   5273:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5274:     my $access=0;
1.800     albertel 5275:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5276: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5277: 	if ($type eq 'user') {
                   5278: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5279: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5280: 		if ($tdom) {
                   5281: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5282: 		}
1.896     albertel 5283: 		if ($tuname) {
                   5284: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5285: 		}
                   5286: 		$access=($effect eq 'allow');
                   5287: 		last;
                   5288: 	    }
                   5289: 	} else {
                   5290: 	    if ($role) {
                   5291: 		if ($role ne $urole) { next; }
                   5292: 	    }
                   5293: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5294: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5295: 		if ($tdom) {
                   5296: 		    if ($tdom ne $udom) { next; }
                   5297: 		}
                   5298: 		if ($tcrs) {
                   5299: 		    if ($tcrs ne $ucrs) { next; }
                   5300: 		}
                   5301: 		if ($tsec) {
                   5302: 		    if ($tsec ne $usec) { next; }
                   5303: 		}
                   5304: 		$access=($effect eq 'allow');
                   5305: 		last;
                   5306: 	    }
                   5307: 	    if ($realm eq '' && $role eq '') {
                   5308: 		$access=($effect eq 'allow');
                   5309: 	    }
1.402     bowersj2 5310: 	}
1.341     www      5311:     }
                   5312:     return $access;
                   5313: }
                   5314: 
1.103     harris41 5315: # ------------------------------------------------- Check for a user privilege
1.12      www      5316: 
                   5317: sub allowed {
1.810     raeburn  5318:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5319:     my $ver_orguri=$uri;
1.439     www      5320:     $uri=&deversion($uri);
1.152     www      5321:     my $orguri=$uri;
1.52      www      5322:     $uri=&declutter($uri);
1.809     raeburn  5323: 
1.810     raeburn  5324:     if ($priv eq 'evb') {
                   5325: # Evade communication block restrictions for specified role in a course
                   5326:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5327:             return $1;
                   5328:         } else {
                   5329:             return;
                   5330:         }
                   5331:     }
                   5332: 
1.620     albertel 5333:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5334: # Free bre access to adm and meta resources
1.775     albertel 5335:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5336: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5337: 	&& ($priv eq 'bre')) {
1.14      www      5338: 	return 'F';
1.159     www      5339:     }
                   5340: 
1.545     banghart 5341: # Free bre access to user's own portfolio contents
1.714     raeburn  5342:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5343:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5344: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5345:         my %setters;
                   5346:         my ($startblock,$endblock) = 
                   5347:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5348:         if ($startblock && $endblock) {
                   5349:             return 'B';
                   5350:         } else {
                   5351:             return 'F';
                   5352:         }
1.545     banghart 5353:     }
                   5354: 
1.762     raeburn  5355: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5356:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5357:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5358:         if (exists($env{'request.course.id'})) {
                   5359:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5360:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5361:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5362:                 my $courseprivid=$env{'request.course.id'};
                   5363:                 $courseprivid=~s/\_/\//;
                   5364:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5365:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5366:                     return $1; 
1.762     raeburn  5367:                 } else {
                   5368:                     if ($env{'request.course.sec'}) {
                   5369:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5370:                     }
                   5371:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5372:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5373:                         return $2;
                   5374:                     }
1.714     raeburn  5375:                 }
                   5376:             }
                   5377:         }
                   5378:     }
                   5379: 
1.159     www      5380: # Free bre to public access
                   5381: 
                   5382:     if ($priv eq 'bre') {
1.238     www      5383:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5384: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5385:            return 'F'; 
                   5386:         }
1.238     www      5387:         if ($copyright eq 'priv') {
                   5388:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5389: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5390: 		return '';
                   5391:             }
                   5392:         }
                   5393:         if ($copyright eq 'domain') {
                   5394:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5395: 	    unless (($env{'user.domain'} eq $1) ||
                   5396:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5397: 		return '';
                   5398:             }
1.262     matthew  5399:         }
1.620     albertel 5400:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5401:             # Library role, so allow browsing of resources in this domain.
                   5402:             return 'F';
1.238     www      5403:         }
1.341     www      5404:         if ($copyright eq 'custom') {
                   5405: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5406:         }
1.14      www      5407:     }
1.264     matthew  5408:     # Domain coordinator is trying to create a course
1.620     albertel 5409:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5410:         # uri is the requested domain in this case.
                   5411:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5412:         # a role of dc for the domain in question.
1.620     albertel 5413:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5414:     }
1.29      www      5415: 
1.52      www      5416:     my $thisallowed='';
                   5417:     my $statecond=0;
                   5418:     my $courseprivid='';
                   5419: 
1.1039    raeburn  5420:     my $ownaccess;
1.1043    raeburn  5421:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  5422:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5423:         if ($uri eq '') {
                   5424:             $ownaccess = 1;
                   5425:         } else {
                   5426:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5427:                 my $udom = $env{'user.domain'};
                   5428:                 my $uname = $env{'user.name'};
                   5429:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5430:                     $ownaccess = 1;
1.1040    raeburn  5431:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5432:                     unless ($uri =~ m{\.\./}) {
                   5433:                         $ownaccess = 1;
                   5434:                     }
                   5435:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5436:                     my $now = time;
                   5437:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5438:                         my $adom = $1;
                   5439:                         foreach my $key (keys(%env)) {
1.1042    raeburn  5440:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  5441:                                 my ($start,$end) = split('.',$env{$key});
                   5442:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5443:                                     $ownaccess = 1;
                   5444:                                     last;
                   5445:                                 }
                   5446:                             }
                   5447:                         }
                   5448:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5449:                         my $adom = $1;
                   5450:                         my $aname = $2;
1.1042    raeburn  5451:                         foreach my $role ('ca','aa') { 
                   5452:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   5453:                                 my ($start,$end) =
                   5454:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   5455:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5456:                                     $ownaccess = 1;
                   5457:                                     last;
                   5458:                                 }
1.1039    raeburn  5459:                             }
                   5460:                         }
                   5461:                     }
                   5462:                 }
                   5463:             }
                   5464:         }
                   5465:     }
                   5466: 
1.52      www      5467: # Course
                   5468: 
1.620     albertel 5469:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5470:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5471:             $thisallowed.=$1;
                   5472:         }
1.52      www      5473:     }
1.29      www      5474: 
1.52      www      5475: # Domain
                   5476: 
1.620     albertel 5477:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5478:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5479:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5480:             $thisallowed.=$1;
                   5481:         }
1.12      www      5482:     }
1.52      www      5483: 
                   5484: # Course: uri itself is a course
1.66      www      5485:     my $courseuri=$uri;
                   5486:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5487:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5488: 
1.620     albertel 5489:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5490:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5491:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5492:             $thisallowed.=$1;
                   5493:         }
1.12      www      5494:     }
1.29      www      5495: 
1.665     albertel 5496: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5497: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5498:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5499: 	$thisallowed='';
1.671     raeburn  5500:         my ($match)=&is_on_map($uri);
                   5501:         if ($match) {
                   5502:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5503:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5504:                 $thisallowed.=$1;
                   5505:             }
                   5506:         } else {
1.705     albertel 5507:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5508:             if ($refuri) {
                   5509:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5510:                     $thisallowed='F';
1.671     raeburn  5511:                 } else {
                   5512:                     $refuri=&declutter($refuri);
                   5513:                     my ($match) = &is_on_map($refuri);
                   5514:                     if ($match) {
                   5515:                         $thisallowed='F';
                   5516:                     }
1.669     raeburn  5517:                 }
1.671     raeburn  5518:             }
                   5519:         }
1.314     www      5520:     }
1.492     albertel 5521: 
1.766     albertel 5522:     if ($priv eq 'bre'
                   5523: 	&& $thisallowed ne 'F' 
                   5524: 	&& $thisallowed ne '2'
                   5525: 	&& &is_portfolio_url($uri)) {
                   5526: 	$thisallowed = &portfolio_access($uri);
                   5527:     }
                   5528:     
1.52      www      5529: # Full access at system, domain or course-wide level? Exit.
1.29      www      5530:     if ($thisallowed=~/F/) {
                   5531: 	return 'F';
                   5532:     }
                   5533: 
1.52      www      5534: # If this is generating or modifying users, exit with special codes
1.29      www      5535: 
1.643     www      5536:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5537: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5538: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5539: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5540: 	    unless ($auname) { return $thisallowed; }
                   5541: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5542: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5543: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5544: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5545: 	}
1.52      www      5546: 	return $thisallowed;
                   5547:     }
                   5548: #
1.103     harris41 5549: # Gathered so far: system, domain and course wide privileges
1.52      www      5550: #
                   5551: # Course: See if uri or referer is an individual resource that is part of 
                   5552: # the course
                   5553: 
1.620     albertel 5554:     if ($env{'request.course.id'}) {
1.232     www      5555: 
1.620     albertel 5556:        $courseprivid=$env{'request.course.id'};
                   5557:        if ($env{'request.course.sec'}) {
                   5558:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5559:        }
                   5560:        $courseprivid=~s/\_/\//;
                   5561:        my $checkreferer=1;
1.232     www      5562:        my ($match,$cond)=&is_on_map($uri);
                   5563:        if ($match) {
                   5564:            $statecond=$cond;
1.620     albertel 5565:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5566:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5567:                $thisallowed.=$1;
                   5568:                $checkreferer=0;
                   5569:            }
1.29      www      5570:        }
1.83      www      5571:        
1.148     www      5572:        if ($checkreferer) {
1.620     albertel 5573: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5574:             unless ($refuri) {
1.800     albertel 5575:                 foreach my $key (keys(%env)) {
                   5576: 		    if ($key=~/^httpref\..*\*/) {
                   5577: 			my $pattern=$key;
1.156     www      5578:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5579:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5580:                         $pattern=~s/\//\\\//g;
1.152     www      5581:                         if ($orguri=~/$pattern/) {
1.800     albertel 5582: 			    $refuri=$env{$key};
1.148     www      5583:                         }
                   5584:                     }
1.191     harris41 5585:                 }
1.148     www      5586:             }
1.232     www      5587: 
1.148     www      5588:          if ($refuri) { 
1.152     www      5589: 	  $refuri=&declutter($refuri);
1.232     www      5590:           my ($match,$cond)=&is_on_map($refuri);
                   5591:             if ($match) {
                   5592:               my $refstatecond=$cond;
1.620     albertel 5593:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5594:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5595:                   $thisallowed.=$1;
1.53      www      5596:                   $uri=$refuri;
                   5597:                   $statecond=$refstatecond;
1.52      www      5598:               }
                   5599:           }
1.148     www      5600:         }
1.29      www      5601:        }
1.52      www      5602:    }
1.29      www      5603: 
1.52      www      5604: #
1.103     harris41 5605: # Gathered now: all privileges that could apply, and condition number
1.52      www      5606: # 
                   5607: #
                   5608: # Full or no access?
                   5609: #
1.29      www      5610: 
1.52      www      5611:     if ($thisallowed=~/F/) {
                   5612: 	return 'F';
                   5613:     }
1.29      www      5614: 
1.52      www      5615:     unless ($thisallowed) {
                   5616:         return '';
                   5617:     }
1.29      www      5618: 
1.52      www      5619: # Restrictions exist, deal with them
                   5620: #
                   5621: #   C:according to course preferences
                   5622: #   R:according to resource settings
                   5623: #   L:unless locked
                   5624: #   X:according to user session state
                   5625: #
                   5626: 
                   5627: # Possibly locked functionality, check all courses
1.54      www      5628: # Locks might take effect only after 10 minutes cache expiration for other
                   5629: # courses, and 2 minutes for current course
1.52      www      5630: 
                   5631:     my $envkey;
                   5632:     if ($thisallowed=~/L/) {
1.1000    raeburn  5633:         foreach $envkey (keys(%env)) {
1.54      www      5634:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5635:                my $courseid=$2;
                   5636:                my $roleid=$1.'.'.$2;
1.92      www      5637:                $courseid=~s/^\///;
1.54      www      5638:                my $expiretime=600;
1.620     albertel 5639:                if ($env{'request.role'} eq $roleid) {
1.54      www      5640: 		  $expiretime=120;
                   5641:                }
                   5642: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5643:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5644:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5645: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5646:                }
1.620     albertel 5647:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5648:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5649: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5650:                        &log($env{'user.domain'},$env{'user.name'},
                   5651:                             $env{'user.home'},
1.57      www      5652:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5653:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5654:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5655: 		       return '';
                   5656:                    }
                   5657:                }
1.620     albertel 5658:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5659:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5660: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5661:                        &log($env{'user.domain'},$env{'user.name'},
                   5662:                             $env{'user.home'},
1.57      www      5663:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5664:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5665:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5666: 		       return '';
                   5667:                    }
                   5668:                }
                   5669: 	   }
1.29      www      5670:        }
1.52      www      5671:     }
                   5672:    
                   5673: #
                   5674: # Rest of the restrictions depend on selected course
                   5675: #
                   5676: 
1.620     albertel 5677:     unless ($env{'request.course.id'}) {
1.766     albertel 5678: 	if ($thisallowed eq 'A') {
                   5679: 	    return 'A';
1.814     raeburn  5680:         } elsif ($thisallowed eq 'B') {
                   5681:             return 'B';
1.766     albertel 5682: 	} else {
                   5683: 	    return '1';
                   5684: 	}
1.52      www      5685:     }
1.29      www      5686: 
1.52      www      5687: #
                   5688: # Now user is definitely in a course
                   5689: #
1.53      www      5690: 
                   5691: 
                   5692: # Course preferences
                   5693: 
                   5694:    if ($thisallowed=~/C/) {
1.620     albertel 5695:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5696:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5697:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5698: 	   =~/\Q$rolecode\E/) {
1.689     albertel 5699: 	   if ($priv ne 'pch') { 
                   5700: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5701: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5702: 			$env{'request.course.id'});
                   5703: 	   }
1.237     www      5704:            return '';
                   5705:        }
                   5706: 
1.620     albertel 5707:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5708: 	   =~/\Q$unamedom\E/) {
1.689     albertel 5709: 	   if ($priv ne 'pch') { 
                   5710: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5711: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5712: 			$env{'request.course.id'});
                   5713: 	   }
1.54      www      5714:            return '';
                   5715:        }
1.53      www      5716:    }
                   5717: 
                   5718: # Resource preferences
                   5719: 
                   5720:    if ($thisallowed=~/R/) {
1.620     albertel 5721:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5722:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 5723: 	   if ($priv ne 'pch') { 
                   5724: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5725: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5726: 	   }
                   5727: 	   return '';
1.54      www      5728:        }
1.53      www      5729:    }
1.30      www      5730: 
1.246     www      5731: # Restricted by state or randomout?
1.30      www      5732: 
1.52      www      5733:    if ($thisallowed=~/X/) {
1.620     albertel 5734:       if ($env{'acc.randomout'}) {
1.579     albertel 5735: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5736:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5737:             return ''; 
                   5738:          }
1.247     www      5739:       }
                   5740:       if (&condval($statecond)) {
1.52      www      5741: 	 return '2';
                   5742:       } else {
                   5743:          return '';
                   5744:       }
                   5745:    }
1.30      www      5746: 
1.766     albertel 5747:     if ($thisallowed eq 'A') {
                   5748: 	return 'A';
1.814     raeburn  5749:     } elsif ($thisallowed eq 'B') {
                   5750:         return 'B';
1.766     albertel 5751:     }
1.52      www      5752:    return 'F';
1.232     www      5753: }
                   5754: 
1.710     albertel 5755: sub split_uri_for_cond {
                   5756:     my $uri=&deversion(&declutter(shift));
                   5757:     my @uriparts=split(/\//,$uri);
                   5758:     my $filename=pop(@uriparts);
                   5759:     my $pathname=join('/',@uriparts);
                   5760:     return ($pathname,$filename);
                   5761: }
1.232     www      5762: # --------------------------------------------------- Is a resource on the map?
                   5763: 
                   5764: sub is_on_map {
1.710     albertel 5765:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5766:     #Trying to find the conditional for the file
1.620     albertel 5767:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5768: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5769:     if ($match) {
1.289     bowersj2 5770: 	return (1,$1);
                   5771:     } else {
1.434     www      5772: 	return (0,0);
1.289     bowersj2 5773:     }
1.12      www      5774: }
                   5775: 
1.427     www      5776: # --------------------------------------------------------- Get symb from alias
                   5777: 
                   5778: sub get_symb_from_alias {
                   5779:     my $symb=shift;
                   5780:     my ($map,$resid,$url)=&decode_symb($symb);
                   5781: # Already is a symb
                   5782:     if ($url) { return $symb; }
                   5783: # Must be an alias
                   5784:     my $aliassymb='';
                   5785:     my %bighash;
1.620     albertel 5786:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5787:                             &GDBM_READER(),0640)) {
                   5788:         my $rid=$bighash{'mapalias_'.$symb};
                   5789: 	if ($rid) {
                   5790: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5791: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5792: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5793: 	}
                   5794:         untie %bighash;
                   5795:     }
                   5796:     return $aliassymb;
                   5797: }
                   5798: 
1.12      www      5799: # ----------------------------------------------------------------- Define Role
                   5800: 
                   5801: sub definerole {
                   5802:   if (allowed('mcr','/')) {
                   5803:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5804:     foreach my $role (split(':',$sysrole)) {
                   5805: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5806:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5807:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5808: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5809:                return "refused:s:$crole&$cqual"; 
                   5810:             }
                   5811:         }
1.191     harris41 5812:     }
1.800     albertel 5813:     foreach my $role (split(':',$domrole)) {
                   5814: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5815:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5816:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5817: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5818:                return "refused:d:$crole&$cqual"; 
                   5819:             }
                   5820:         }
1.191     harris41 5821:     }
1.800     albertel 5822:     foreach my $role (split(':',$courole)) {
                   5823: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5824:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5825:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5826: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5827:                return "refused:c:$crole&$cqual"; 
                   5828:             }
                   5829:         }
1.191     harris41 5830:     }
1.620     albertel 5831:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5832:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5833: 	        "rolesdef_$rolename=".
                   5834:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5835:     return reply($command,$env{'user.home'});
1.12      www      5836:   } else {
                   5837:     return 'refused';
                   5838:   }
1.105     harris41 5839: }
                   5840: 
                   5841: # ---------------- Make a metadata query against the network of library servers
                   5842: 
                   5843: sub metadata_query {
1.244     matthew  5844:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5845:     my %rhash;
1.845     albertel 5846:     my %libserv = &all_library();
1.244     matthew  5847:     my @server_list = (defined($server_array) ? @$server_array
                   5848:                                               : keys(%libserv) );
                   5849:     for my $server (@server_list) {
1.118     harris41 5850: 	unless ($custom or $customshow) {
                   5851: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5852: 	    $rhash{$server}=$reply;
                   5853: 	}
                   5854: 	else {
                   5855: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5856: 			     &escape($custom).':'.&escape($customshow),
                   5857: 			     $server);
                   5858: 	    $rhash{$server}=$reply;
                   5859: 	}
1.112     harris41 5860:     }
1.118     harris41 5861:     return \%rhash;
1.240     www      5862: }
                   5863: 
                   5864: # ----------------------------------------- Send log queries and wait for reply
                   5865: 
                   5866: sub log_query {
                   5867:     my ($uname,$udom,$query,%filters)=@_;
                   5868:     my $uhome=&homeserver($uname,$udom);
                   5869:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5870:     my $uhost=&hostname($uhome);
1.800     albertel 5871:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5872:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5873:                        $uhome);
1.479     albertel 5874:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5875:     return get_query_reply($queryid);
                   5876: }
                   5877: 
1.818     raeburn  5878: # -------------------------- Update MySQL table for portfolio file
                   5879: 
                   5880: sub update_portfolio_table {
1.821     raeburn  5881:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5882:     if ($group ne '') {
                   5883:         $file_name =~s /^\Q$group\E//;
                   5884:     }
1.818     raeburn  5885:     my $homeserver = &homeserver($uname,$udom);
                   5886:     my $queryid=
1.821     raeburn  5887:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5888:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5889:     my $reply = &get_query_reply($queryid);
                   5890:     return $reply;
                   5891: }
                   5892: 
1.899     raeburn  5893: # -------------------------- Update MySQL allusers table
                   5894: 
                   5895: sub update_allusers_table {
                   5896:     my ($uname,$udom,$names) = @_;
                   5897:     my $homeserver = &homeserver($uname,$udom);
                   5898:     my $queryid=
                   5899:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5900:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5901:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5902:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5903:                'generation='.&escape($names->{'generation'}).'%%'.
                   5904:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5905:                'id='.&escape($names->{'id'}),$homeserver);
1.1056.4.4  raeburn  5906:     return;
1.899     raeburn  5907: }
                   5908: 
1.508     raeburn  5909: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5910: 
                   5911: sub fetch_enrollment_query {
1.511     raeburn  5912:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5913:     my $homeserver;
1.547     raeburn  5914:     my $maxtries = 1;
1.508     raeburn  5915:     if ($context eq 'automated') {
                   5916:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5917:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5918:     } else {
                   5919:         $homeserver = &homeserver($cnum,$dom);
                   5920:     }
1.838     albertel 5921:     my $host=&hostname($homeserver);
1.506     raeburn  5922:     my $cmd = '';
1.1000    raeburn  5923:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 5924:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5925:     }
                   5926:     $cmd =~ s/%%$//;
                   5927:     $cmd = &escape($cmd);
                   5928:     my $query = 'fetchenrollment';
1.620     albertel 5929:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5930:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5931:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5932:         return 'error: '.$queryid;
                   5933:     }
1.506     raeburn  5934:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5935:     my $tries = 1;
                   5936:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5937:         $reply = &get_query_reply($queryid);
                   5938:         $tries ++;
                   5939:     }
1.526     raeburn  5940:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5941:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5942:     } else {
1.901     albertel 5943:         my @responses = split(/:/,$reply);
1.515     raeburn  5944:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5945:             foreach my $line (@responses) {
                   5946:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5947:                 $$replyref{$key} = $value;
                   5948:             }
                   5949:         } else {
1.506     raeburn  5950:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5951:             foreach my $line (@responses) {
                   5952:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5953:                 $$replyref{$key} = $value;
                   5954:                 if ($value > 0) {
1.800     albertel 5955:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5956:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5957:                         my $destname = $pathname.'/'.$filename;
                   5958:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5959:                         if ($xml_classlist =~ /^error/) {
                   5960:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5961:                         } else {
1.506     raeburn  5962:                             if ( open(FILE,">$destname") ) {
                   5963:                                 print FILE &unescape($xml_classlist);
                   5964:                                 close(FILE);
1.526     raeburn  5965:                             } else {
                   5966:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5967:                             }
                   5968:                         }
                   5969:                     }
                   5970:                 }
                   5971:             }
                   5972:         }
                   5973:         return 'ok';
                   5974:     }
                   5975:     return 'error';
                   5976: }
                   5977: 
1.242     www      5978: sub get_query_reply {
                   5979:     my $queryid=shift;
1.240     www      5980:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5981:     my $reply='';
                   5982:     for (1..100) {
                   5983: 	sleep 2;
                   5984:         if (-e $replyfile.'.end') {
1.448     albertel 5985: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5986: 		$reply = join('',<$fh>);
                   5987: 		close($fh);
1.240     www      5988: 	   } else { return 'error: reply_file_error'; }
1.242     www      5989:            return &unescape($reply);
                   5990: 	}
1.240     www      5991:     }
1.242     www      5992:     return 'timeout:'.$queryid;
1.240     www      5993: }
                   5994: 
                   5995: sub courselog_query {
1.241     www      5996: #
                   5997: # possible filters:
                   5998: # url: url or symb
                   5999: # username
                   6000: # domain
                   6001: # action: view, submit, grade
                   6002: # start: timestamp
                   6003: # end: timestamp
                   6004: #
1.240     www      6005:     my (%filters)=@_;
1.620     albertel 6006:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6007:     if ($filters{'url'}) {
                   6008: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6009:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6010:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6011:     }
1.620     albertel 6012:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6013:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6014:     return &log_query($cname,$cdom,'courselog',%filters);
                   6015: }
                   6016: 
                   6017: sub userlog_query {
1.858     raeburn  6018: #
                   6019: # possible filters:
                   6020: # action: log check role
                   6021: # start: timestamp
                   6022: # end: timestamp
                   6023: #
1.240     www      6024:     my ($uname,$udom,%filters)=@_;
                   6025:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6026: }
                   6027: 
1.506     raeburn  6028: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6029: 
                   6030: sub auto_run {
1.508     raeburn  6031:     my ($cnum,$cdom) = @_;
1.876     raeburn  6032:     my $response = 0;
                   6033:     my $settings;
                   6034:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6035:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6036:         $settings = $domconfig{'autoenroll'};
                   6037:         if ($settings->{'run'} eq '1') {
                   6038:             $response = 1;
                   6039:         }
                   6040:     } else {
1.934     raeburn  6041:         my $homeserver;
                   6042:         if (&is_course($cdom,$cnum)) {
                   6043:             $homeserver = &homeserver($cnum,$cdom);
                   6044:         } else {
                   6045:             $homeserver = &domain($cdom,'primary');
                   6046:         }
                   6047:         if ($homeserver ne 'no_host') {
                   6048:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6049:         }
1.876     raeburn  6050:     }
1.506     raeburn  6051:     return $response;
                   6052: }
1.776     albertel 6053: 
1.506     raeburn  6054: sub auto_get_sections {
1.508     raeburn  6055:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6056:     my $homeserver;
                   6057:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6058:         $homeserver = &homeserver($cnum,$cdom);
                   6059:     }
                   6060:     if (!defined($homeserver)) { 
                   6061:         if ($cdom =~ /^$match_domain$/) {
                   6062:             $homeserver = &domain($cdom,'primary');
                   6063:         }
                   6064:     }
                   6065:     my @secs;
                   6066:     if (defined($homeserver)) {
                   6067:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6068:         unless ($response eq 'refused') {
                   6069:             @secs = split(/:/,$response);
                   6070:         }
1.506     raeburn  6071:     }
                   6072:     return @secs;
                   6073: }
1.776     albertel 6074: 
1.506     raeburn  6075: sub auto_new_course {
1.508     raeburn  6076:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   6077:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  6078:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  6079:     return $response;
                   6080: }
1.776     albertel 6081: 
1.506     raeburn  6082: sub auto_validate_courseID {
1.508     raeburn  6083:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6084:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6085:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6086:     return $response;
                   6087: }
1.776     albertel 6088: 
1.1007    raeburn  6089: sub auto_validate_instcode {
1.1020    raeburn  6090:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6091:     my ($homeserver,$response);
                   6092:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6093:         $homeserver = &homeserver($cnum,$cdom);
                   6094:     }
                   6095:     if (!defined($homeserver)) {
                   6096:         if ($cdom =~ /^$match_domain$/) {
                   6097:             $homeserver = &domain($cdom,'primary');
                   6098:         }
                   6099:     }
1.1056.4.2  raeburn  6100:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6101:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6102:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6103:     return ($outcome,$description);
1.1007    raeburn  6104: }
                   6105: 
1.506     raeburn  6106: sub auto_create_password {
1.873     raeburn  6107:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6108:     my ($homeserver,$response);
1.506     raeburn  6109:     my $create_passwd = 0;
                   6110:     my $authchk = '';
1.873     raeburn  6111:     if ($udom =~ /^$match_domain$/) {
                   6112:         $homeserver = &domain($udom,'primary');
                   6113:     }
                   6114:     if ($homeserver eq '') {
                   6115:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6116:             $homeserver = &homeserver($cnum,$cdom);
                   6117:         }
                   6118:     }
                   6119:     if ($homeserver eq '') {
                   6120:         $authchk = 'nodomain';
1.506     raeburn  6121:     } else {
1.873     raeburn  6122:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6123:         if ($response eq 'refused') {
                   6124:             $authchk = 'refused';
                   6125:         } else {
1.901     albertel 6126:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6127:         }
1.506     raeburn  6128:     }
                   6129:     return ($authparam,$create_passwd,$authchk);
                   6130: }
                   6131: 
1.706     raeburn  6132: sub auto_photo_permission {
                   6133:     my ($cnum,$cdom,$students) = @_;
                   6134:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6135:     my ($outcome,$perm_reqd,$conditions) = 
                   6136: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6137:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6138: 	return (undef,undef);
                   6139:     }
1.706     raeburn  6140:     return ($outcome,$perm_reqd,$conditions);
                   6141: }
                   6142: 
                   6143: sub auto_checkphotos {
                   6144:     my ($uname,$udom,$pid) = @_;
                   6145:     my $homeserver = &homeserver($uname,$udom);
                   6146:     my ($result,$resulttype);
                   6147:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6148: 				   &escape($uname).':'.&escape($pid),
                   6149: 				   $homeserver));
1.709     albertel 6150:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6151: 	return (undef,undef);
                   6152:     }
1.706     raeburn  6153:     if ($outcome) {
                   6154:         ($result,$resulttype) = split(/:/,$outcome);
                   6155:     } 
                   6156:     return ($result,$resulttype);
                   6157: }
                   6158: 
                   6159: sub auto_photochoice {
                   6160:     my ($cnum,$cdom) = @_;
                   6161:     my $homeserver = &homeserver($cnum,$cdom);
                   6162:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6163: 						       &escape($cdom),
                   6164: 						       $homeserver)));
1.709     albertel 6165:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6166: 	return (undef,undef);
                   6167:     }
1.706     raeburn  6168:     return ($update,$comment);
                   6169: }
                   6170: 
                   6171: sub auto_photoupdate {
                   6172:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6173:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6174:     my $host=&hostname($homeserver);
1.706     raeburn  6175:     my $cmd = '';
                   6176:     my $maxtries = 1;
1.800     albertel 6177:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6178:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6179:     }
                   6180:     $cmd =~ s/%%$//;
                   6181:     $cmd = &escape($cmd);
                   6182:     my $query = 'institutionalphotos';
                   6183:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   6184:     unless ($queryid=~/^\Q$host\E\_/) {
                   6185:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   6186:         return 'error: '.$queryid;
                   6187:     }
                   6188:     my $reply = &get_query_reply($queryid);
                   6189:     my $tries = 1;
                   6190:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6191:         $reply = &get_query_reply($queryid);
                   6192:         $tries ++;
                   6193:     }
                   6194:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   6195:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   6196:     } else {
                   6197:         my @responses = split(/:/,$reply);
                   6198:         my $outcome = shift(@responses); 
                   6199:         foreach my $item (@responses) {
                   6200:             my ($key,$value) = split(/=/,$item);
                   6201:             $$photo{$key} = $value;
                   6202:         }
                   6203:         return $outcome;
                   6204:     }
                   6205:     return 'error';
                   6206: }
                   6207: 
1.521     raeburn  6208: sub auto_instcode_format {
1.793     albertel 6209:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   6210: 	$cat_order) = @_;
1.521     raeburn  6211:     my $courses = '';
1.772     raeburn  6212:     my @homeservers;
1.521     raeburn  6213:     if ($caller eq 'global') {
1.841     albertel 6214: 	my %servers = &get_servers($codedom,'library');
                   6215: 	foreach my $tryserver (keys(%servers)) {
                   6216: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6217: 		push(@homeservers,$tryserver);
                   6218: 	    }
1.584     raeburn  6219:         }
1.1022    raeburn  6220:     } elsif ($caller eq 'requests') {
                   6221:         if ($codedom =~ /^$match_domain$/) {
                   6222:             my $chome = &domain($codedom,'primary');
                   6223:             unless ($chome eq 'no_host') {
                   6224:                 push(@homeservers,$chome);
                   6225:             }
                   6226:         }
1.521     raeburn  6227:     } else {
1.772     raeburn  6228:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  6229:     }
1.793     albertel 6230:     foreach my $code (keys(%{$instcodes})) {
                   6231:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  6232:     }
                   6233:     chop($courses);
1.772     raeburn  6234:     my $ok_response = 0;
                   6235:     my $response;
                   6236:     while (@homeservers > 0 && $ok_response == 0) {
                   6237:         my $server = shift(@homeservers); 
                   6238:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   6239:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   6240:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 6241: 		split(/:/,$response);
1.772     raeburn  6242:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   6243:             push(@{$codetitles},&str2array($codetitles_str));
                   6244:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   6245:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   6246:             $ok_response = 1;
                   6247:         }
                   6248:     }
                   6249:     if ($ok_response) {
1.521     raeburn  6250:         return 'ok';
1.772     raeburn  6251:     } else {
                   6252:         return $response;
1.521     raeburn  6253:     }
                   6254: }
                   6255: 
1.792     raeburn  6256: sub auto_instcode_defaults {
                   6257:     my ($domain,$returnhash,$code_order) = @_;
                   6258:     my @homeservers;
1.841     albertel 6259: 
                   6260:     my %servers = &get_servers($domain,'library');
                   6261:     foreach my $tryserver (keys(%servers)) {
                   6262: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6263: 	    push(@homeservers,$tryserver);
                   6264: 	}
1.792     raeburn  6265:     }
1.841     albertel 6266: 
1.792     raeburn  6267:     my $response;
1.841     albertel 6268:     foreach my $server (@homeservers) {
1.792     raeburn  6269:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 6270:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   6271: 	
                   6272: 	foreach my $pair (split(/\&/,$response)) {
                   6273: 	    my ($name,$value)=split(/\=/,$pair);
                   6274: 	    if ($name eq 'code_order') {
                   6275: 		@{$code_order} = split(/\&/,&unescape($value));
                   6276: 	    } else {
                   6277: 		$returnhash->{&unescape($name)}=&unescape($value);
                   6278: 	    }
                   6279: 	}
                   6280: 	return 'ok';
1.792     raeburn  6281:     }
1.841     albertel 6282: 
                   6283:     return $response;
1.1003    raeburn  6284: }
                   6285: 
                   6286: sub auto_possible_instcodes {
1.1007    raeburn  6287:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   6288:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   6289:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   6290:         return;
                   6291:     }
1.1003    raeburn  6292:     my (@homeservers,$uhome);
                   6293:     if (defined(&domain($domain,'primary'))) {
                   6294:         $uhome=&domain($domain,'primary');
                   6295:         push(@homeservers,&domain($domain,'primary'));
                   6296:     } else {
                   6297:         my %servers = &get_servers($domain,'library');
                   6298:         foreach my $tryserver (keys(%servers)) {
                   6299:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6300:                 push(@homeservers,$tryserver);
                   6301:             }
                   6302:         }
                   6303:     }
                   6304:     my $response;
                   6305:     foreach my $server (@homeservers) {
                   6306:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   6307:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  6308:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   6309:             split(':',$response);
                   6310:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   6311:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  6312:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  6313:             my ($name,$value)=split('=',$item);
                   6314:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6315:         }
                   6316:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  6317:             my ($name,$value)=split('=',$item);
                   6318:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6319:         }
                   6320:         return 'ok';
                   6321:     }
                   6322:     return $response;
                   6323: }
1.792     raeburn  6324: 
1.1010    raeburn  6325: sub auto_courserequest_checks {
                   6326:     my ($dom) = @_;
1.1020    raeburn  6327:     my ($homeserver,%validations);
                   6328:     if ($dom =~ /^$match_domain$/) {
                   6329:         $homeserver = &domain($dom,'primary');
                   6330:     }
                   6331:     unless ($homeserver eq 'no_host') {
                   6332:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   6333:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   6334:             my @items = split(/&/,$response);
                   6335:             foreach my $item (@items) {
                   6336:                 my ($key,$value) = split('=',$item);
                   6337:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   6338:             }
                   6339:         }
                   6340:     }
1.1010    raeburn  6341:     return %validations; 
                   6342: }
                   6343: 
1.1020    raeburn  6344: sub auto_courserequest_validation {
                   6345:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   6346:     my ($homeserver,$response);
                   6347:     if ($dom =~ /^$match_domain$/) {
                   6348:         $homeserver = &domain($dom,'primary');
                   6349:     }
                   6350:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  6351:           
1.1020    raeburn  6352:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  6353:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  6354:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   6355:                                     $homeserver));
                   6356:     }
                   6357:     return $response;
                   6358: }
                   6359: 
1.777     albertel 6360: sub auto_validate_class_sec {
1.918     raeburn  6361:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  6362:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  6363:     my $ownerlist;
                   6364:     if (ref($owners) eq 'ARRAY') {
                   6365:         $ownerlist = join(',',@{$owners});
                   6366:     } else {
                   6367:         $ownerlist = $owners;
                   6368:     }
1.773     raeburn  6369:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  6370:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  6371:     return $response;
                   6372: }
                   6373: 
1.679     raeburn  6374: # ------------------------------------------------------- Course Group routines
                   6375: 
                   6376: sub get_coursegroups {
1.809     raeburn  6377:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6378:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6379: }
                   6380: 
1.679     raeburn  6381: sub modify_coursegroup {
                   6382:     my ($cdom,$cnum,$groupsettings) = @_;
                   6383:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6384: }
                   6385: 
1.809     raeburn  6386: sub toggle_coursegroup_status {
                   6387:     my ($cdom,$cnum,$group,$action) = @_;
                   6388:     my ($from_namespace,$to_namespace);
                   6389:     if ($action eq 'delete') {
                   6390:         $from_namespace = 'coursegroups';
                   6391:         $to_namespace = 'deleted_groups';
                   6392:     } else {
                   6393:         $from_namespace = 'deleted_groups';
                   6394:         $to_namespace = 'coursegroups';
                   6395:     }
                   6396:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6397:     if (my $tmp = &error(%curr_group)) {
                   6398:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6399:         return ('read error',$tmp);
                   6400:     } else {
                   6401:         my %savedsettings = %curr_group; 
1.809     raeburn  6402:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6403:         my $deloutcome;
                   6404:         if ($result eq 'ok') {
1.809     raeburn  6405:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6406:         } else {
                   6407:             return ('write error',$result);
                   6408:         }
                   6409:         if ($deloutcome eq 'ok') {
                   6410:             return 'ok';
                   6411:         } else {
                   6412:             return ('delete error',$deloutcome);
                   6413:         }
                   6414:     }
                   6415: }
                   6416: 
1.679     raeburn  6417: sub modify_group_roles {
1.957     raeburn  6418:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6419:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6420:     my $role = 'gr/'.&escape($userprivs);
                   6421:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6422:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6423:     if ($result eq 'ok') {
                   6424:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6425:     }
1.679     raeburn  6426:     return $result;
                   6427: }
                   6428: 
                   6429: sub modify_coursegroup_membership {
                   6430:     my ($cdom,$cnum,$membership) = @_;
                   6431:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6432:     return $result;
                   6433: }
                   6434: 
1.682     raeburn  6435: sub get_active_groups {
                   6436:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6437:     my $now = time;
                   6438:     my %groups = ();
                   6439:     foreach my $key (keys(%env)) {
1.811     albertel 6440:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6441:             my ($start,$end) = split(/\./,$env{$key});
                   6442:             if (($end!=0) && ($end<$now)) { next; }
                   6443:             if (($start!=0) && ($start>$now)) { next; }
                   6444:             if ($1 eq $cdom && $2 eq $cnum) {
                   6445:                 $groups{$3} = $env{$key} ;
                   6446:             }
                   6447:         }
                   6448:     }
                   6449:     return %groups;
                   6450: }
                   6451: 
1.683     raeburn  6452: sub get_group_membership {
                   6453:     my ($cdom,$cnum,$group) = @_;
                   6454:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6455: }
                   6456: 
                   6457: sub get_users_groups {
                   6458:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6459:     my @usersgroups;
1.683     raeburn  6460:     my $cachetime=1800;
                   6461: 
                   6462:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6463:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6464:     if (defined($cached)) {
1.734     albertel 6465:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6466:     } else {  
                   6467:         $grouplist = '';
1.816     raeburn  6468:         my $courseurl = &courseid_to_courseurl($courseid);
1.1056.4.10! raeburn  6469:         my $extra = &freeze_escape({'skipcheck' => 1});
        !          6470:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817     raeburn  6471:         my $access_end = $env{'course.'.$courseid.
                   6472:                               '.default_enrollment_end_date'};
                   6473:         my $now = time;
                   6474:         foreach my $key (keys(%roleshash)) {
                   6475:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6476:                 my $group = $1;
                   6477:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6478:                     my $start = $2;
                   6479:                     my $end = $1;
                   6480:                     if ($start == -1) { next; } # deleted from group
                   6481:                     if (($start!=0) && ($start>$now)) { next; }
                   6482:                     if (($end!=0) && ($end<$now)) {
                   6483:                         if ($access_end && $access_end < $now) {
                   6484:                             if ($access_end - $end < 86400) {
                   6485:                                 push(@usersgroups,$group);
1.733     raeburn  6486:                             }
                   6487:                         }
1.817     raeburn  6488:                         next;
1.733     raeburn  6489:                     }
1.817     raeburn  6490:                     push(@usersgroups,$group);
1.683     raeburn  6491:                 }
                   6492:             }
                   6493:         }
1.817     raeburn  6494:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6495:         $grouplist = join(':',@usersgroups);
                   6496:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6497:     }
1.733     raeburn  6498:     return @usersgroups;
1.683     raeburn  6499: }
                   6500: 
                   6501: sub devalidate_getgroups_cache {
                   6502:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6503:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6504: 
1.683     raeburn  6505:     my $hashid="$udom:$uname:$courseid";
                   6506:     &devalidate_cache_new('getgroups',$hashid);
                   6507: }
                   6508: 
1.12      www      6509: # ------------------------------------------------------------------ Plain Text
                   6510: 
                   6511: sub plaintext {
1.988     raeburn  6512:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  6513:     if ($short =~ m{^cr/}) {
1.758     albertel 6514: 	return (split('/',$short))[-1];
                   6515:     }
1.742     raeburn  6516:     if (!defined($cid)) {
                   6517:         $cid = $env{'request.course.id'};
                   6518:     }
                   6519:     my %rolenames = (
1.1008    raeburn  6520:                       Course    => 'std',
                   6521:                       Community => 'alt1',
1.742     raeburn  6522:                     );
1.1037    raeburn  6523:     if ($cid ne '') {
                   6524:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   6525:             unless ($forcedefault) {
                   6526:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6527:                 &Apache::lonlocal::mt_escape(\$roletext);
                   6528:                 return &Apache::lonlocal::mt($roletext);
                   6529:             }
                   6530:         }
                   6531:     }
                   6532:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   6533:         (defined($rolenames{$type})) && 
                   6534:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  6535:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  6536:     } elsif ($cid ne '') {
                   6537:         my $crstype = $env{'course.'.$cid.'.type'};
                   6538:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   6539:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   6540:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   6541:         }
1.742     raeburn  6542:     }
1.1037    raeburn  6543:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      6544: }
                   6545: 
                   6546: # ----------------------------------------------------------------- Assign Role
                   6547: 
                   6548: sub assignrole {
1.957     raeburn  6549:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6550:         $context)=@_;
1.21      www      6551:     my $mrole;
                   6552:     if ($role =~ /^cr\//) {
1.393     www      6553:         my $cwosec=$url;
1.811     albertel 6554:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      6555: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  6556:            my $refused = 1;
                   6557:            if ($context eq 'requestcourses') {
                   6558:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   6559:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   6560:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   6561:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6562:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6563:                            if ($crsenv{'internal.courseowner'} eq
                   6564:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   6565:                                $refused = '';
                   6566:                            }
                   6567:                        }
                   6568:                    }
                   6569:                }
                   6570:            }
                   6571:            if ($refused) {
                   6572:                &logthis('Refused custom assignrole: '.
                   6573:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   6574:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   6575:                return 'refused';
                   6576:            }
1.104     www      6577:         }
1.21      www      6578:         $mrole='cr';
1.678     raeburn  6579:     } elsif ($role =~ /^gr\//) {
                   6580:         my $cwogrp=$url;
1.811     albertel 6581:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  6582:         unless (&allowed('mdg',$cwogrp)) {
                   6583:             &logthis('Refused group assignrole: '.
                   6584:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   6585:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   6586:             return 'refused';
                   6587:         }
                   6588:         $mrole='gr';
1.21      www      6589:     } else {
1.82      www      6590:         my $cwosec=$url;
1.811     albertel 6591:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  6592:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   6593:             my $refused;
                   6594:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   6595:                 if (!(&allowed('c'.$role,$url))) {
                   6596:                     $refused = 1;
                   6597:                 }
                   6598:             } else {
                   6599:                 $refused = 1;
                   6600:             }
1.947     raeburn  6601:             if ($refused) {
1.1045    raeburn  6602:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6603:                 if (!$selfenroll && $context eq 'course') {
                   6604:                     my %crsenv;
                   6605:                     if ($role eq 'cc' || $role eq 'co') {
                   6606:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6607:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   6608:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   6609:                                 if ($crsenv{'internal.courseowner'} eq 
                   6610:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6611:                                     $refused = '';
                   6612:                                 }
                   6613:                             }
                   6614:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   6615:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   6616:                                 if ($crsenv{'internal.courseowner'} eq 
                   6617:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6618:                                     $refused = '';
                   6619:                                 }
                   6620:                             }
                   6621:                         }
                   6622:                     }
                   6623:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  6624:                     $refused = '';
1.1017    raeburn  6625:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  6626:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  6627:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  6628:                         my $wrongcc;
                   6629:                         if ($cnum =~ /^$match_community$/) {
                   6630:                             $wrongcc = 1 if ($role eq 'cc');
                   6631:                         } else {
                   6632:                             $wrongcc = 1 if ($role eq 'co');
                   6633:                         }
                   6634:                         unless ($wrongcc) {
                   6635:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6636:                             if ($crsenv{'internal.courseowner'} eq 
                   6637:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   6638:                                 $refused = '';
                   6639:                             }
1.1017    raeburn  6640:                         }
                   6641:                     }
                   6642:                 }
                   6643:                 if ($refused) {
1.947     raeburn  6644:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   6645:                              ' '.$role.' '.$end.' '.$start.' by '.
                   6646: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   6647:                     return 'refused';
                   6648:                 }
1.932     raeburn  6649:             }
1.104     www      6650:         }
1.21      www      6651:         $mrole=$role;
                   6652:     }
1.620     albertel 6653:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6654:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6655:     if ($end) { $command.='_'.$end; }
1.21      www      6656:     if ($start) {
                   6657: 	if ($end) { 
1.81      www      6658:            $command.='_'.$start; 
1.21      www      6659:         } else {
1.81      www      6660:            $command.='_0_'.$start;
1.21      www      6661:         }
                   6662:     }
1.739     raeburn  6663:     my $origstart = $start;
                   6664:     my $origend = $end;
1.957     raeburn  6665:     my $delflag;
1.357     www      6666: # actually delete
                   6667:     if ($deleteflag) {
1.373     www      6668: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6669: # modify command to delete the role
1.620     albertel 6670:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6671:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6672: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6673: # set start and finish to negative values for userrolelog
                   6674:            $start=-1;
                   6675:            $end=-1;
1.957     raeburn  6676:            $delflag = 1;
1.357     www      6677:         }
                   6678:     }
                   6679: # send command
1.349     www      6680:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6681: # log new user role if status is ok
1.349     www      6682:     if ($answer eq 'ok') {
1.663     raeburn  6683: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6684: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6685:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6686:         unless ($role =~ /^gr/) {
                   6687:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6688:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6689:         }
1.1053    raeburn  6690:         if ($role eq 'cc') {
                   6691:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   6692:         }
1.349     www      6693:     }
                   6694:     return $answer;
1.169     harris41 6695: }
                   6696: 
1.1053    raeburn  6697: sub autoupdate_coowners {
                   6698:     my ($url,$end,$start,$uname,$udom) = @_;
                   6699:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   6700:     if (($cdom ne '') && ($cnum ne '')) {
                   6701:         my $now = time;
                   6702:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   6703:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   6704:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   6705:             my $instcode = $coursehash{'internal.coursecode'};
                   6706:             if ($instcode ne '') {
1.1056    raeburn  6707:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   6708:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  6709:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  6710:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   6711:                         if ($result eq 'valid') {
                   6712:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  6713:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6714:                                     push(@newcoowners,$coowner);
                   6715:                                 }
                   6716:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   6717:                                     push(@newcoowners,$uname.':'.$udom);
                   6718:                                 }
                   6719:                                 @newcoowners = sort(@newcoowners);
                   6720:                             } else {
                   6721:                                 push(@newcoowners,$uname.':'.$udom);
                   6722:                             }
                   6723:                         } else {
                   6724:                             if ($coursehash{'internal.co-owners'}) {
                   6725:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6726:                                     unless ($coowner eq $uname.':'.$udom) {
                   6727:                                         push(@newcoowners,$coowner);
                   6728:                                     }
                   6729:                                 }
                   6730:                                 unless (@newcoowners > 0) {
                   6731:                                     $delcoowners = 1;
                   6732:                                     $coowners = '';
                   6733:                                 }
                   6734:                             }
                   6735:                         }
                   6736:                         if (@newcoowners || $delcoowners) {
                   6737:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   6738:                                             $delcoowners,@newcoowners);
                   6739:                         }
                   6740:                     }
                   6741:                 }
                   6742:             }
                   6743:         }
                   6744:     }
                   6745: }
                   6746: 
                   6747: sub store_coowners {
                   6748:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   6749:     my $cid = $cdom.'_'.$cnum;
                   6750:     my ($coowners,$delresult,$putresult);
                   6751:     if (@newcoowners) {
                   6752:         $coowners = join(',',@newcoowners);
                   6753:         my %coownershash = (
                   6754:                             'internal.co-owners' => $coowners,
                   6755:                            );
                   6756:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   6757:         if ($putresult eq 'ok') {
                   6758:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   6759:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   6760:             }
                   6761:         }
                   6762:     }
                   6763:     if ($delcoowners) {
                   6764:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   6765:         if ($delresult eq 'ok') {
                   6766:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   6767:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   6768:             }
                   6769:         }
                   6770:     }
                   6771:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   6772:         my %crsinfo =
                   6773:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6774:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   6775:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   6776:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   6777:         }
                   6778:     }
                   6779: }
                   6780: 
1.169     harris41 6781: # -------------------------------------------------- Modify user authentication
1.197     www      6782: # Overrides without validation
                   6783: 
1.169     harris41 6784: sub modifyuserauth {
                   6785:     my ($udom,$uname,$umode,$upass)=@_;
                   6786:     my $uhome=&homeserver($uname,$udom);
1.197     www      6787:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6788:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6789:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6790:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6791:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6792: 		     &escape($upass),$uhome);
1.620     albertel 6793:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6794:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6795:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6796:     &log($udom,,$uname,$uhome,
1.620     albertel 6797:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6798:                                      $env{'user.name'}.', '.$umode.
1.197     www      6799:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 6800:     unless ($reply eq 'ok') {
1.197     www      6801:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 6802: 	return 'error: '.$reply;
                   6803:     }   
1.170     harris41 6804:     return 'ok';
1.80      www      6805: }
                   6806: 
1.81      www      6807: # --------------------------------------------------------------- Modify a user
1.80      www      6808: 
1.81      www      6809: sub modifyuser {
1.206     matthew  6810:     my ($udom,    $uname, $uid,
                   6811:         $umode,   $upass, $first,
                   6812:         $middle,  $last,  $gene,
1.1056.4.1  raeburn  6813:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 6814:     $udom= &LONCAPA::clean_domain($udom);
                   6815:     $uname=&LONCAPA::clean_username($uname);
1.1056.4.1  raeburn  6816:     my $showcandelete = 'none';
                   6817:     if (ref($candelete) eq 'ARRAY') {
                   6818:         if (@{$candelete} > 0) {
                   6819:             $showcandelete = join(', ',@{$candelete});
                   6820:         }
                   6821:     }
1.81      www      6822:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      6823:              $umode.', '.$first.', '.$middle.', '.
1.1056.4.1  raeburn  6824:              $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  6825:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   6826:                                      ' desiredhome not specified'). 
1.620     albertel 6827:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6828:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 6829:     my $uhome=&homeserver($uname,$udom,'true');
1.1056.4.4  raeburn  6830:     my $newuser;
                   6831:     if ($uhome eq 'no_host') {
                   6832:         $newuser = 1;
                   6833:     }
1.80      www      6834: # ----------------------------------------------------------------- Create User
1.406     albertel 6835:     if (($uhome eq 'no_host') && 
                   6836: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      6837:         my $unhome='';
1.844     albertel 6838:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  6839:             $unhome = $desiredhome;
1.620     albertel 6840: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   6841: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  6842:         } else { # load balancing routine for determining $unhome
1.81      www      6843:             my $loadm=10000000;
1.841     albertel 6844: 	    my %servers = &get_servers($udom,'library');
                   6845: 	    foreach my $tryserver (keys(%servers)) {
                   6846: 		my $answer=reply('load',$tryserver);
                   6847: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   6848: 		    $loadm=$answer;
                   6849: 		    $unhome=$tryserver;
                   6850: 		}
1.80      www      6851: 	    }
                   6852:         }
                   6853:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  6854: 	    return 'error: unable to find a home server for '.$uname.
                   6855:                    ' in domain '.$udom;
1.80      www      6856:         }
                   6857:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   6858:                          &escape($upass),$unhome);
                   6859: 	unless ($reply eq 'ok') {
                   6860:             return 'error: '.$reply;
                   6861:         }   
1.230     stredwic 6862:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      6863:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  6864: 	    return 'error: unable verify users home machine.';
1.80      www      6865:         }
1.209     matthew  6866:     }   # End of creation of new user
1.80      www      6867: # ---------------------------------------------------------------------- Add ID
                   6868:     if ($uid) {
                   6869:        $uid=~tr/A-Z/a-z/;
                   6870:        my %uidhash=&idrget($udom,$uname);
1.196     www      6871:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   6872:          && (!$forceid)) {
1.80      www      6873: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  6874: 	      return 'error: user id "'.$uid.'" does not match '.
                   6875:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      6876:           }
                   6877:        } else {
                   6878: 	  &idput($udom,($uname => $uid));
                   6879:        }
                   6880:     }
                   6881: # -------------------------------------------------------------- Add names, etc
1.313     matthew  6882:     my @tmp=&get('environment',
1.899     raeburn  6883: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  6884:                     'permanentemail','inststatus'],
1.134     albertel 6885: 		   $udom,$uname);
1.1056.4.4  raeburn  6886:     my (%names,%oldnames);
1.313     matthew  6887:     if ($tmp[0] =~ m/^error:.*/) { 
                   6888:         %names=(); 
                   6889:     } else {
                   6890:         %names = @tmp;
1.1056.4.4  raeburn  6891:         %oldnames = %names;
1.313     matthew  6892:     }
1.1056.4.6  raeburn  6893: #
1.1056.4.1  raeburn  6894: # If name, email and/or uid are blank (e.g., because an uploaded file
                   6895: # of users did not contain them), do not overwrite existing values
                   6896: # unless field is in $candelete array ref.  
                   6897: #
                   6898: 
                   6899:     my @fields = ('firstname','middlename','lastname','generation',
                   6900:                   'permanentemail','id');
                   6901:     my %newvalues;
                   6902:     if (ref($candelete) eq 'ARRAY') {
                   6903:         foreach my $field (@fields) {
                   6904:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   6905:                 if ($field eq 'firstname') {
                   6906:                     $names{$field} = $first;
                   6907:                 } elsif ($field eq 'middlename') {
                   6908:                     $names{$field} = $middle;
                   6909:                 } elsif ($field eq 'lastname') {
                   6910:                     $names{$field} = $last;
                   6911:                 } elsif ($field eq 'generation') { 
                   6912:                     $names{$field} = $gene;
                   6913:                 } elsif ($field eq 'permanentemail') {
                   6914:                     $names{$field} = $email;
                   6915:                 } elsif ($field eq 'id') {
                   6916:                     $names{$field}  = $uid;
                   6917:                 }
                   6918:             }
                   6919:         }
                   6920:     }
1.388     www      6921:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  6922:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      6923:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  6924:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      6925:     if ($email) {
                   6926:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  6927:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      6928:     }
1.899     raeburn  6929:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  6930:     if (defined($inststatus)) {
                   6931:         $names{'inststatus'} = '';
                   6932:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   6933:         if (ref($usertypes) eq 'HASH') {
                   6934:             my @okstatuses; 
                   6935:             foreach my $item (split(/:/,$inststatus)) {
                   6936:                 if (defined($usertypes->{$item})) {
                   6937:                     push(@okstatuses,$item);  
                   6938:                 }
                   6939:             }
                   6940:             if (@okstatuses) {
                   6941:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   6942:             }
                   6943:         }
                   6944:     }
1.1056.4.4  raeburn  6945:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  6946:                  $umode.', '.$first.', '.$middle.', '.
1.1056.4.4  raeburn  6947:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  6948:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   6949:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   6950:     } else {
                   6951:         $logmsg .= ' during self creation';
                   6952:     }
1.1056.4.4  raeburn  6953:     my $changed;
                   6954:     if ($newuser) {
                   6955:         $changed = 1;
                   6956:     } else {
                   6957:         foreach my $field (@fields) {
                   6958:             if ($names{$field} ne $oldnames{$field}) {
                   6959:                 $changed = 1;
                   6960:                 last;
                   6961:             }
                   6962:         }
                   6963:     }
                   6964:     unless ($changed) {
                   6965:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   6966:         &logthis($logmsg);
                   6967:         return 'ok';
                   6968:     }
                   6969:     my $reply = &put('environment', \%names, $udom,$uname);
                   6970:     if ($reply ne 'ok') {
                   6971:         return 'error: '.$reply;
                   6972:     }
                   6973:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   6974:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   6975:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  6976:     &logthis($logmsg);
1.134     albertel 6977:     return 'ok';
1.80      www      6978: }
                   6979: 
1.81      www      6980: # -------------------------------------------------------------- Modify student
1.80      www      6981: 
1.81      www      6982: sub modifystudent {
                   6983:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  6984:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  6985:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 6986:     if (!$cid) {
1.620     albertel 6987: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6988: 	    return 'not_in_class';
                   6989: 	}
1.80      www      6990:     }
                   6991: # --------------------------------------------------------------- Make the user
1.81      www      6992:     my $reply=&modifyuser
1.209     matthew  6993: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  6994:          $desiredhome,$email,$inststatus);
1.80      www      6995:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  6996:     # This will cause &modify_student_enrollment to get the uid from the
                   6997:     # students environment
                   6998:     $uid = undef if (!$forceid);
1.455     albertel 6999:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  7000: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  7001:     return $reply;
                   7002: }
                   7003: 
                   7004: sub modify_student_enrollment {
1.957     raeburn  7005:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 7006:     my ($cdom,$cnum,$chome);
                   7007:     if (!$cid) {
1.620     albertel 7008: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7009: 	    return 'not_in_class';
                   7010: 	}
1.620     albertel 7011: 	$cdom=$env{'course.'.$cid.'.domain'};
                   7012: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 7013:     } else {
                   7014: 	($cdom,$cnum)=split(/_/,$cid);
                   7015:     }
1.620     albertel 7016:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 7017:     if (!$chome) {
1.457     raeburn  7018: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  7019:     }
1.455     albertel 7020:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  7021:     # Make sure the user exists
1.81      www      7022:     my $uhome=&homeserver($uname,$udom);
                   7023:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7024: 	return 'error: no such user';
                   7025:     }
1.297     matthew  7026:     # Get student data if we were not given enough information
                   7027:     if (!defined($first)  || $first  eq '' || 
                   7028:         !defined($last)   || $last   eq '' || 
                   7029:         !defined($uid)    || $uid    eq '' || 
                   7030:         !defined($middle) || $middle eq '' || 
                   7031:         !defined($gene)   || $gene   eq '') {
1.294     matthew  7032:         # They did not supply us with enough data to enroll the student, so
                   7033:         # we need to pick up more information.
1.297     matthew  7034:         my %tmp = &get('environment',
1.294     matthew  7035:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  7036:                        ,$udom,$uname);
                   7037: 
1.800     albertel 7038:         #foreach my $key (keys(%tmp)) {
                   7039:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 7040:         #}
1.294     matthew  7041:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   7042:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   7043:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  7044:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  7045:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   7046:     }
1.556     albertel 7047:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 7048:     my $reply=cput('classlist',
                   7049: 		   {"$uname:$udom" => 
1.515     raeburn  7050: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7051: 		   $cdom,$cnum);
1.81      www      7052:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7053: 	return 'error: '.$reply;
1.652     albertel 7054:     } else {
                   7055: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      7056:     }
1.297     matthew  7057:     # Add student role to user
1.83      www      7058:     my $uurl='/'.$cid;
1.81      www      7059:     $uurl=~s/\_/\//g;
                   7060:     if ($usec) {
                   7061: 	$uurl.='/'.$usec;
                   7062:     }
1.957     raeburn  7063:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      7064: }
                   7065: 
1.556     albertel 7066: sub format_name {
                   7067:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7068:     my $name;
                   7069:     if ($first ne 'lastname') {
                   7070: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7071:     } else {
                   7072: 	if ($lastname=~/\S/) {
                   7073: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7074: 	    $name=~s/\s+,/,/;
                   7075: 	} else {
                   7076: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7077: 	}
                   7078:     }
                   7079:     $name=~s/^\s+//;
                   7080:     $name=~s/\s+$//;
                   7081:     $name=~s/\s+/ /g;
                   7082:     return $name;
                   7083: }
                   7084: 
1.84      www      7085: # ------------------------------------------------- Write to course preferences
                   7086: 
                   7087: sub writecoursepref {
                   7088:     my ($courseid,%prefs)=@_;
                   7089:     $courseid=~s/^\///;
                   7090:     $courseid=~s/\_/\//g;
                   7091:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7092:     my $chome=homeserver($cnum,$cdomain);
                   7093:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7094: 	return 'error: no such course';
                   7095:     }
                   7096:     my $cstring='';
1.800     albertel 7097:     foreach my $pref (keys(%prefs)) {
                   7098: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7099:     }
1.84      www      7100:     $cstring=~s/\&$//;
                   7101:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7102: }
                   7103: 
                   7104: # ---------------------------------------------------------- Make/modify course
                   7105: 
                   7106: sub createcourse {
1.741     raeburn  7107:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7108:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7109:     $url=&declutter($url);
                   7110:     my $cid='';
1.1028    raeburn  7111:     if ($context eq 'requestcourses') {
                   7112:         my $can_create = 0;
                   7113:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7114:         if ($udom eq $ownerdom) {
                   7115:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7116:                                   $context)) {
                   7117:                 $can_create = 1;
                   7118:             }
                   7119:         } else {
                   7120:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7121:                                            $category);
                   7122:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7123:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7124:                 if (@curr > 0) {
                   7125:                     my @options = qw(approval validate autolimit);
                   7126:                     my $optregex = join('|',@options);
                   7127:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7128:                         $can_create = 1;
                   7129:                     }
                   7130:                 }
                   7131:             }
                   7132:         }
                   7133:         if ($can_create) {
                   7134:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7135:                 unless (&allowed('ccc',$udom)) {
                   7136:                     return 'refused'; 
                   7137:                 }
1.1017    raeburn  7138:             }
                   7139:         } else {
                   7140:             return 'refused';
                   7141:         }
1.1028    raeburn  7142:     } elsif (!&allowed('ccc',$udom)) {
                   7143:         return 'refused';
1.84      www      7144:     }
1.1011    raeburn  7145: # --------------------------------------------------------------- Get Unique ID
                   7146:     my $uname;
                   7147:     if ($cnum =~ /^$match_courseid$/) {
                   7148:         my $chome=&homeserver($cnum,$udom,'true');
                   7149:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7150:             $uname = $cnum;
                   7151:         } else {
1.1038    raeburn  7152:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7153:         }
                   7154:     } else {
1.1038    raeburn  7155:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7156:     }
                   7157:     return $uname if ($uname =~ /^error/);
                   7158: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7159:     if (!defined($course_server)) {
                   7160:         if (defined(&domain($udom,'primary'))) {
                   7161:             $course_server = &domain($udom,'primary');
                   7162:         } else {
                   7163:             $course_server = $env{'user.home'}; 
                   7164:         }
                   7165:     }
                   7166:     my %host_servers =
                   7167:         &Apache::lonnet::get_servers($udom,'library');
                   7168:     unless ($host_servers{$course_server}) {
                   7169:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  7170:     }
1.84      www      7171: # ------------------------------------------------------------- Make the course
                   7172:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  7173:                       $course_server);
1.84      www      7174:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  7175:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      7176:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7177: 	return 'error: no such course';
                   7178:     }
1.271     www      7179: # ----------------------------------------------------------------- Course made
1.516     raeburn  7180: # log existence
1.1029    raeburn  7181:     my $now = time;
1.918     raeburn  7182:     my $newcourse = {
                   7183:                     $udom.'_'.$uname => {
1.921     raeburn  7184:                                      description => $description,
                   7185:                                      inst_code   => $inst_code,
                   7186:                                      owner       => $course_owner,
                   7187:                                      type        => $crstype,
1.1029    raeburn  7188:                                      creator     => $env{'user.name'}.':'.
                   7189:                                                     $env{'user.domain'},
                   7190:                                      created     => $now,
                   7191:                                      context     => $context,
1.918     raeburn  7192:                                                 },
                   7193:                     };
1.921     raeburn  7194:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      7195: # set toplevel url
1.271     www      7196:     my $topurl=$url;
                   7197:     unless ($nonstandard) {
                   7198: # ------------------------------------------ For standard courses, make top url
                   7199:         my $mapurl=&clutter($url);
1.278     www      7200:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 7201:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      7202: <map>
                   7203: <resource id="1" type="start"></resource>
                   7204: <resource id="2" src="$mapurl"></resource>
                   7205: <resource id="3" type="finish"></resource>
                   7206: <link index="1" from="1" to="2"></link>
                   7207: <link index="2" from="2" to="3"></link>
                   7208: </map>
                   7209: ENDINITMAP
                   7210:         $topurl=&declutter(
1.638     albertel 7211:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      7212:                           );
                   7213:     }
                   7214: # ----------------------------------------------------------- Write preferences
1.84      www      7215:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  7216:                      ('description'              => $description,
                   7217:                       'url'                      => $topurl,
                   7218:                       'internal.creator'         => $env{'user.name'}.':'.
                   7219:                                                     $env{'user.domain'},
                   7220:                       'internal.created'         => $now,
                   7221:                       'internal.creationcontext' => $context)
                   7222:                     );
1.84      www      7223:     return '/'.$udom.'/'.$uname;
                   7224: }
                   7225: 
1.1011    raeburn  7226: # ------------------------------------------------------------------- Create ID
                   7227: sub generate_coursenum {
1.1038    raeburn  7228:     my ($udom,$crstype) = @_;
1.1011    raeburn  7229:     my $domdesc = &domain($udom);
                   7230:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  7231:     my $first;
                   7232:     if ($crstype eq 'Community') {
                   7233:         $first = '0';
                   7234:     } else {
                   7235:         $first = int(1+rand(9)); 
                   7236:     } 
                   7237:     my $uname=$first.
1.1011    raeburn  7238:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7239:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7240:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7241: # ----------------------------------------------- Make sure that does not exist
                   7242:     my $uhome=&homeserver($uname,$udom,'true');
                   7243:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  7244:         if ($crstype eq 'Community') {
                   7245:             $first = '0';
                   7246:         } else {
                   7247:             $first = int(1+rand(9));
                   7248:         }
                   7249:         $uname=$first.
1.1011    raeburn  7250:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7251:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7252:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7253:         $uhome=&homeserver($uname,$udom,'true');
                   7254:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   7255:             return 'error: unable to generate unique course-ID';
                   7256:         }
                   7257:     }
                   7258:     return $uname;
                   7259: }
                   7260: 
1.813     albertel 7261: sub is_course {
                   7262:     my ($cdom,$cnum) = @_;
                   7263:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  7264: 				undef,'.');
1.813     albertel 7265:     if (exists($courses{$cdom.'_'.$cnum})) {
                   7266:         return 1;
                   7267:     }
                   7268:     return 0;
                   7269: }
                   7270: 
1.1015    raeburn  7271: sub store_userdata {
                   7272:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  7273:     my $result;
1.1016    raeburn  7274:     if ($datakey ne '') {
1.1013    raeburn  7275:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  7276:             if ($udom eq '' || $uname eq '') {
                   7277:                 $udom = $env{'user.domain'};
                   7278:                 $uname = $env{'user.name'};
                   7279:             }
                   7280:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  7281:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   7282:                 $result = 'error: no_host';
                   7283:             } else {
                   7284:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   7285:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   7286: 
                   7287:                 my $namevalue='';
                   7288:                 foreach my $key (keys(%{$storehash})) {
                   7289:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7290:                 }
                   7291:                 $namevalue=~s/\&$//;
                   7292:                 $result =  &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015    raeburn  7293:                                   "$namespace:$datakey:$namevalue",$uhome);
1.1013    raeburn  7294:             }
                   7295:         } else {
                   7296:             $result = 'error: data to store was not a hash reference'; 
                   7297:         }
                   7298:     } else {
                   7299:         $result= 'error: invalid requestkey'; 
                   7300:     }
                   7301:     return $result;
                   7302: }
                   7303: 
1.21      www      7304: # ---------------------------------------------------------- Assign Custom Role
                   7305: 
                   7306: sub assigncustomrole {
1.957     raeburn  7307:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7308:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  7309:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      7310: }
                   7311: 
                   7312: # ----------------------------------------------------------------- Revoke Role
                   7313: 
                   7314: sub revokerole {
1.957     raeburn  7315:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7316:     my $now=time;
1.965     raeburn  7317:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      7318: }
                   7319: 
                   7320: # ---------------------------------------------------------- Revoke Custom Role
                   7321: 
                   7322: sub revokecustomrole {
1.957     raeburn  7323:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7324:     my $now=time;
1.357     www      7325:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  7326:            $deleteflag,$selfenroll,$context);
1.17      www      7327: }
                   7328: 
1.533     banghart 7329: # ------------------------------------------------------------ Disk usage
1.535     albertel 7330: sub diskusage {
1.955     raeburn  7331:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   7332:     $directorypath =~ s/\/$//;
                   7333:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   7334:                        .&escape($getpropath).':'.&escape($uname).':'
                   7335:                        .&escape($udom),homeserver($uname,$udom));
                   7336:     if ($listing eq 'unknown_cmd') {
                   7337:         if ($getpropath) {
                   7338:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   7339:         }
                   7340:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   7341:     }
1.514     albertel 7342:     return $listing;
1.512     banghart 7343: }
                   7344: 
1.566     banghart 7345: sub is_locked {
                   7346:     my ($file_name, $domain, $user) = @_;
                   7347:     my @check;
                   7348:     my $is_locked;
                   7349:     push @check, $file_name;
1.613     albertel 7350:     my %locked = &get('file_permissions',\@check,
1.620     albertel 7351: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 7352:     my ($tmp)=keys(%locked);
                   7353:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  7354:     
1.566     banghart 7355:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  7356:         $is_locked = 'false';
                   7357:         foreach my $entry (@{$locked{$file_name}}) {
                   7358:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  7359:                $is_locked = 'true';
                   7360:                last;
1.745     raeburn  7361:            }
                   7362:        }
1.566     banghart 7363:     } else {
                   7364:         $is_locked = 'false';
                   7365:     }
                   7366: }
                   7367: 
1.759     albertel 7368: sub declutter_portfile {
                   7369:     my ($file) = @_;
1.833     albertel 7370:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 7371:     return $file;
                   7372: }
                   7373: 
1.559     banghart 7374: # ------------------------------------------------------------- Mark as Read Only
                   7375: 
                   7376: sub mark_as_readonly {
                   7377:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 7378:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7379:     my ($tmp)=keys(%current_permissions);
                   7380:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 7381:     foreach my $file (@{$files}) {
1.759     albertel 7382: 	$file = &declutter_portfile($file);
1.561     banghart 7383:         push(@{$current_permissions{$file}},$what);
1.559     banghart 7384:     }
1.613     albertel 7385:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7386:     return;
                   7387: }
                   7388: 
1.572     banghart 7389: # ------------------------------------------------------------Save Selected Files
                   7390: 
                   7391: sub save_selected_files {
                   7392:     my ($user, $path, @files) = @_;
                   7393:     my $filename = $user."savedfiles";
1.573     banghart 7394:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 7395:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 7396:     foreach my $file (@files) {
1.620     albertel 7397:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 7398:     }
                   7399:     foreach my $file (@other_files) {
1.574     banghart 7400:         print (OUT $file."\n");
1.572     banghart 7401:     }
1.574     banghart 7402:     close (OUT);
1.572     banghart 7403:     return 'ok';
                   7404: }
                   7405: 
1.574     banghart 7406: sub clear_selected_files {
                   7407:     my ($user) = @_;
                   7408:     my $filename = $user."savedfiles";
                   7409:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7410:     print (OUT undef);
                   7411:     close (OUT);
                   7412:     return ("ok");    
                   7413: }
                   7414: 
1.572     banghart 7415: sub files_in_path {
                   7416:     my ($user, $path) = @_;
                   7417:     my $filename = $user."savedfiles";
                   7418:     my %return_files;
1.574     banghart 7419:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 7420:     while (my $line_in = <IN>) {
1.574     banghart 7421:         chomp ($line_in);
                   7422:         my @paths_and_file = split (m!/!, $line_in);
                   7423:         my $file_part = pop (@paths_and_file);
                   7424:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 7425:         $path_part.='/';
                   7426:         my $path_and_file = $path_part.$file_part;
                   7427:         if ($path_part eq $path) {
                   7428:             $return_files{$file_part}= 'selected';
                   7429:         }
                   7430:     }
1.574     banghart 7431:     close (IN);
                   7432:     return (\%return_files);
1.572     banghart 7433: }
                   7434: 
                   7435: # called in portfolio select mode, to show files selected NOT in current directory
                   7436: sub files_not_in_path {
                   7437:     my ($user, $path) = @_;
                   7438:     my $filename = $user."savedfiles";
                   7439:     my @return_files;
                   7440:     my $path_part;
1.800     albertel 7441:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7442:     while (my $line = <IN>) {
1.572     banghart 7443:         #ok, I know it's clunky, but I want it to work
1.800     albertel 7444:         my @paths_and_file = split(m|/|, $line);
                   7445:         my $file_part = pop(@paths_and_file);
                   7446:         chomp($file_part);
                   7447:         my $path_part = join('/', @paths_and_file);
1.572     banghart 7448:         $path_part .= '/';
                   7449:         my $path_and_file = $path_part.$file_part;
                   7450:         if ($path_part ne $path) {
1.800     albertel 7451:             push(@return_files, ($path_and_file));
1.572     banghart 7452:         }
                   7453:     }
1.800     albertel 7454:     close(OUT);
1.574     banghart 7455:     return (@return_files);
1.572     banghart 7456: }
                   7457: 
1.745     raeburn  7458: #----------------------------------------------Get portfolio file permissions
1.629     banghart 7459: 
1.745     raeburn  7460: sub get_portfile_permissions {
                   7461:     my ($domain,$user) = @_;
1.613     albertel 7462:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7463:     my ($tmp)=keys(%current_permissions);
                   7464:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7465:     return \%current_permissions;
                   7466: }
                   7467: 
                   7468: #---------------------------------------------Get portfolio file access controls
                   7469: 
1.749     raeburn  7470: sub get_access_controls {
1.745     raeburn  7471:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 7472:     my %access;
                   7473:     my $real_file = $file;
                   7474:     $file =~ s/\.meta$//;
1.745     raeburn  7475:     if (defined($file)) {
1.749     raeburn  7476:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   7477:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 7478:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  7479:             }
                   7480:         }
1.745     raeburn  7481:     } else {
1.749     raeburn  7482:         foreach my $key (keys(%{$current_permissions})) {
                   7483:             if ($key =~ /\0accesscontrol$/) {
                   7484:                 if (defined($group)) {
                   7485:                     if ($key !~ m-^\Q$group\E/-) {
                   7486:                         next;
                   7487:                     }
                   7488:                 }
                   7489:                 my ($fullpath) = split(/\0/,$key);
                   7490:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   7491:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   7492:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   7493:                     }
                   7494:                 }
                   7495:             }
                   7496:         }
                   7497:     }
                   7498:     return %access;
                   7499: }
                   7500: 
                   7501: sub modify_access_controls {
                   7502:     my ($file_name,$changes,$domain,$user)=@_;
                   7503:     my ($outcome,$deloutcome);
                   7504:     my %store_permissions;
                   7505:     my %new_values;
                   7506:     my %new_control;
                   7507:     my %translation;
                   7508:     my @deletions = ();
                   7509:     my $now = time;
                   7510:     if (exists($$changes{'activate'})) {
                   7511:         if (ref($$changes{'activate'}) eq 'HASH') {
                   7512:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   7513:             my $numnew = scalar(@newitems);
                   7514:             for (my $i=0; $i<$numnew; $i++) {
                   7515:                 my $newkey = $newitems[$i];
                   7516:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  7517:                 if ($newkey =~ /^\d+:/) { 
                   7518:                     $newkey =~ s/^(\d+)/$newid/;
                   7519:                     $translation{$1} = $newid;
                   7520:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   7521:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   7522:                     $translation{$1} = $newid;
                   7523:                 }
1.749     raeburn  7524:                 $new_values{$file_name."\0".$newkey} = 
                   7525:                                           $$changes{'activate'}{$newitems[$i]};
                   7526:                 $new_control{$newkey} = $now;
                   7527:             }
                   7528:         }
                   7529:     }
                   7530:     my %todelete;
                   7531:     my %changed_items;
                   7532:     foreach my $action ('delete','update') {
                   7533:         if (exists($$changes{$action})) {
                   7534:             if (ref($$changes{$action}) eq 'HASH') {
                   7535:                 foreach my $key (keys(%{$$changes{$action}})) {
                   7536:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   7537:                     if ($action eq 'delete') { 
                   7538:                         $todelete{$itemnum} = 1;
                   7539:                     } else {
                   7540:                         $changed_items{$itemnum} = $key;
                   7541:                     }
                   7542:                 }
1.745     raeburn  7543:             }
                   7544:         }
1.749     raeburn  7545:     }
                   7546:     # get lock on access controls for file.
                   7547:     my $lockhash = {
                   7548:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   7549:                                                        ':'.$env{'user.domain'},
                   7550:                    }; 
                   7551:     my $tries = 0;
                   7552:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7553:    
                   7554:     while (($gotlock ne 'ok') && $tries <3) {
                   7555:         $tries ++;
                   7556:         sleep 1;
                   7557:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7558:     }
                   7559:     if ($gotlock eq 'ok') {
                   7560:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   7561:         my ($tmp)=keys(%curr_permissions);
                   7562:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   7563:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   7564:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   7565:             if (ref($curr_controls) eq 'HASH') {
                   7566:                 foreach my $control_item (keys(%{$curr_controls})) {
                   7567:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   7568:                     if (defined($todelete{$itemnum})) {
                   7569:                         push(@deletions,$file_name."\0".$control_item);
                   7570:                     } else {
                   7571:                         if (defined($changed_items{$itemnum})) {
                   7572:                             $new_control{$changed_items{$itemnum}} = $now;
                   7573:                             push(@deletions,$file_name."\0".$control_item);
                   7574:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   7575:                         } else {
                   7576:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   7577:                         }
                   7578:                     }
1.745     raeburn  7579:                 }
                   7580:             }
                   7581:         }
1.970     raeburn  7582:         my ($group);
                   7583:         if (&is_course($domain,$user)) {
                   7584:             ($group,my $file) = split(/\//,$file_name,2);
                   7585:         }
1.749     raeburn  7586:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   7587:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   7588:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   7589:         #  remove lock
                   7590:         my @del_lock = ($file_name."\0".'locked_access_records');
                   7591:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  7592:         my $sqlresult =
1.970     raeburn  7593:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  7594:                                     $group);
1.749     raeburn  7595:     } else {
                   7596:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  7597:     }
1.749     raeburn  7598:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  7599: }
                   7600: 
1.827     raeburn  7601: sub make_public_indefinitely {
                   7602:     my ($requrl) = @_;
                   7603:     my $now = time;
                   7604:     my $action = 'activate';
                   7605:     my $aclnum = 0;
                   7606:     if (&is_portfolio_url($requrl)) {
                   7607:         my (undef,$udom,$unum,$file_name,$group) =
                   7608:             &parse_portfolio_url($requrl);
                   7609:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   7610:         my %access_controls = &get_access_controls($current_perms,
                   7611:                                                    $group,$file_name);
                   7612:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   7613:             my ($num,$scope,$end,$start) = 
                   7614:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7615:             if ($scope eq 'public') {
                   7616:                 if ($start <= $now && $end == 0) {
                   7617:                     $action = 'none';
                   7618:                 } else {
                   7619:                     $action = 'update';
                   7620:                     $aclnum = $num;
                   7621:                 }
                   7622:                 last;
                   7623:             }
                   7624:         }
                   7625:         if ($action eq 'none') {
                   7626:              return 'ok';
                   7627:         } else {
                   7628:             my %changes;
                   7629:             my $newend = 0;
                   7630:             my $newstart = $now;
                   7631:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   7632:             $changes{$action}{$newkey} = {
                   7633:                 type => 'public',
                   7634:                 time => {
                   7635:                     start => $newstart,
                   7636:                     end   => $newend,
                   7637:                 },
                   7638:             };
                   7639:             my ($outcome,$deloutcome,$new_values,$translation) =
                   7640:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   7641:             return $outcome;
                   7642:         }
                   7643:     } else {
                   7644:         return 'invalid';
                   7645:     }
                   7646: }
                   7647: 
1.745     raeburn  7648: #------------------------------------------------------Get Marked as Read Only
                   7649: 
                   7650: sub get_marked_as_readonly {
                   7651:     my ($domain,$user,$what,$group) = @_;
                   7652:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 7653:     my @readonly_files;
1.629     banghart 7654:     my $cmp1=$what;
                   7655:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  7656:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7657:         if (defined($group)) {
                   7658:             if ($file_name !~ m-^\Q$group\E/-) {
                   7659:                 next;
                   7660:             }
                   7661:         }
1.561     banghart 7662:         if (ref($value) eq "ARRAY"){
                   7663:             foreach my $stored_what (@{$value}) {
1.629     banghart 7664:                 my $cmp2=$stored_what;
1.759     albertel 7665:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  7666:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  7667:                 }
1.629     banghart 7668:                 if ($cmp1 eq $cmp2) {
1.561     banghart 7669:                     push(@readonly_files, $file_name);
1.745     raeburn  7670:                     last;
1.563     banghart 7671:                 } elsif (!defined($what)) {
                   7672:                     push(@readonly_files, $file_name);
1.745     raeburn  7673:                     last;
1.561     banghart 7674:                 }
                   7675:             }
1.745     raeburn  7676:         }
1.561     banghart 7677:     }
                   7678:     return @readonly_files;
                   7679: }
1.577     banghart 7680: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 7681: 
1.577     banghart 7682: sub get_marked_as_readonly_hash {
1.745     raeburn  7683:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 7684:     my %readonly_files;
1.745     raeburn  7685:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7686:         if (defined($group)) {
                   7687:             if ($file_name !~ m-^\Q$group\E/-) {
                   7688:                 next;
                   7689:             }
                   7690:         }
1.577     banghart 7691:         if (ref($value) eq "ARRAY"){
                   7692:             foreach my $stored_what (@{$value}) {
1.745     raeburn  7693:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 7694:                     foreach my $lock_descriptor(@{$stored_what}) {
                   7695:                         if ($lock_descriptor eq 'graded') {
                   7696:                             $readonly_files{$file_name} = 'graded';
                   7697:                         } elsif ($lock_descriptor eq 'handback') {
                   7698:                             $readonly_files{$file_name} = 'handback';
                   7699:                         } else {
                   7700:                             if (!exists($readonly_files{$file_name})) {
                   7701:                                 $readonly_files{$file_name} = 'locked';
                   7702:                             }
                   7703:                         }
1.745     raeburn  7704:                     }
1.750     banghart 7705:                 } 
1.577     banghart 7706:             }
                   7707:         } 
                   7708:     }
                   7709:     return %readonly_files;
                   7710: }
1.559     banghart 7711: # ------------------------------------------------------------ Unmark as Read Only
                   7712: 
                   7713: sub unmark_as_readonly {
1.629     banghart 7714:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   7715:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  7716:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 7717:     $file_name = &declutter_portfile($file_name);
1.634     albertel 7718:     my $symb_crs = $what;
                   7719:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  7720:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 7721:     my ($tmp)=keys(%current_permissions);
                   7722:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7723:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 7724:     foreach my $file (@readonly_files) {
1.759     albertel 7725: 	my $clean_file = &declutter_portfile($file);
                   7726: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 7727: 	my $current_locks = $current_permissions{$file};
1.563     banghart 7728:         my @new_locks;
                   7729:         my @del_keys;
                   7730:         if (ref($current_locks) eq "ARRAY"){
                   7731:             foreach my $locker (@{$current_locks}) {
1.632     albertel 7732:                 my $compare=$locker;
1.749     raeburn  7733:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  7734:                     $compare=join('',@{$locker});
1.746     raeburn  7735:                     if ($compare ne $symb_crs) {
                   7736:                         push(@new_locks, $locker);
                   7737:                     }
1.563     banghart 7738:                 }
                   7739:             }
1.650     albertel 7740:             if (scalar(@new_locks) > 0) {
1.563     banghart 7741:                 $current_permissions{$file} = \@new_locks;
                   7742:             } else {
                   7743:                 push(@del_keys, $file);
1.613     albertel 7744:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 7745:                 delete($current_permissions{$file});
1.563     banghart 7746:             }
                   7747:         }
1.561     banghart 7748:     }
1.613     albertel 7749:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7750:     return;
                   7751: }
1.512     banghart 7752: 
1.17      www      7753: # ------------------------------------------------------------ Directory lister
                   7754: 
                   7755: sub dirlist {
1.955     raeburn  7756:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      7757:     $uri=~s/^\///;
                   7758:     $uri=~s/\/$//;
1.253     stredwic 7759:     my ($udom, $uname);
1.955     raeburn  7760:     if ($getuserdir) {
1.253     stredwic 7761:         $udom = $userdomain;
                   7762:         $uname = $username;
1.955     raeburn  7763:     } else {
                   7764:         (undef,$udom,$uname)=split(/\//,$uri);
                   7765:         if(defined($userdomain)) {
                   7766:             $udom = $userdomain;
                   7767:         }
                   7768:         if(defined($username)) {
                   7769:             $uname = $username;
                   7770:         }
1.253     stredwic 7771:     }
1.955     raeburn  7772:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 7773: 
1.955     raeburn  7774:     $dirRoot = $perlvar{'lonDocRoot'};
                   7775:     if (defined($getpropath)) {
                   7776:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 7777:         $dirRoot =~ s/\/$//;
1.955     raeburn  7778:     } elsif (defined($getuserdir)) {
                   7779:         my $subdir=$uname.'__';
                   7780:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   7781:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   7782:                    ."/$udom/$subdir/$uname";
                   7783:     } elsif (defined($alternateRoot)) {
                   7784:         $dirRoot = $alternateRoot;
1.751     banghart 7785:     }
1.253     stredwic 7786: 
                   7787:     if($udom) {
                   7788:         if($uname) {
1.955     raeburn  7789:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  7790:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  7791:                               .':'.&escape($uname).':'.&escape($udom),
                   7792:                               &homeserver($uname,$udom));
                   7793:             if ($listing eq 'unknown_cmd') {
                   7794:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   7795:                                   &homeserver($uname,$udom));
                   7796:             } else {
                   7797:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7798:             }
1.605     matthew  7799:             if ($listing eq 'unknown_cmd') {
1.800     albertel 7800:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   7801: 				  &homeserver($uname,$udom));
1.605     matthew  7802:                 @listing_results = split(/:/,$listing);
                   7803:             } else {
                   7804:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7805:             }
                   7806:             return @listing_results;
1.955     raeburn  7807:         } elsif(!$alternateRoot) {
1.800     albertel 7808:             my %allusers;
1.841     albertel 7809: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  7810:  	    foreach my $tryserver (keys(%servers)) {
                   7811:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   7812:                                   &escape($udom),$tryserver);
                   7813:                 if ($listing eq 'unknown_cmd') {
                   7814: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7815: 				      $udom, $tryserver);
                   7816:                 } else {
                   7817:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7818:                 }
1.841     albertel 7819: 		if ($listing eq 'unknown_cmd') {
                   7820: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7821: 				      $udom, $tryserver);
                   7822: 		    @listing_results = split(/:/,$listing);
                   7823: 		} else {
                   7824: 		    @listing_results =
                   7825: 			map { &unescape($_); } split(/:/,$listing);
                   7826: 		}
                   7827: 		if ($listing_results[0] ne 'no_such_dir' && 
                   7828: 		    $listing_results[0] ne 'empty'       &&
                   7829: 		    $listing_results[0] ne 'con_lost') {
                   7830: 		    foreach my $line (@listing_results) {
                   7831: 			my ($entry) = split(/&/,$line,2);
                   7832: 			$allusers{$entry} = 1;
                   7833: 		    }
                   7834: 		}
1.253     stredwic 7835:             }
                   7836:             my $alluserstr='';
1.800     albertel 7837:             foreach my $user (sort(keys(%allusers))) {
                   7838:                 $alluserstr.=$user.'&user:';
1.253     stredwic 7839:             }
                   7840:             $alluserstr=~s/:$//;
                   7841:             return split(/:/,$alluserstr);
                   7842:         } else {
1.800     albertel 7843:             return ('missing user name');
1.253     stredwic 7844:         }
1.955     raeburn  7845:     } elsif(!defined($getpropath)) {
1.841     albertel 7846:         my @all_domains = sort(&all_domains());
1.955     raeburn  7847:         foreach my $domain (@all_domains) {
                   7848:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   7849:         }
                   7850:         return @all_domains;
                   7851:     } else {
1.800     albertel 7852:         return ('missing domain');
1.275     stredwic 7853:     }
                   7854: }
                   7855: 
                   7856: # --------------------------------------------- GetFileTimestamp
                   7857: # This function utilizes dirlist and returns the date stamp for
                   7858: # when it was last modified.  It will also return an error of -1
                   7859: # if an error occurs
                   7860: 
                   7861: sub GetFileTimestamp {
1.955     raeburn  7862:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 7863:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   7864:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  7865:     my ($fileStat) = 
                   7866:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   7867:                                  undef,$getuserdir);
1.275     stredwic 7868:     my @stats = split('&', $fileStat);
                   7869:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  7870:         # @stats contains first the filename, then the stat output
                   7871:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 7872:     } else {
                   7873:         return -1;
1.253     stredwic 7874:     }
1.26      www      7875: }
                   7876: 
1.712     albertel 7877: sub stat_file {
                   7878:     my ($uri) = @_;
1.787     albertel 7879:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 7880: 
1.955     raeburn  7881:     my ($udom,$uname,$file);
1.712     albertel 7882:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   7883: 	($udom,$uname,$file) =
1.811     albertel 7884: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 7885: 	$file = 'userfiles/'.$file;
                   7886:     }
                   7887:     if ($uri =~ m-^/res/-) {
                   7888: 	($udom,$uname) = 
1.807     albertel 7889: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 7890: 	$file = $uri;
                   7891:     }
                   7892: 
                   7893:     if (!$udom || !$uname || !$file) {
                   7894: 	# unable to handle the uri
                   7895: 	return ();
                   7896:     }
1.956     raeburn  7897:     my $getpropath;
                   7898:     if ($file =~ /^userfiles\//) {
                   7899:         $getpropath = 1;
                   7900:     }
1.955     raeburn  7901:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 7902:     my @stats = split('&', $result);
1.721     banghart 7903:     
1.712     albertel 7904:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   7905: 	shift(@stats); #filename is first
                   7906: 	return @stats;
                   7907:     }
                   7908:     return ();
                   7909: }
                   7910: 
1.26      www      7911: # -------------------------------------------------------- Value of a Condition
                   7912: 
1.713     albertel 7913: # gets the value of a specific preevaluated condition
                   7914: #    stored in the string  $env{user.state.<cid>}
                   7915: # or looks up a condition reference in the bighash and if if hasn't
                   7916: # already been evaluated recurses into docondval to get the value of
                   7917: # the condition, then memoizing it to 
                   7918: #   $env{user.state.<cid>.<condition>}
1.40      www      7919: sub directcondval {
                   7920:     my $number=shift;
1.620     albertel 7921:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 7922: 	&Apache::lonuserstate::evalstate();
                   7923:     }
1.713     albertel 7924:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   7925: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   7926:     } elsif ($number =~ /^_/) {
                   7927: 	my $sub_condition;
                   7928: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7929: 		&GDBM_READER(),0640)) {
                   7930: 	    $sub_condition=$bighash{'conditions'.$number};
                   7931: 	    untie(%bighash);
                   7932: 	}
                   7933: 	my $value = &docondval($sub_condition);
1.949     raeburn  7934: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 7935: 	return $value;
                   7936:     }
1.620     albertel 7937:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   7938:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      7939:     } else {
                   7940:        return 2;
                   7941:     }
                   7942: }
                   7943: 
1.713     albertel 7944: # get the collection of conditions for this resource
1.26      www      7945: sub condval {
                   7946:     my $condidx=shift;
1.54      www      7947:     my $allpathcond='';
1.713     albertel 7948:     foreach my $cond (split(/\|/,$condidx)) {
                   7949: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   7950: 	    $allpathcond.=
                   7951: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   7952: 	}
1.191     harris41 7953:     }
1.54      www      7954:     $allpathcond=~s/\|$//;
1.713     albertel 7955:     return &docondval($allpathcond);
                   7956: }
                   7957: 
                   7958: #evaluates an expression of conditions
                   7959: sub docondval {
                   7960:     my ($allpathcond) = @_;
                   7961:     my $result=0;
                   7962:     if ($env{'request.course.id'}
                   7963: 	&& defined($allpathcond)) {
                   7964: 	my $operand='|';
                   7965: 	my @stack;
                   7966: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   7967: 	    if ($chunk eq '(') {
                   7968: 		push @stack,($operand,$result);
                   7969: 	    } elsif ($chunk eq ')') {
                   7970: 		my $before=pop @stack;
                   7971: 		if (pop @stack eq '&') {
                   7972: 		    $result=$result>$before?$before:$result;
                   7973: 		} else {
                   7974: 		    $result=$result>$before?$result:$before;
                   7975: 		}
                   7976: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   7977: 		$operand=$chunk;
                   7978: 	    } else {
                   7979: 		my $new=directcondval($chunk);
                   7980: 		if ($operand eq '&') {
                   7981: 		    $result=$result>$new?$new:$result;
                   7982: 		} else {
                   7983: 		    $result=$result>$new?$result:$new;
                   7984: 		}
                   7985: 	    }
                   7986: 	}
1.26      www      7987:     }
                   7988:     return $result;
1.421     albertel 7989: }
                   7990: 
                   7991: # ---------------------------------------------------- Devalidate courseresdata
                   7992: 
                   7993: sub devalidatecourseresdata {
                   7994:     my ($coursenum,$coursedomain)=@_;
                   7995:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7996:     &devalidate_cache_new('courseres',$hashid);
1.28      www      7997: }
                   7998: 
1.763     www      7999: 
1.200     www      8000: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     8001: #
                   8002: #  Parameters:
                   8003: #      $coursenum    - Number of the course.
                   8004: #      $coursedomain - Domain at which the course was created.
                   8005: #  Returns:
                   8006: #     A hash of the course parameters along (I think) with timestamps
                   8007: #     and version info.
1.877     foxr     8008: 
1.624     albertel 8009: sub get_courseresdata {
                   8010:     my ($coursenum,$coursedomain)=@_;
1.200     www      8011:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8012:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8013:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8014:     my %dumpreply;
1.417     albertel 8015:     unless (defined($cached)) {
1.624     albertel 8016: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8017: 	$result=\%dumpreply;
1.251     albertel 8018: 	my ($tmp) = keys(%dumpreply);
                   8019: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8020: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8021: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8022: 	    return $tmp;
1.416     albertel 8023: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8024: 	    $result=undef;
1.599     albertel 8025: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8026: 	}
                   8027:     }
1.624     albertel 8028:     return $result;
                   8029: }
                   8030: 
1.633     albertel 8031: sub devalidateuserresdata {
                   8032:     my ($uname,$udom)=@_;
                   8033:     my $hashid="$udom:$uname";
                   8034:     &devalidate_cache_new('userres',$hashid);
                   8035: }
                   8036: 
1.624     albertel 8037: sub get_userresdata {
                   8038:     my ($uname,$udom)=@_;
                   8039:     #most student don\'t have any data set, check if there is some data
                   8040:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   8041: 
                   8042:     my $hashid="$udom:$uname";
                   8043:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   8044:     if (!defined($cached)) {
                   8045: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   8046: 	$result=\%resourcedata;
                   8047: 	&do_cache_new('userres',$hashid,$result,600);
                   8048:     }
                   8049:     my ($tmp)=keys(%$result);
                   8050:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8051: 	return $result;
                   8052:     }
                   8053:     #error 2 occurs when the .db doesn't exist
                   8054:     if ($tmp!~/error: 2 /) {
1.672     albertel 8055: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8056: 		 " Trying to get resource data for ".
                   8057: 		 $uname." at ".$udom.": ".
                   8058: 		 $tmp."</font>");
                   8059:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8060: 	#&EXT_cache_set($udom,$uname);
                   8061: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8062: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8063:     }
                   8064:     return $tmp;
                   8065: }
1.879     foxr     8066: #----------------------------------------------- resdata - return resource data
                   8067: #  Purpose:
                   8068: #    Return resource data for either users or for a course.
                   8069: #  Parameters:
                   8070: #     $name      - Course/user name.
                   8071: #     $domain    - Name of the domain the user/course is registered on.
                   8072: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8073: #     @which     - Array of names of resources desired.
                   8074: #  Returns:
                   8075: #     The value of the first reasource in @which that is found in the
                   8076: #     resource hash.
                   8077: #  Exceptional Conditions:
                   8078: #     If the $type passed in is not valid (not the string 'course' or 
                   8079: #     'user', an undefined  reference is returned.
                   8080: #     If none of the resources are found, an undef is returned
1.624     albertel 8081: sub resdata {
                   8082:     my ($name,$domain,$type,@which)=@_;
                   8083:     my $result;
                   8084:     if ($type eq 'course') {
                   8085: 	$result=&get_courseresdata($name,$domain);
                   8086:     } elsif ($type eq 'user') {
                   8087: 	$result=&get_userresdata($name,$domain);
                   8088:     }
                   8089:     if (!ref($result)) { return $result; }    
1.251     albertel 8090:     foreach my $item (@which) {
1.927     albertel 8091: 	if (defined($result->{$item->[0]})) {
                   8092: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8093: 	}
1.250     albertel 8094:     }
1.291     albertel 8095:     return undef;
1.200     www      8096: }
                   8097: 
1.379     matthew  8098: #
                   8099: # EXT resource caching routines
                   8100: #
                   8101: 
                   8102: sub clear_EXT_cache_status {
1.383     albertel 8103:     &delenv('cache.EXT.');
1.379     matthew  8104: }
                   8105: 
                   8106: sub EXT_cache_status {
                   8107:     my ($target_domain,$target_user) = @_;
1.383     albertel 8108:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8109:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8110:         # We know already the user has no data
                   8111:         return 1;
                   8112:     } else {
                   8113:         return 0;
                   8114:     }
                   8115: }
                   8116: 
                   8117: sub EXT_cache_set {
                   8118:     my ($target_domain,$target_user) = @_;
1.383     albertel 8119:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8120:     #&appenv({$cachename => time});
1.379     matthew  8121: }
                   8122: 
1.28      www      8123: # --------------------------------------------------------- Value of a Variable
1.58      www      8124: sub EXT {
1.715     albertel 8125: 
1.395     albertel 8126:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8127:     unless ($varname) { return ''; }
1.218     albertel 8128:     #get real user name/domain, courseid and symb
                   8129:     my $courseid;
1.359     albertel 8130:     my $publicuser;
1.427     www      8131:     if ($symbparm) {
                   8132: 	$symbparm=&get_symb_from_alias($symbparm);
                   8133:     }
1.218     albertel 8134:     if (!($uname && $udom)) {
1.790     albertel 8135:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8136:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8137:     } else {
1.620     albertel 8138: 	$courseid=$env{'request.course.id'};
1.218     albertel 8139:     }
1.48      www      8140:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8141:     my $rest;
1.320     albertel 8142:     if (defined($therest[0])) {
1.48      www      8143:        $rest=join('.',@therest);
                   8144:     } else {
                   8145:        $rest='';
                   8146:     }
1.320     albertel 8147: 
1.57      www      8148:     my $qualifierrest=$qualifier;
                   8149:     if ($rest) { $qualifierrest.='.'.$rest; }
                   8150:     my $spacequalifierrest=$space;
                   8151:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      8152:     if ($realm eq 'user') {
1.48      www      8153: # --------------------------------------------------------------- user.resource
                   8154: 	if ($space eq 'resource') {
1.651     albertel 8155: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   8156: 		  || defined($Apache::lonhomework::parsing_a_task))
                   8157: 		 &&
1.744     albertel 8158: 		 ($symbparm eq &symbread()) ) {	
                   8159: 		# if we are in the middle of processing the resource the
                   8160: 		# get the value we are planning on committing
                   8161:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   8162:                     return $Apache::lonhomework::results{$qualifierrest};
                   8163:                 } else {
                   8164:                     return $Apache::lonhomework::history{$qualifierrest};
                   8165:                 }
1.335     albertel 8166: 	    } else {
1.359     albertel 8167: 		my %restored;
1.620     albertel 8168: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 8169: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   8170: 		} else {
                   8171: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   8172: 		}
1.335     albertel 8173: 		return $restored{$qualifierrest};
                   8174: 	    }
1.48      www      8175: # ----------------------------------------------------------------- user.access
                   8176:         } elsif ($space eq 'access') {
1.218     albertel 8177: 	    # FIXME - not supporting calls for a specific user
1.48      www      8178:             return &allowed($qualifier,$rest);
                   8179: # ------------------------------------------ user.preferences, user.environment
                   8180:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 8181: 	    if (($uname eq $env{'user.name'}) &&
                   8182: 		($udom eq $env{'user.domain'})) {
                   8183: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 8184: 	    } else {
1.359     albertel 8185: 		my %returnhash;
                   8186: 		if (!$publicuser) {
                   8187: 		    %returnhash=&userenvironment($udom,$uname,
                   8188: 						 $qualifierrest);
                   8189: 		}
1.218     albertel 8190: 		return $returnhash{$qualifierrest};
                   8191: 	    }
1.48      www      8192: # ----------------------------------------------------------------- user.course
                   8193:         } elsif ($space eq 'course') {
1.218     albertel 8194: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8195:             return $env{join('.',('request.course',$qualifier))};
1.48      www      8196: # ------------------------------------------------------------------- user.role
                   8197:         } elsif ($space eq 'role') {
1.218     albertel 8198: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8199:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      8200:             if ($qualifier eq 'value') {
                   8201: 		return $role;
                   8202:             } elsif ($qualifier eq 'extent') {
                   8203:                 return $where;
                   8204:             }
                   8205: # ----------------------------------------------------------------- user.domain
                   8206:         } elsif ($space eq 'domain') {
1.218     albertel 8207:             return $udom;
1.48      www      8208: # ------------------------------------------------------------------- user.name
                   8209:         } elsif ($space eq 'name') {
1.218     albertel 8210:             return $uname;
1.48      www      8211: # ---------------------------------------------------- Any other user namespace
1.29      www      8212:         } else {
1.359     albertel 8213: 	    my %reply;
                   8214: 	    if (!$publicuser) {
                   8215: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   8216: 	    }
                   8217: 	    return $reply{$qualifierrest};
1.48      www      8218:         }
1.236     www      8219:     } elsif ($realm eq 'query') {
                   8220: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 8221:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   8222: 						[$spacequalifierrest]);
1.620     albertel 8223: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      8224:    } elsif ($realm eq 'request') {
1.48      www      8225: # ------------------------------------------------------------- request.browser
                   8226:         if ($space eq 'browser') {
1.430     www      8227: 	    if ($qualifier eq 'textremote') {
1.676     albertel 8228: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      8229: 		    return 1;
                   8230: 		} else {
                   8231: 		    return 0;
                   8232: 		}
                   8233: 	    } else {
1.620     albertel 8234: 		return $env{'browser.'.$qualifier};
1.430     www      8235: 	    }
1.57      www      8236: # ------------------------------------------------------------ request.filename
                   8237:         } else {
1.620     albertel 8238:             return $env{'request.'.$spacequalifierrest};
1.29      www      8239:         }
1.28      www      8240:     } elsif ($realm eq 'course') {
1.48      www      8241: # ---------------------------------------------------------- course.description
1.620     albertel 8242:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      8243:     } elsif ($realm eq 'resource') {
1.165     www      8244: 
1.620     albertel 8245: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 8246: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   8247: 	}
1.693     albertel 8248: 
                   8249: 	if ($space eq 'title') {
                   8250: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   8251: 	    return &gettitle($symbparm);
                   8252: 	}
                   8253: 	
                   8254: 	if ($space eq 'map') {
                   8255: 	    my ($map) = &decode_symb($symbparm);
                   8256: 	    return &symbread($map);
                   8257: 	}
1.905     albertel 8258: 	if ($space eq 'filename') {
                   8259: 	    if ($symbparm) {
                   8260: 		return &clutter((&decode_symb($symbparm))[2]);
                   8261: 	    }
                   8262: 	    return &hreflocation('',$env{'request.filename'});
                   8263: 	}
1.693     albertel 8264: 
                   8265: 	my ($section, $group, @groups);
1.593     albertel 8266: 	my ($courselevelm,$courselevel);
1.539     albertel 8267: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8268: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      8269: 
1.218     albertel 8270: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      8271: 
1.60      www      8272: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 8273: 	    my $symbp=$symbparm;
1.735     albertel 8274: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 8275: 
                   8276: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   8277: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   8278: 
1.620     albertel 8279: 	    if (($env{'user.name'} eq $uname) &&
                   8280: 		($env{'user.domain'} eq $udom)) {
                   8281: 		$section=$env{'request.course.sec'};
1.733     raeburn  8282:                 @groups = split(/:/,$env{'request.course.groups'});  
                   8283:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 8284: 	    } else {
1.539     albertel 8285: 		if (! defined($usection)) {
1.551     albertel 8286: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 8287: 		} else {
                   8288: 		    $section = $usection;
                   8289: 		}
1.733     raeburn  8290:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 8291: 	    }
                   8292: 
                   8293: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   8294: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   8295: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   8296: 
1.593     albertel 8297: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 8298: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 8299: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      8300: 
1.60      www      8301: # ----------------------------------------------------------- first, check user
1.624     albertel 8302: 
                   8303: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 8304: 				       ([$courselevelr,'resource'],
                   8305: 					[$courselevelm,'map'     ],
                   8306: 					[$courselevel, 'course'  ]));
1.931     albertel 8307: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      8308: 
1.594     albertel 8309: # ------------------------------------------------ second, check some of course
1.684     raeburn  8310:             my $coursereply;
1.691     raeburn  8311:             if (@groups > 0) {
                   8312:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   8313:                                        $mapparm,$spacequalifierrest);
1.927     albertel 8314:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  8315:             }
1.96      www      8316: 
1.684     raeburn  8317: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 8318: 				  $env{'course.'.$courseid.'.domain'},
                   8319: 				  'course',
                   8320: 				  ([$seclevelr,   'resource'],
                   8321: 				   [$seclevelm,   'map'     ],
                   8322: 				   [$seclevel,    'course'  ],
                   8323: 				   [$courselevelr,'resource']));
                   8324: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      8325: 
1.60      www      8326: # ------------------------------------------------------ third, check map parms
1.218     albertel 8327: 	    my %parmhash=();
                   8328: 	    my $thisparm='';
                   8329: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 8330: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 8331: 		    &GDBM_READER(),0640)) {
1.218     albertel 8332: 		$thisparm=$parmhash{$symbparm};
                   8333: 		untie(%parmhash);
                   8334: 	    }
1.927     albertel 8335: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 8336: 	}
1.594     albertel 8337: # ------------------------------------------ fourth, look in resource metadata
1.71      www      8338: 
1.218     albertel 8339: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 8340: 	my $filename;
                   8341: 	if (!$symbparm) { $symbparm=&symbread(); }
                   8342: 	if ($symbparm) {
1.409     www      8343: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 8344: 	} else {
1.620     albertel 8345: 	    $filename=$env{'request.filename'};
1.282     albertel 8346: 	}
                   8347: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 8348: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 8349: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 8350: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      8351: 
1.927     albertel 8352: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 8353: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8354: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 8355: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   8356: 				     $env{'course.'.$courseid.'.domain'},
                   8357: 				     'course',
1.927     albertel 8358: 				     ([$courselevelm,'map'   ],
                   8359: 				      [$courselevel, 'course']));
                   8360: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 8361: 	}
1.145     www      8362: # ------------------------------------------------------------------ Cascade up
1.218     albertel 8363: 	unless ($space eq '0') {
1.336     albertel 8364: 	    my @parts=split(/_/,$space);
                   8365: 	    my $id=pop(@parts);
                   8366: 	    my $part=join('_',@parts);
                   8367: 	    if ($part eq '') { $part='0'; }
1.927     albertel 8368: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 8369: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  8370: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 8371: 	}
1.395     albertel 8372: 	if ($recurse) { return undef; }
                   8373: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 8374: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      8375: # ---------------------------------------------------- Any other user namespace
                   8376:     } elsif ($realm eq 'environment') {
                   8377: # ----------------------------------------------------------------- environment
1.620     albertel 8378: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   8379: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 8380: 	} else {
1.770     albertel 8381: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   8382: 		return '';
                   8383: 	    }
1.219     albertel 8384: 	    my %returnhash=&userenvironment($udom,$uname,
                   8385: 					    $spacequalifierrest);
                   8386: 	    return $returnhash{$spacequalifierrest};
                   8387: 	}
1.28      www      8388:     } elsif ($realm eq 'system') {
1.48      www      8389: # ----------------------------------------------------------------- system.time
                   8390: 	if ($space eq 'time') {
                   8391: 	    return time;
                   8392:         }
1.696     albertel 8393:     } elsif ($realm eq 'server') {
                   8394: # ----------------------------------------------------------------- system.time
                   8395: 	if ($space eq 'name') {
                   8396: 	    return $ENV{'SERVER_NAME'};
                   8397:         }
1.28      www      8398:     }
1.48      www      8399:     return '';
1.61      www      8400: }
                   8401: 
1.927     albertel 8402: sub get_reply {
                   8403:     my ($reply_value) = @_;
1.940     raeburn  8404:     if (ref($reply_value) eq 'ARRAY') {
                   8405:         if (wantarray) {
                   8406: 	    return @$reply_value;
                   8407:         }
                   8408:         return $reply_value->[0];
                   8409:     } else {
                   8410:         return $reply_value;
1.927     albertel 8411:     }
                   8412: }
                   8413: 
1.691     raeburn  8414: sub check_group_parms {
                   8415:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   8416:     my @groupitems = ();
                   8417:     my $resultitem;
1.927     albertel 8418:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  8419:     foreach my $group (@{$groups}) {
                   8420:         foreach my $level (@levels) {
1.927     albertel 8421:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   8422:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  8423:         }
                   8424:     }
                   8425:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   8426:                             $env{'course.'.$courseid.'.domain'},
                   8427:                                      'course',@groupitems);
                   8428:     return $coursereply;
                   8429: }
                   8430: 
                   8431: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  8432:     my ($courseid,@groups) = @_;
                   8433:     @groups = sort(@groups);
1.691     raeburn  8434:     return @groups;
                   8435: }
                   8436: 
1.395     albertel 8437: sub packages_tab_default {
                   8438:     my ($uri,$varname)=@_;
                   8439:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 8440: 
                   8441:     my (@extension,@specifics,$do_default);
                   8442:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 8443: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 8444: 	if ($pack_type eq 'default') {
                   8445: 	    $do_default=1;
                   8446: 	} elsif ($pack_type eq 'extension') {
                   8447: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 8448: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 8449: 	    # only look at packages defaults for packages that this id is
1.738     albertel 8450: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   8451: 	}
                   8452:     }
                   8453:     # first look for a package that matches the requested part id
                   8454:     foreach my $package (@specifics) {
                   8455: 	my (undef,$pack_type,$pack_part)=@{$package};
                   8456: 	next if ($pack_part ne $part);
                   8457: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8458: 	    return $packagetab{"$pack_type&$name&default"};
                   8459: 	}
                   8460:     }
                   8461:     # look for any possible matching non extension_ package
                   8462:     foreach my $package (@specifics) {
                   8463: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 8464: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8465: 	    return $packagetab{"$pack_type&$name&default"};
                   8466: 	}
1.585     albertel 8467: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 8468: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   8469: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 8470: 	}
                   8471:     }
1.738     albertel 8472:     # look for any posible extension_ match
                   8473:     foreach my $package (@extension) {
                   8474: 	my ($package,$pack_type)=@{$package};
                   8475: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8476: 	    return $packagetab{"$pack_type&$name&default"};
                   8477: 	}
                   8478: 	if (defined($packagetab{$package."&$name&default"})) {
                   8479: 	    return $packagetab{$package."&$name&default"};
                   8480: 	}
                   8481:     }
                   8482:     # look for a global default setting
                   8483:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   8484: 	return $packagetab{"default&$name&default"};
                   8485:     }
1.395     albertel 8486:     return undef;
                   8487: }
                   8488: 
1.334     albertel 8489: sub add_prefix_and_part {
                   8490:     my ($prefix,$part)=@_;
                   8491:     my $keyroot;
                   8492:     if (defined($prefix) && $prefix !~ /^__/) {
                   8493: 	# prefix that has a part already
                   8494: 	$keyroot=$prefix;
                   8495:     } elsif (defined($prefix)) {
                   8496: 	# prefix that is missing a part
                   8497: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   8498:     } else {
                   8499: 	# no prefix at all
                   8500: 	if (defined($part)) { $keyroot='_'.$part; }
                   8501:     }
                   8502:     return $keyroot;
                   8503: }
                   8504: 
1.71      www      8505: # ---------------------------------------------------------------- Get metadata
                   8506: 
1.599     albertel 8507: my %metaentry;
1.71      www      8508: sub metadata {
1.176     www      8509:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      8510:     $uri=&declutter($uri);
1.288     albertel 8511:     # if it is a non metadata possible uri return quickly
1.529     albertel 8512:     if (($uri eq '') || 
                   8513: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 8514: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 8515:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   8516: 	return undef;
                   8517:     }
                   8518:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   8519: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 8520: 	return undef;
1.288     albertel 8521:     }
1.73      www      8522:     my $filename=$uri;
                   8523:     $uri=~s/\.meta$//;
1.172     www      8524: #
                   8525: # Is the metadata already cached?
1.177     www      8526: # Look at timestamp of caching
1.172     www      8527: # Everything is cached by the main uri, libraries are never directly cached
                   8528: #
1.428     albertel 8529:     if (!defined($liburi)) {
1.599     albertel 8530: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 8531: 	if (defined($cached)) { return $result->{':'.$what}; }
                   8532:     }
                   8533:     {
1.172     www      8534: #
                   8535: # Is this a recursive call for a library?
                   8536: #
1.599     albertel 8537: #	if (! exists($metacache{$uri})) {
                   8538: #	    $metacache{$uri}={};
                   8539: #	}
1.924     albertel 8540: 	my $cachetime = 60*60;
1.171     www      8541:         if ($liburi) {
                   8542: 	    $liburi=&declutter($liburi);
                   8543:             $filename=$liburi;
1.401     bowersj2 8544:         } else {
1.599     albertel 8545: 	    &devalidate_cache_new('meta',$uri);
                   8546: 	    undef(%metaentry);
1.401     bowersj2 8547: 	}
1.140     www      8548:         my %metathesekeys=();
1.73      www      8549:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 8550: 	my $metastring;
1.924     albertel 8551: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 8552: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 8553: 	    $metastring = 
1.929     albertel 8554: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 8555: 					  ('grade_target' => 'meta'));
                   8556: 	    $cachetime = 1; # only want this cached in the child not long term
                   8557: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 8558: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 8559: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 8560: 	    $metastring=&getfile($file);
1.489     albertel 8561: 	}
1.208     albertel 8562:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      8563:         my $token;
1.140     www      8564:         undef %metathesekeys;
1.71      www      8565:         while ($token=$parser->get_token) {
1.339     albertel 8566: 	    if ($token->[0] eq 'S') {
                   8567: 		if (defined($token->[2]->{'package'})) {
1.172     www      8568: #
                   8569: # This is a package - get package info
                   8570: #
1.339     albertel 8571: 		    my $package=$token->[2]->{'package'};
                   8572: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8573: 		    if (defined($token->[2]->{'id'})) { 
                   8574: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   8575: 		    }
1.599     albertel 8576: 		    if ($metaentry{':packages'}) {
                   8577: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 8578: 		    } else {
1.599     albertel 8579: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 8580: 		    }
1.736     albertel 8581: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 8582: 			my $part=$keyroot;
                   8583: 			$part=~s/^\_//;
1.736     albertel 8584: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   8585: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   8586: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 8587: 			    # ignore package.tab specified default values
                   8588:                             # here &package_tab_default() will fetch those
                   8589: 			    if ($subp eq 'default') { next; }
1.736     albertel 8590: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 8591: 			    my $unikey;
                   8592: 			    if ($pack =~ /_0$/) {
                   8593: 				$unikey='parameter_0_'.$name;
                   8594: 				$part=0;
                   8595: 			    } else {
                   8596: 				$unikey='parameter'.$keyroot.'_'.$name;
                   8597: 			    }
1.339     albertel 8598: 			    if ($subp eq 'display') {
                   8599: 				$value.=' [Part: '.$part.']';
                   8600: 			    }
1.599     albertel 8601: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 8602: 			    $metathesekeys{$unikey}=1;
1.599     albertel 8603: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8604: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 8605: 			    }
1.599     albertel 8606: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   8607: 				$metaentry{':'.$unikey}=
                   8608: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 8609: 			    }
1.339     albertel 8610: 			}
                   8611: 		    }
                   8612: 		} else {
1.172     www      8613: #
                   8614: # This is not a package - some other kind of start tag
1.339     albertel 8615: #
                   8616: 		    my $entry=$token->[1];
                   8617: 		    my $unikey;
                   8618: 		    if ($entry eq 'import') {
                   8619: 			$unikey='';
                   8620: 		    } else {
                   8621: 			$unikey=$entry;
                   8622: 		    }
                   8623: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8624: 
                   8625: 		    if (defined($token->[2]->{'id'})) { 
                   8626: 			$unikey.='_'.$token->[2]->{'id'}; 
                   8627: 		    }
1.175     www      8628: 
1.339     albertel 8629: 		    if ($entry eq 'import') {
1.175     www      8630: #
                   8631: # Importing a library here
1.339     albertel 8632: #
                   8633: 			if ($depthcount<20) {
                   8634: 			    my $location=$parser->get_text('/import');
                   8635: 			    my $dir=$filename;
                   8636: 			    $dir=~s|[^/]*$||;
                   8637: 			    $location=&filelocation($dir,$location);
1.736     albertel 8638: 			    my $metadata = 
                   8639: 				&metadata($uri,'keys', $location,$unikey,
                   8640: 					  $depthcount+1);
                   8641: 			    foreach my $meta (split(',',$metadata)) {
                   8642: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   8643: 				$metathesekeys{$meta}=1;
1.339     albertel 8644: 			    }
                   8645: 			}
                   8646: 		    } else { 
                   8647: 			if (defined($token->[2]->{'name'})) { 
                   8648: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   8649: 			}
                   8650: 			$metathesekeys{$unikey}=1;
1.736     albertel 8651: 			foreach my $param (@{$token->[3]}) {
                   8652: 			    $metaentry{':'.$unikey.'.'.$param} =
                   8653: 				$token->[2]->{$param};
1.339     albertel 8654: 			}
                   8655: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 8656: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 8657: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   8658: 		 # only ws inside the tag, and not in default, so use default
                   8659: 		 # as value
1.599     albertel 8660: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 8661: 			} elsif ( $internaltext =~ /\S/ ) {
                   8662: 		  # something interesting inside the tag
                   8663: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 8664: 			} else {
1.908     albertel 8665: 		  # no interesting values, don't set a default
1.339     albertel 8666: 			}
1.172     www      8667: # end of not-a-package not-a-library import
1.339     albertel 8668: 		    }
1.172     www      8669: # end of not-a-package start tag
1.339     albertel 8670: 		}
1.172     www      8671: # the next is the end of "start tag"
1.339     albertel 8672: 	    }
                   8673: 	}
1.483     albertel 8674: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 8675: 	$extension = lc($extension);
                   8676: 	if ($extension eq 'htm') { $extension='html'; }
                   8677: 
1.737     albertel 8678: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 8679: 	    #no specific packages #how's our extension
                   8680: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 8681: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 8682: 					 \%metathesekeys);
                   8683: 	}
1.883     albertel 8684: 
                   8685: 	if (!exists($metaentry{':packages'})
                   8686: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 8687: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 8688: 		#no specific packages well let's get default then
                   8689: 		if ($key!~/^default&/) { next; }
1.488     albertel 8690: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 8691: 					     \%metathesekeys);
                   8692: 	    }
                   8693: 	}
1.338     www      8694: # are there custom rights to evaluate
1.599     albertel 8695: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 8696: 
1.338     www      8697:     #
                   8698:     # Importing a rights file here
1.339     albertel 8699:     #
                   8700: 	    unless ($depthcount) {
1.599     albertel 8701: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 8702: 		my $dir=$filename;
                   8703: 		$dir=~s|[^/]*$||;
                   8704: 		$location=&filelocation($dir,$location);
1.736     albertel 8705: 		my $rights_metadata =
                   8706: 		    &metadata($uri,'keys',$location,'_rights',
                   8707: 			      $depthcount+1);
                   8708: 		foreach my $rights (split(',',$rights_metadata)) {
                   8709: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   8710: 		    $metathesekeys{$rights}=1;
1.339     albertel 8711: 		}
                   8712: 	    }
                   8713: 	}
1.737     albertel 8714: 	# uniqifiy package listing
                   8715: 	my %seen;
                   8716: 	my @uniq_packages =
                   8717: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   8718: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   8719: 
                   8720: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 8721: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   8722: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 8723: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      8724: # this is the end of "was not already recently cached
1.71      www      8725:     }
1.599     albertel 8726:     return $metaentry{':'.$what};
1.261     albertel 8727: }
                   8728: 
1.488     albertel 8729: sub metadata_create_package_def {
1.483     albertel 8730:     my ($uri,$key,$package,$metathesekeys)=@_;
                   8731:     my ($pack,$name,$subp)=split(/\&/,$key);
                   8732:     if ($subp eq 'default') { next; }
                   8733:     
1.599     albertel 8734:     if (defined($metaentry{':packages'})) {
                   8735: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 8736:     } else {
1.599     albertel 8737: 	$metaentry{':packages'}=$package;
1.483     albertel 8738:     }
                   8739:     my $value=$packagetab{$key};
                   8740:     my $unikey;
                   8741:     $unikey='parameter_0_'.$name;
1.599     albertel 8742:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 8743:     $$metathesekeys{$unikey}=1;
1.599     albertel 8744:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8745: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 8746:     }
1.599     albertel 8747:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   8748: 	$metaentry{':'.$unikey}=
                   8749: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 8750:     }
                   8751: }
                   8752: 
1.261     albertel 8753: sub metadata_generate_part0 {
                   8754:     my ($metadata,$metacache,$uri) = @_;
                   8755:     my %allnames;
1.737     albertel 8756:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 8757: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 8758: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   8759: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 8760: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 8761: 	    $allnames{$name}=$part;
                   8762: 	  }
                   8763: 	}
                   8764:     }
                   8765:     foreach my $name (keys(%allnames)) {
                   8766:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 8767:       my $key=":parameter_0_$name";
1.261     albertel 8768:       $$metacache{"$key.part"}='0';
                   8769:       $$metacache{"$key.name"}=$name;
1.428     albertel 8770:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 8771: 					   $allnames{$name}.'_'.$name.
                   8772: 					   '.type'};
1.428     albertel 8773:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 8774: 			     '.display'};
1.644     www      8775:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 8776:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 8777:       $$metacache{"$key.display"}=$olddis;
                   8778:     }
1.71      www      8779: }
                   8780: 
1.764     albertel 8781: # ------------------------------------------------------ Devalidate title cache
                   8782: 
                   8783: sub devalidate_title_cache {
                   8784:     my ($url)=@_;
                   8785:     if (!$env{'request.course.id'}) { return; }
                   8786:     my $symb=&symbread($url);
                   8787:     if (!$symb) { return; }
                   8788:     my $key=$env{'request.course.id'}."\0".$symb;
                   8789:     &devalidate_cache_new('title',$key);
                   8790: }
                   8791: 
1.1014    droeschl 8792: # ------------------------------------------------- Get the title of a course
                   8793: 
                   8794: sub current_course_title {
                   8795:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   8796: }
1.301     www      8797: # ------------------------------------------------- Get the title of a resource
                   8798: 
                   8799: sub gettitle {
                   8800:     my $urlsymb=shift;
                   8801:     my $symb=&symbread($urlsymb);
1.534     albertel 8802:     if ($symb) {
1.620     albertel 8803: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 8804: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 8805: 	if (defined($cached)) { 
                   8806: 	    return $result;
                   8807: 	}
1.534     albertel 8808: 	my ($map,$resid,$url)=&decode_symb($symb);
                   8809: 	my $title='';
1.907     albertel 8810: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   8811: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   8812: 	} else {
                   8813: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8814: 		    &GDBM_READER(),0640)) {
                   8815: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   8816: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   8817: 		untie(%bighash);
                   8818: 	    }
1.534     albertel 8819: 	}
                   8820: 	$title=~s/\&colon\;/\:/gs;
                   8821: 	if ($title) {
1.599     albertel 8822: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 8823: 	}
                   8824: 	$urlsymb=$url;
                   8825:     }
                   8826:     my $title=&metadata($urlsymb,'title');
                   8827:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   8828:     return $title;
1.301     www      8829: }
1.613     albertel 8830: 
1.614     albertel 8831: sub get_slot {
                   8832:     my ($which,$cnum,$cdom)=@_;
                   8833:     if (!$cnum || !$cdom) {
1.790     albertel 8834: 	(undef,my $courseid)=&whichuser();
1.620     albertel 8835: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   8836: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 8837:     }
1.703     albertel 8838:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   8839:     my %slotinfo;
                   8840:     if (exists($remembered{$key})) {
                   8841: 	$slotinfo{$which} = $remembered{$key};
                   8842:     } else {
                   8843: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   8844: 	&Apache::lonhomework::showhash(%slotinfo);
                   8845: 	my ($tmp)=keys(%slotinfo);
                   8846: 	if ($tmp=~/^error:/) { return (); }
                   8847: 	$remembered{$key} = $slotinfo{$which};
                   8848:     }
1.616     albertel 8849:     if (ref($slotinfo{$which}) eq 'HASH') {
                   8850: 	return %{$slotinfo{$which}};
                   8851:     }
                   8852:     return $slotinfo{$which};
1.614     albertel 8853: }
1.31      www      8854: # ------------------------------------------------- Update symbolic store links
                   8855: 
                   8856: sub symblist {
                   8857:     my ($mapname,%newhash)=@_;
1.438     www      8858:     $mapname=&deversion(&declutter($mapname));
1.31      www      8859:     my %hash;
1.620     albertel 8860:     if (($env{'request.course.fn'}) && (%newhash)) {
                   8861:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8862:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  8863: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 8864: 		next if ($url eq 'last_known'
                   8865: 			 && $env{'form.no_update_last_known'});
                   8866: 		$hash{declutter($url)}=&encode_symb($mapname,
                   8867: 						    $newhash{$url}->[1],
                   8868: 						    $newhash{$url}->[0]);
1.191     harris41 8869:             }
1.31      www      8870:             if (untie(%hash)) {
                   8871: 		return 'ok';
                   8872:             }
                   8873:         }
                   8874:     }
                   8875:     return 'error';
1.212     www      8876: }
                   8877: 
                   8878: # --------------------------------------------------------------- Verify a symb
                   8879: 
                   8880: sub symbverify {
1.510     www      8881:     my ($symb,$thisurl)=@_;
                   8882:     my $thisfn=$thisurl;
1.439     www      8883:     $thisfn=&declutter($thisfn);
1.215     www      8884: # direct jump to resource in page or to a sequence - will construct own symbs
                   8885:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   8886: # check URL part
1.409     www      8887:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      8888: 
1.431     www      8889:     unless ($url eq $thisfn) { return 0; }
1.213     www      8890: 
1.216     www      8891:     $symb=&symbclean($symb);
1.510     www      8892:     $thisurl=&deversion($thisurl);
1.439     www      8893:     $thisfn=&deversion($thisfn);
1.213     www      8894: 
                   8895:     my %bighash;
                   8896:     my $okay=0;
1.431     www      8897: 
1.620     albertel 8898:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8899:                             &GDBM_READER(),0640)) {
1.1032    raeburn  8900:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   8901:             $thisurl =~ s/\?.+$//;
                   8902:         }
1.510     www      8903:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      8904:         unless ($ids) { 
1.510     www      8905:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      8906:         }
                   8907:         if ($ids) {
                   8908: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 8909: 	    foreach my $id (split(/\,/,$ids)) {
                   8910: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  8911:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   8912:                    $symb =~ s/\?.+$//;
                   8913:                }
1.216     www      8914:                if (
                   8915:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   8916:    eq $symb) { 
1.620     albertel 8917: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 8918: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 8919: 		       $okay=1; 
                   8920: 		   }
                   8921: 	       }
1.216     www      8922: 	   }
                   8923:         }
1.213     www      8924: 	untie(%bighash);
                   8925:     }
                   8926:     return $okay;
1.31      www      8927: }
                   8928: 
1.210     www      8929: # --------------------------------------------------------------- Clean-up symb
                   8930: 
                   8931: sub symbclean {
                   8932:     my $symb=shift;
1.568     albertel 8933:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      8934: # remove version from map
                   8935:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      8936: 
1.210     www      8937: # remove version from URL
                   8938:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      8939: 
1.507     www      8940: # remove wrapper
                   8941: 
1.510     www      8942:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 8943:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      8944:     return $symb;
1.409     www      8945: }
                   8946: 
                   8947: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 8948: 
                   8949: sub encode_symb {
                   8950:     my ($map,$resid,$url)=@_;
                   8951:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   8952: }
1.409     www      8953: 
                   8954: sub decode_symb {
1.568     albertel 8955:     my $symb=shift;
                   8956:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   8957:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      8958:     return (&fixversion($map),$resid,&fixversion($url));
                   8959: }
                   8960: 
                   8961: sub fixversion {
                   8962:     my $fn=shift;
1.609     banghart 8963:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      8964:     my %bighash;
                   8965:     my $uri=&clutter($fn);
1.620     albertel 8966:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      8967: # is this cached?
1.599     albertel 8968:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      8969:     if (defined($cached)) { return $result; }
                   8970: # unfortunately not cached, or expired
1.620     albertel 8971:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      8972: 	    &GDBM_READER(),0640)) {
                   8973:  	if ($bighash{'version_'.$uri}) {
                   8974:  	    my $version=$bighash{'version_'.$uri};
1.444     www      8975:  	    unless (($version eq 'mostrecent') || 
                   8976: 		    ($version==&getversion($uri))) {
1.440     www      8977:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   8978:  	    }
                   8979:  	}
                   8980:  	untie %bighash;
1.413     www      8981:     }
1.599     albertel 8982:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      8983: }
                   8984: 
                   8985: sub deversion {
                   8986:     my $url=shift;
                   8987:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   8988:     return $url;
1.210     www      8989: }
                   8990: 
1.31      www      8991: # ------------------------------------------------------ Return symb list entry
                   8992: 
                   8993: sub symbread {
1.249     www      8994:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 8995:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 8996:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      8997: # no filename provided? try from environment
1.44      www      8998:     unless ($thisfn) {
1.620     albertel 8999:         if ($env{'request.symb'}) {
                   9000: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 9001: 	}
1.620     albertel 9002: 	$thisfn=$env{'request.filename'};
1.44      www      9003:     }
1.569     albertel 9004:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      9005: # is that filename actually a symb? Verify, clean, and return
                   9006:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 9007: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 9008: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 9009: 	}
1.242     www      9010:     }
1.44      www      9011:     $thisfn=declutter($thisfn);
1.31      www      9012:     my %hash;
1.37      www      9013:     my %bighash;
                   9014:     my $syval='';
1.620     albertel 9015:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  9016:         my $targetfn = $thisfn;
1.609     banghart 9017:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  9018:             $targetfn = 'adm/wrapper/'.$thisfn;
                   9019:         }
1.687     albertel 9020: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   9021: 	    $targetfn=$1;
                   9022: 	}
1.620     albertel 9023:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9024:                       &GDBM_READER(),0640)) {
1.481     raeburn  9025: 	    $syval=$hash{$targetfn};
1.37      www      9026:             untie(%hash);
                   9027:         }
                   9028: # ---------------------------------------------------------- There was an entry
                   9029:         if ($syval) {
1.601     albertel 9030: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 9031: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  9032: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9033: 		    #return $env{$cache_str}='';
1.601     albertel 9034: 		#}    
                   9035: 		#$syval.=$1;
                   9036: 	    #}
1.37      www      9037:         } else {
                   9038: # ------------------------------------------------------- Was not in symb table
1.620     albertel 9039:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9040:                             &GDBM_READER(),0640)) {
1.37      www      9041: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      9042:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      9043:               unless ($ids) { 
                   9044:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      9045:               }
                   9046:               unless ($ids) {
                   9047: # alias?
                   9048: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      9049:               }
1.37      www      9050:               if ($ids) {
                   9051: # ------------------------------------------------------------------- Has ID(s)
                   9052:                  my @possibilities=split(/\,/,$ids);
1.39      www      9053:                  if ($#possibilities==0) {
                   9054: # ----------------------------------------------- There is only one possibility
1.37      www      9055: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 9056: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9057: 						    $resid,$thisfn);
1.249     www      9058:                  } elsif (!$donotrecurse) {
1.39      www      9059: # ------------------------------------------ There is more than one possibility
                   9060:                      my $realpossible=0;
1.800     albertel 9061:                      foreach my $id (@possibilities) {
                   9062: 			 my $file=$bighash{'src_'.$id};
1.39      www      9063:                          if (&allowed('bre',$file)) {
1.800     albertel 9064:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      9065:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   9066: 				$realpossible++;
1.626     albertel 9067:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9068: 						    $resid,$thisfn);
1.39      www      9069:                             }
                   9070: 			 }
1.191     harris41 9071:                      }
1.39      www      9072: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      9073:                  } else {
                   9074:                      $syval='';
1.37      www      9075:                  }
                   9076: 	      }
                   9077:               untie(%bighash)
1.481     raeburn  9078:            }
1.31      www      9079:         }
1.62      www      9080:         if ($syval) {
1.620     albertel 9081: 	    return $env{$cache_str}=$syval;
1.62      www      9082:         }
1.31      www      9083:     }
1.949     raeburn  9084:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9085:     return $env{$cache_str}='';
1.31      www      9086: }
                   9087: 
                   9088: # ---------------------------------------------------------- Return random seed
                   9089: 
1.32      www      9090: sub numval {
                   9091:     my $txt=shift;
                   9092:     $txt=~tr/A-J/0-9/;
                   9093:     $txt=~tr/a-j/0-9/;
                   9094:     $txt=~tr/K-T/0-9/;
                   9095:     $txt=~tr/k-t/0-9/;
                   9096:     $txt=~tr/U-Z/0-5/;
                   9097:     $txt=~tr/u-z/0-5/;
                   9098:     $txt=~s/\D//g;
1.564     albertel 9099:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      9100:     return int($txt);
1.368     albertel 9101: }
                   9102: 
1.484     albertel 9103: sub numval2 {
                   9104:     my $txt=shift;
                   9105:     $txt=~tr/A-J/0-9/;
                   9106:     $txt=~tr/a-j/0-9/;
                   9107:     $txt=~tr/K-T/0-9/;
                   9108:     $txt=~tr/k-t/0-9/;
                   9109:     $txt=~tr/U-Z/0-5/;
                   9110:     $txt=~tr/u-z/0-5/;
                   9111:     $txt=~s/\D//g;
                   9112:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9113:     my $total;
                   9114:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 9115:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 9116:     return int($total);
                   9117: }
                   9118: 
1.575     albertel 9119: sub numval3 {
                   9120:     use integer;
                   9121:     my $txt=shift;
                   9122:     $txt=~tr/A-J/0-9/;
                   9123:     $txt=~tr/a-j/0-9/;
                   9124:     $txt=~tr/K-T/0-9/;
                   9125:     $txt=~tr/k-t/0-9/;
                   9126:     $txt=~tr/U-Z/0-5/;
                   9127:     $txt=~tr/u-z/0-5/;
                   9128:     $txt=~s/\D//g;
                   9129:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9130:     my $total;
                   9131:     foreach my $val (@txts) { $total+=$val; }
                   9132:     if ($_64bit) { $total=(($total<<32)>>32); }
                   9133:     return $total;
                   9134: }
                   9135: 
1.675     albertel 9136: sub digest {
                   9137:     my ($data)=@_;
                   9138:     my $digest=&Digest::MD5::md5($data);
                   9139:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   9140:     my ($e,$f);
                   9141:     {
                   9142:         use integer;
                   9143:         $e=($a+$b);
                   9144:         $f=($c+$d);
                   9145:         if ($_64bit) {
                   9146:             $e=(($e<<32)>>32);
                   9147:             $f=(($f<<32)>>32);
                   9148:         }
                   9149:     }
                   9150:     if (wantarray) {
                   9151: 	return ($e,$f);
                   9152:     } else {
                   9153: 	my $g;
                   9154: 	{
                   9155: 	    use integer;
                   9156: 	    $g=($e+$f);
                   9157: 	    if ($_64bit) {
                   9158: 		$g=(($g<<32)>>32);
                   9159: 	    }
                   9160: 	}
                   9161: 	return $g;
                   9162:     }
                   9163: }
                   9164: 
1.368     albertel 9165: sub latest_rnd_algorithm_id {
1.675     albertel 9166:     return '64bit5';
1.366     albertel 9167: }
1.32      www      9168: 
1.503     albertel 9169: sub get_rand_alg {
                   9170:     my ($courseid)=@_;
1.790     albertel 9171:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 9172:     if ($courseid) {
1.620     albertel 9173: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 9174:     }
                   9175:     return &latest_rnd_algorithm_id();
                   9176: }
                   9177: 
1.562     albertel 9178: sub validCODE {
                   9179:     my ($CODE)=@_;
                   9180:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   9181:     return 0;
                   9182: }
                   9183: 
1.491     albertel 9184: sub getCODE {
1.620     albertel 9185:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 9186:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   9187: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   9188: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 9189: 	return $Apache::lonhomework::history{'resource.CODE'};
                   9190:     }
                   9191:     return undef;
                   9192: }
                   9193: 
1.31      www      9194: sub rndseed {
1.155     albertel 9195:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 9196:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 9197:     if (!defined($symb)) {
1.366     albertel 9198: 	unless ($symb=$wsymb) { return time; }
                   9199:     }
                   9200:     if (!$courseid) { $courseid=$wcourseid; }
                   9201:     if (!$domain) { $domain=$wdomain; }
                   9202:     if (!$username) { $username=$wusername }
1.503     albertel 9203:     my $which=&get_rand_alg();
1.803     albertel 9204: 
1.491     albertel 9205:     if (defined(&getCODE())) {
1.675     albertel 9206: 	if ($which eq '64bit5') {
                   9207: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   9208: 	} elsif ($which eq '64bit4') {
1.575     albertel 9209: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   9210: 	} else {
                   9211: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   9212: 	}
1.675     albertel 9213:     } elsif ($which eq '64bit5') {
                   9214: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 9215:     } elsif ($which eq '64bit4') {
                   9216: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 9217:     } elsif ($which eq '64bit3') {
                   9218: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 9219:     } elsif ($which eq '64bit2') {
                   9220: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 9221:     } elsif ($which eq '64bit') {
                   9222: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   9223:     }
                   9224:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   9225: }
                   9226: 
                   9227: sub rndseed_32bit {
                   9228:     my ($symb,$courseid,$domain,$username)=@_;
                   9229:     {
                   9230: 	use integer;
                   9231: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   9232: 	my $symbseed=numval($symb) << 22;
                   9233: 	my $namechck=unpack("%32C*",$username) << 17;
                   9234: 	my $nameseed=numval($username) << 12;
                   9235: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   9236: 	my $courseseed=unpack("%32C*",$courseid);
                   9237: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 9238: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9239: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9240: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 9241: 	return $num;
                   9242:     }
                   9243: }
                   9244: 
                   9245: sub rndseed_64bit {
                   9246:     my ($symb,$courseid,$domain,$username)=@_;
                   9247:     {
                   9248: 	use integer;
                   9249: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   9250: 	my $symbseed=numval($symb) << 10;
                   9251: 	my $namechck=unpack("%32S*",$username);
                   9252: 	
                   9253: 	my $nameseed=numval($username) << 21;
                   9254: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   9255: 	my $courseseed=unpack("%32S*",$courseid);
                   9256: 	
                   9257: 	my $num1=$symbchck+$symbseed+$namechck;
                   9258: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9259: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9260: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9261: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 9262: 	return "$num1,$num2";
1.155     albertel 9263:     }
1.366     albertel 9264: }
                   9265: 
1.443     albertel 9266: sub rndseed_64bit2 {
                   9267:     my ($symb,$courseid,$domain,$username)=@_;
                   9268:     {
                   9269: 	use integer;
                   9270: 	# strings need to be an even # of cahracters long, it it is odd the
                   9271:         # last characters gets thrown away
                   9272: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9273: 	my $symbseed=numval($symb) << 10;
                   9274: 	my $namechck=unpack("%32S*",$username.' ');
                   9275: 	
                   9276: 	my $nameseed=numval($username) << 21;
1.501     albertel 9277: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9278: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9279: 	
                   9280: 	my $num1=$symbchck+$symbseed+$namechck;
                   9281: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9282: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9283: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 9284: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 9285: 	return "$num1,$num2";
                   9286:     }
                   9287: }
                   9288: 
                   9289: sub rndseed_64bit3 {
                   9290:     my ($symb,$courseid,$domain,$username)=@_;
                   9291:     {
                   9292: 	use integer;
                   9293: 	# strings need to be an even # of cahracters long, it it is odd the
                   9294:         # last characters gets thrown away
                   9295: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9296: 	my $symbseed=numval2($symb) << 10;
                   9297: 	my $namechck=unpack("%32S*",$username.' ');
                   9298: 	
                   9299: 	my $nameseed=numval2($username) << 21;
1.443     albertel 9300: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9301: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9302: 	
                   9303: 	my $num1=$symbchck+$symbseed+$namechck;
                   9304: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9305: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9306: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 9307: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9308: 	
1.503     albertel 9309: 	return "$num1:$num2";
1.443     albertel 9310:     }
                   9311: }
                   9312: 
1.575     albertel 9313: sub rndseed_64bit4 {
                   9314:     my ($symb,$courseid,$domain,$username)=@_;
                   9315:     {
                   9316: 	use integer;
                   9317: 	# strings need to be an even # of cahracters long, it it is odd the
                   9318:         # last characters gets thrown away
                   9319: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9320: 	my $symbseed=numval3($symb) << 10;
                   9321: 	my $namechck=unpack("%32S*",$username.' ');
                   9322: 	
                   9323: 	my $nameseed=numval3($username) << 21;
                   9324: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9325: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9326: 	
                   9327: 	my $num1=$symbchck+$symbseed+$namechck;
                   9328: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9329: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9330: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 9331: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9332: 	
                   9333: 	return "$num1:$num2";
                   9334:     }
                   9335: }
                   9336: 
1.675     albertel 9337: sub rndseed_64bit5 {
                   9338:     my ($symb,$courseid,$domain,$username)=@_;
                   9339:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   9340:     return "$num1:$num2";
                   9341: }
                   9342: 
1.366     albertel 9343: sub rndseed_CODE_64bit {
                   9344:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 9345:     {
1.366     albertel 9346: 	use integer;
1.443     albertel 9347: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 9348: 	my $symbseed=numval2($symb);
1.491     albertel 9349: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9350: 	my $CODEseed=numval(&getCODE());
1.443     albertel 9351: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 9352: 	my $num1=$symbseed+$CODEchck;
                   9353: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9354: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9355: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 9356: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9357: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 9358: 	return "$num1:$num2";
1.366     albertel 9359:     }
                   9360: }
                   9361: 
1.575     albertel 9362: sub rndseed_CODE_64bit4 {
                   9363:     my ($symb,$courseid,$domain,$username)=@_;
                   9364:     {
                   9365: 	use integer;
                   9366: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   9367: 	my $symbseed=numval3($symb);
                   9368: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9369: 	my $CODEseed=numval3(&getCODE());
                   9370: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9371: 	my $num1=$symbseed+$CODEchck;
                   9372: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9373: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9374: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 9375: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9376: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   9377: 	return "$num1:$num2";
                   9378:     }
                   9379: }
                   9380: 
1.675     albertel 9381: sub rndseed_CODE_64bit5 {
                   9382:     my ($symb,$courseid,$domain,$username)=@_;
                   9383:     my $code = &getCODE();
                   9384:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   9385:     return "$num1:$num2";
                   9386: }
                   9387: 
1.366     albertel 9388: sub setup_random_from_rndseed {
                   9389:     my ($rndseed)=@_;
1.503     albertel 9390:     if ($rndseed =~/([,:])/) {
                   9391: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 9392: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   9393:     } else {
                   9394: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 9395:     }
1.36      albertel 9396: }
                   9397: 
1.474     albertel 9398: sub latest_receipt_algorithm_id {
1.835     albertel 9399:     return 'receipt3';
1.474     albertel 9400: }
                   9401: 
1.480     www      9402: sub recunique {
                   9403:     my $fucourseid=shift;
                   9404:     my $unique;
1.835     albertel 9405:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   9406: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9407: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      9408:     } else {
                   9409: 	$unique=$perlvar{'lonReceipt'};
                   9410:     }
                   9411:     return unpack("%32C*",$unique);
                   9412: }
                   9413: 
                   9414: sub recprefix {
                   9415:     my $fucourseid=shift;
                   9416:     my $prefix;
1.835     albertel 9417:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   9418: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9419: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      9420:     } else {
                   9421: 	$prefix=$perlvar{'lonHostID'};
                   9422:     }
                   9423:     return unpack("%32C*",$prefix);
                   9424: }
                   9425: 
1.76      www      9426: sub ireceipt {
1.474     albertel 9427:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 9428: 
                   9429:     my $return =&recprefix($fucourseid).'-';
                   9430: 
                   9431:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   9432: 	$env{'request.state'} eq 'construct') {
                   9433: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   9434: 	return $return;
                   9435:     }
                   9436: 
1.76      www      9437:     my $cuname=unpack("%32C*",$funame);
                   9438:     my $cudom=unpack("%32C*",$fudom);
                   9439:     my $cucourseid=unpack("%32C*",$fucourseid);
                   9440:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      9441:     my $cunique=&recunique($fucourseid);
1.474     albertel 9442:     my $cpart=unpack("%32S*",$part);
1.835     albertel 9443:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   9444: 
1.790     albertel 9445: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 9446: 			       
                   9447: 	$return.= ($cunique%$cuname+
                   9448: 		   $cunique%$cudom+
                   9449: 		   $cusymb%$cuname+
                   9450: 		   $cusymb%$cudom+
                   9451: 		   $cucourseid%$cuname+
                   9452: 		   $cucourseid%$cudom+
                   9453: 		   $cpart%$cuname+
                   9454: 		   $cpart%$cudom);
                   9455:     } else {
                   9456: 	$return.= ($cunique%$cuname+
                   9457: 		   $cunique%$cudom+
                   9458: 		   $cusymb%$cuname+
                   9459: 		   $cusymb%$cudom+
                   9460: 		   $cucourseid%$cuname+
                   9461: 		   $cucourseid%$cudom);
                   9462:     }
                   9463:     return $return;
1.76      www      9464: }
                   9465: 
                   9466: sub receipt {
1.474     albertel 9467:     my ($part)=@_;
1.790     albertel 9468:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 9469:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      9470: }
1.260     ng       9471: 
1.790     albertel 9472: sub whichuser {
                   9473:     my ($passedsymb)=@_;
                   9474:     my ($symb,$courseid,$domain,$name,$publicuser);
                   9475:     if (defined($env{'form.grade_symb'})) {
                   9476: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   9477: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   9478: 	if (!$allowed &&
                   9479: 	    exists($env{'request.course.sec'}) &&
                   9480: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   9481: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   9482: 			      '/'.$env{'request.course.sec'});
                   9483: 	}
                   9484: 	if ($allowed) {
                   9485: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   9486: 	    $courseid=$tmp_courseid;
                   9487: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   9488: 	    ($name)=&get_env_multiple('form.grade_username');
                   9489: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   9490: 	}
                   9491:     }
                   9492:     if (!$passedsymb) {
                   9493: 	$symb=&symbread();
                   9494:     } else {
                   9495: 	$symb=$passedsymb;
                   9496:     }
                   9497:     $courseid=$env{'request.course.id'};
                   9498:     $domain=$env{'user.domain'};
                   9499:     $name=$env{'user.name'};
                   9500:     if ($name eq 'public' && $domain eq 'public') {
                   9501: 	if (!defined($env{'form.username'})) {
                   9502: 	    $env{'form.username'}.=time.rand(10000000);
                   9503: 	}
                   9504: 	$name.=$env{'form.username'};
                   9505:     }
                   9506:     return ($symb,$courseid,$domain,$name,$publicuser);
                   9507: 
                   9508: }
                   9509: 
1.36      albertel 9510: # ------------------------------------------------------------ Serves up a file
1.472     albertel 9511: # returns either the contents of the file or 
                   9512: # -1 if the file doesn't exist
1.481     raeburn  9513: #
                   9514: # if the target is a file that was uploaded via DOCS, 
                   9515: # a check will be made to see if a current copy exists on the local server,
                   9516: # if it does this will be served, otherwise a copy will be retrieved from
                   9517: # the home server for the course and stored in /home/httpd/html/userfiles on
                   9518: # the local server.   
1.472     albertel 9519: 
1.36      albertel 9520: sub getfile {
1.538     albertel 9521:     my ($file) = @_;
1.609     banghart 9522:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 9523:     &repcopy($file);
                   9524:     return &readfile($file);
                   9525: }
                   9526: 
                   9527: sub repcopy_userfile {
                   9528:     my ($file)=@_;
1.609     banghart 9529:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 9530:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 9531:     my ($cdom,$cnum,$filename) = 
1.811     albertel 9532: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 9533:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   9534:     if (-e "$file") {
1.828     www      9535: # we already have a local copy, check it out
1.538     albertel 9536: 	my @fileinfo = stat($file);
1.828     www      9537: 	my $rtncode;
                   9538: 	my $info;
1.538     albertel 9539: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 9540: 	if ($lwpresp ne 'ok') {
1.828     www      9541: # there is no such file anymore, even though we had a local copy
1.482     albertel 9542: 	    if ($rtncode eq '404') {
1.538     albertel 9543: 		unlink($file);
1.482     albertel 9544: 	    }
                   9545: 	    return -1;
                   9546: 	}
                   9547: 	if ($info < $fileinfo[9]) {
1.828     www      9548: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  9549: 	    return 'ok';
1.828     www      9550: 	} else {
                   9551: # the file is outdated, get rid of it
                   9552: 	    unlink($file);
1.482     albertel 9553: 	}
1.828     www      9554:     }
                   9555: # one way or the other, at this point, we don't have the file
                   9556: # construct the correct path for the file
                   9557:     my @parts = ($cdom,$cnum); 
                   9558:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   9559: 	push @parts, split(/\//,$1);
                   9560:     }
                   9561:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   9562:     foreach my $part (@parts) {
                   9563: 	$path .= '/'.$part;
                   9564: 	if (!-e $path) {
                   9565: 	    mkdir($path,0770);
1.482     albertel 9566: 	}
                   9567:     }
1.828     www      9568: # now the path exists for sure
                   9569: # get a user agent
                   9570:     my $ua=new LWP::UserAgent;
                   9571:     my $transferfile=$file.'.in.transfer';
                   9572: # FIXME: this should flock
                   9573:     if (-e $transferfile) { return 'ok'; }
                   9574:     my $request;
                   9575:     $uri=~s/^\///;
1.980     raeburn  9576:     my $homeserver = &homeserver($cnum,$cdom);
                   9577:     my $protocol = $protocol{$homeserver};
                   9578:     $protocol = 'http' if ($protocol ne 'https');
                   9579:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      9580:     my $response=$ua->request($request,$transferfile);
                   9581: # did it work?
                   9582:     if ($response->is_error()) {
                   9583: 	unlink($transferfile);
                   9584: 	&logthis("Userfile repcopy failed for $uri");
                   9585: 	return -1;
                   9586:     }
                   9587: # worked, rename the transfer file
                   9588:     rename($transferfile,$file);
1.607     raeburn  9589:     return 'ok';
1.481     raeburn  9590: }
                   9591: 
1.517     albertel 9592: sub tokenwrapper {
                   9593:     my $uri=shift;
1.980     raeburn  9594:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 9595:     $uri=~s|^/||;
1.620     albertel 9596:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 9597:     my $token=$1;
1.552     albertel 9598:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   9599:     if ($udom && $uname && $file) {
                   9600: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  9601:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  9602:         my $homeserver = &homeserver($uname,$udom);
                   9603:         my $protocol = $protocol{$homeserver};
                   9604:         $protocol = 'http' if ($protocol ne 'https');
                   9605:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 9606:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   9607:                                '&tokenissued='.$perlvar{'lonHostID'};
                   9608:     } else {
                   9609:         return '/adm/notfound.html';
                   9610:     }
                   9611: }
                   9612: 
1.828     www      9613: # call with reqtype HEAD: get last modification time
                   9614: # call with reqtype GET: get the file contents
                   9615: # Do not call this with reqtype GET for large files! It loads everything into memory
                   9616: #
1.481     raeburn  9617: sub getuploaded {
                   9618:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   9619:     $uri=~s/^\///;
1.980     raeburn  9620:     my $homeserver = &homeserver($cnum,$cdom);
                   9621:     my $protocol = $protocol{$homeserver};
                   9622:     $protocol = 'http' if ($protocol ne 'https');
                   9623:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  9624:     my $ua=new LWP::UserAgent;
                   9625:     my $request=new HTTP::Request($reqtype,$uri);
                   9626:     my $response=$ua->request($request);
                   9627:     $$rtncode = $response->code;
1.482     albertel 9628:     if (! $response->is_success()) {
                   9629: 	return 'failed';
                   9630:     }      
                   9631:     if ($reqtype eq 'HEAD') {
1.486     www      9632: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 9633:     } elsif ($reqtype eq 'GET') {
                   9634: 	$$info = $response->content;
1.472     albertel 9635:     }
1.482     albertel 9636:     return 'ok';
1.36      albertel 9637: }
                   9638: 
1.481     raeburn  9639: sub readfile {
                   9640:     my $file = shift;
                   9641:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   9642:     my $fh;
                   9643:     open($fh,"<$file");
                   9644:     my $a='';
1.800     albertel 9645:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  9646:     return $a;
                   9647: }
                   9648: 
1.36      albertel 9649: sub filelocation {
1.590     banghart 9650:     my ($dir,$file) = @_;
                   9651:     my $location;
                   9652:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 9653: 
                   9654:     if ($file =~ m-^/adm/-) {
                   9655: 	$file=~s-^/adm/wrapper/-/-;
                   9656: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   9657:     }
1.882     albertel 9658: 
1.590     banghart 9659:     if ($file=~m:^/~:) { # is a contruction space reference
                   9660:         $location = $file;
                   9661:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 9662:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 9663: 	# is a correct contruction space reference
                   9664:         $location = $file;
1.956     raeburn  9665:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   9666:         $location = $file;
1.609     banghart 9667:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 9668:         my ($udom,$uname,$filename)=
1.811     albertel 9669:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 9670:         my $home=&homeserver($uname,$udom);
                   9671:         my $is_me=0;
                   9672:         my @ids=&current_machine_ids();
                   9673:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   9674:         if ($is_me) {
1.955     raeburn  9675:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 9676:         } else {
                   9677:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   9678:   	      $udom.'/'.$uname.'/'.$filename;
                   9679:         }
1.882     albertel 9680:     } elsif ($file =~ m-^/adm/-) {
                   9681: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 9682:     } else {
                   9683:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   9684:         $file=~s:^/res/:/:;
                   9685:         if ( !( $file =~ m:^/:) ) {
                   9686:             $location = $dir. '/'.$file;
                   9687:         } else {
                   9688:             $location = '/home/httpd/html/res'.$file;
                   9689:         }
1.59      albertel 9690:     }
1.590     banghart 9691:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 9692:     while ($location=~m{/\.\./}) {
                   9693: 	if ($location =~ m{/[^/]+/\.\./}) {
                   9694: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   9695: 	} else {
                   9696: 	    $location=~ s{/\.\./}{/}g;
                   9697: 	}
                   9698:     } #remove dir/..
1.590     banghart 9699:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   9700:     return $location;
1.46      www      9701: }
1.36      albertel 9702: 
1.46      www      9703: sub hreflocation {
                   9704:     my ($dir,$file)=@_;
1.980     raeburn  9705:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 9706: 	$file=filelocation($dir,$file);
1.700     albertel 9707:     } elsif ($file=~m-^/adm/-) {
                   9708: 	$file=~s-^/adm/wrapper/-/-;
                   9709: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 9710:     }
                   9711:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   9712: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 9713:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   9714: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 9715:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 9716: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 9717: 	    -/uploaded/$1/$2/-x;
1.46      www      9718:     }
1.913     albertel 9719:     if ($file=~ m{^/userfiles/}) {
                   9720: 	$file =~ s{^/userfiles/}{/uploaded/};
                   9721:     }
1.462     albertel 9722:     return $file;
1.465     albertel 9723: }
                   9724: 
                   9725: sub current_machine_domains {
1.853     albertel 9726:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   9727: }
                   9728: 
                   9729: sub machine_domains {
                   9730:     my ($hostname) = @_;
1.465     albertel 9731:     my @domains;
1.838     albertel 9732:     my %hostname = &all_hostnames();
1.465     albertel 9733:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  9734: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 9735: 	if ($hostname eq $name) {
1.844     albertel 9736: 	    push(@domains,&host_domain($id));
1.465     albertel 9737: 	}
                   9738:     }
                   9739:     return @domains;
                   9740: }
                   9741: 
                   9742: sub current_machine_ids {
1.853     albertel 9743:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   9744: }
                   9745: 
                   9746: sub machine_ids {
                   9747:     my ($hostname) = @_;
                   9748:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 9749:     my @ids;
1.888     albertel 9750:     my %name_to_host = &all_names();
1.889     albertel 9751:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   9752: 	return @{ $name_to_host{$hostname} };
                   9753:     }
                   9754:     return;
1.31      www      9755: }
                   9756: 
1.824     raeburn  9757: sub additional_machine_domains {
                   9758:     my @domains;
                   9759:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   9760:     while( my $line = <$fh>) {
                   9761:         $line =~ s/\s//g;
                   9762:         push(@domains,$line);
                   9763:     }
                   9764:     return @domains;
                   9765: }
                   9766: 
                   9767: sub default_login_domain {
                   9768:     my $domain = $perlvar{'lonDefDomain'};
                   9769:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   9770:     foreach my $posdom (&current_machine_domains(),
                   9771:                         &additional_machine_domains()) {
                   9772:         if (lc($posdom) eq lc($testdomain)) {
                   9773:             $domain=$posdom;
                   9774:             last;
                   9775:         }
                   9776:     }
                   9777:     return $domain;
                   9778: }
                   9779: 
1.31      www      9780: # ------------------------------------------------------------- Declutters URLs
                   9781: 
                   9782: sub declutter {
                   9783:     my $thisfn=shift;
1.569     albertel 9784:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 9785:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      9786:     $thisfn=~s/^\///;
1.697     albertel 9787:     $thisfn=~s|^adm/wrapper/||;
                   9788:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      9789:     $thisfn=~s/^res\///;
1.1032    raeburn  9790:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   9791:         $thisfn=~s/\?.+$//;
                   9792:     }
1.268     www      9793:     return $thisfn;
                   9794: }
                   9795: 
                   9796: # ------------------------------------------------------------- Clutter up URLs
                   9797: 
                   9798: sub clutter {
                   9799:     my $thisfn='/'.&declutter(shift);
1.887     albertel 9800:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 9801: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      9802:        $thisfn='/res'.$thisfn; 
                   9803:     }
1.1031    raeburn  9804:     if ($thisfn !~m|^/adm|) {
                   9805: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 9806: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 9807: 	} else {
                   9808: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   9809: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 9810: 	    if ($embstyle eq 'ssi'
                   9811: 		|| ($embstyle eq 'hdn')
                   9812: 		|| ($embstyle eq 'rat')
                   9813: 		|| ($embstyle eq 'prv')
                   9814: 		|| ($embstyle eq 'ign')) {
                   9815: 		#do nothing with these
                   9816: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 9817: 		|| ($embstyle eq 'emb')
                   9818: 		|| ($embstyle eq 'wrp')) {
                   9819: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 9820: 	    } elsif ($embstyle eq 'unk'
                   9821: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 9822: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 9823: 	    } else {
1.718     www      9824: #		&logthis("Got a blank emb style");
1.695     albertel 9825: 	    }
1.694     albertel 9826: 	}
                   9827:     }
1.31      www      9828:     return $thisfn;
1.12      www      9829: }
                   9830: 
1.787     albertel 9831: sub clutter_with_no_wrapper {
                   9832:     my $uri = &clutter(shift);
                   9833:     if ($uri =~ m-^/adm/-) {
                   9834: 	$uri =~ s-^/adm/wrapper/-/-;
                   9835: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   9836:     }
                   9837:     return $uri;
                   9838: }
                   9839: 
1.557     albertel 9840: sub freeze_escape {
                   9841:     my ($value)=@_;
                   9842:     if (ref($value)) {
                   9843: 	$value=&nfreeze($value);
                   9844: 	return '__FROZEN__'.&escape($value);
                   9845:     }
                   9846:     return &escape($value);
                   9847: }
                   9848: 
1.11      www      9849: 
1.557     albertel 9850: sub thaw_unescape {
                   9851:     my ($value)=@_;
                   9852:     if ($value =~ /^__FROZEN__/) {
                   9853: 	substr($value,0,10,undef);
                   9854: 	$value=&unescape($value);
                   9855: 	return &thaw($value);
                   9856:     }
                   9857:     return &unescape($value);
                   9858: }
                   9859: 
1.436     albertel 9860: sub correct_line_ends {
                   9861:     my ($result)=@_;
                   9862:     $$result =~s/\r\n/\n/mg;
                   9863:     $$result =~s/\r/\n/mg;
1.415     albertel 9864: }
1.1       albertel 9865: # ================================================================ Main Program
                   9866: 
1.184     www      9867: sub goodbye {
1.204     albertel 9868:    &logthis("Starting Shut down");
1.443     albertel 9869: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 9870:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 9871: #converted
1.599     albertel 9872: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 9873:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   9874: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   9875: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 9876: #1.1 only
1.870     albertel 9877: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   9878: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   9879: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   9880: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   9881:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 9882:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   9883:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      9884:    &flushcourselogs();
                   9885:    &logthis("Shutting down");
                   9886: }
                   9887: 
1.852     albertel 9888: sub get_dns {
1.869     albertel 9889:     my ($url,$func,$ignore_cache) = @_;
                   9890:     if (!$ignore_cache) {
                   9891: 	my ($content,$cached)=
                   9892: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   9893: 	if ($cached) {
                   9894: 	    &$func($content);
                   9895: 	    return;
                   9896: 	}
                   9897:     }
                   9898: 
                   9899:     my %alldns;
1.852     albertel 9900:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9901:     foreach my $dns (<$config>) {
                   9902: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  9903:         my $line = $1;
                   9904:         my ($host,$protocol) = split(/:/,$line);
                   9905:         if ($protocol ne 'https') {
                   9906:             $protocol = 'http';
                   9907:         }
                   9908: 	$alldns{$host} = $protocol;
1.869     albertel 9909:     }
                   9910:     while (%alldns) {
                   9911: 	my ($dns) = keys(%alldns);
1.852     albertel 9912: 	my $ua=new LWP::UserAgent;
1.979     raeburn  9913: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 9914: 	my $response=$ua->request($request);
1.979     raeburn  9915:         delete($alldns{$dns});
1.852     albertel 9916: 	next if ($response->is_error());
                   9917: 	my @content = split("\n",$response->content);
1.869     albertel 9918: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 9919: 	&$func(\@content);
1.869     albertel 9920: 	return;
1.852     albertel 9921:     }
                   9922:     close($config);
1.871     albertel 9923:     my $which = (split('/',$url))[3];
                   9924:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   9925:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 9926:     my @content = <$config>;
                   9927:     &$func(\@content);
                   9928:     return;
1.852     albertel 9929: }
1.327     albertel 9930: # ------------------------------------------------------------ Read domain file
                   9931: {
1.852     albertel 9932:     my $loaded;
1.846     albertel 9933:     my %domain;
                   9934: 
1.852     albertel 9935:     sub parse_domain_tab {
                   9936: 	my ($lines) = @_;
                   9937: 	foreach my $line (@$lines) {
                   9938: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      9939: 
1.846     albertel 9940: 	    chomp($line);
1.852     albertel 9941: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 9942: 	    my %this_domain;
                   9943: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   9944: 			       'lang_def', 'city', 'longi', 'lati',
                   9945: 			       'primary') {
                   9946: 		$this_domain{$field} = shift(@elements);
                   9947: 	    }
                   9948: 	    $domain{$name} = \%this_domain;
1.852     albertel 9949: 	}
                   9950:     }
1.864     albertel 9951: 
                   9952:     sub reset_domain_info {
                   9953: 	undef($loaded);
                   9954: 	undef(%domain);
                   9955:     }
                   9956: 
1.852     albertel 9957:     sub load_domain_tab {
1.869     albertel 9958: 	my ($ignore_cache) = @_;
                   9959: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 9960: 	my $fh;
                   9961: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   9962: 	    my @lines = <$fh>;
                   9963: 	    &parse_domain_tab(\@lines);
1.448     albertel 9964: 	}
1.852     albertel 9965: 	close($fh);
                   9966: 	$loaded = 1;
1.327     albertel 9967:     }
1.846     albertel 9968: 
                   9969:     sub domain {
1.852     albertel 9970: 	&load_domain_tab() if (!$loaded);
                   9971: 
1.846     albertel 9972: 	my ($name,$what) = @_;
                   9973: 	return if ( !exists($domain{$name}) );
                   9974: 
                   9975: 	if (!$what) {
                   9976: 	    return $domain{$name}{'description'};
                   9977: 	}
                   9978: 	return $domain{$name}{$what};
                   9979:     }
1.974     raeburn  9980: 
                   9981:     sub domain_info {
                   9982:         &load_domain_tab() if (!$loaded);
                   9983:         return %domain;
                   9984:     }
                   9985: 
1.327     albertel 9986: }
                   9987: 
                   9988: 
1.1       albertel 9989: # ------------------------------------------------------------- Read hosts file
                   9990: {
1.838     albertel 9991:     my %hostname;
1.844     albertel 9992:     my %hostdom;
1.845     albertel 9993:     my %libserv;
1.852     albertel 9994:     my $loaded;
1.888     albertel 9995:     my %name_to_host;
1.1056.4.6  raeburn  9996:     my %internetdom;
1.852     albertel 9997: 
                   9998:     sub parse_hosts_tab {
                   9999: 	my ($file) = @_;
                   10000: 	foreach my $configline (@$file) {
                   10001: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   10002: 	    next if ($configline =~ /^\^/);
                   10003: 	    chomp($configline);
1.1056.4.6  raeburn  10004: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 10005: 	    $name=~s/\s//g;
                   10006: 	    if ($id && $domain && $role && $name) {
                   10007: 		$hostname{$id}=$name;
1.888     albertel 10008: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 10009: 		$hostdom{$id}=$domain;
                   10010: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  10011:                 if (defined($protocol)) {
                   10012:                     if ($protocol eq 'https') {
                   10013:                         $protocol{$id} = $protocol;
                   10014:                     } else {
                   10015:                         $protocol{$id} = 'http'; 
                   10016:                     }
1.968     raeburn  10017:                 } else {
1.969     raeburn  10018:                     $protocol{$id} = 'http';
1.968     raeburn  10019:                 }
1.1056.4.6  raeburn  10020:                 if (defined($intdom)) {
                   10021:                     $internetdom{$id} = $intdom;
                   10022:                 }
1.852     albertel 10023: 	    }
                   10024: 	}
                   10025:     }
1.864     albertel 10026:     
                   10027:     sub reset_hosts_info {
1.897     albertel 10028: 	&purge_remembered();
1.864     albertel 10029: 	&reset_domain_info();
                   10030: 	&reset_hosts_ip_info();
1.892     albertel 10031: 	undef(%name_to_host);
1.864     albertel 10032: 	undef(%hostname);
                   10033: 	undef(%hostdom);
                   10034: 	undef(%libserv);
                   10035: 	undef($loaded);
                   10036:     }
1.1       albertel 10037: 
1.852     albertel 10038:     sub load_hosts_tab {
1.869     albertel 10039: 	my ($ignore_cache) = @_;
                   10040: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 10041: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10042: 	my @config = <$config>;
                   10043: 	&parse_hosts_tab(\@config);
                   10044: 	close($config);
                   10045: 	$loaded=1;
1.1       albertel 10046:     }
1.852     albertel 10047: 
1.838     albertel 10048:     sub hostname {
1.852     albertel 10049: 	&load_hosts_tab() if (!$loaded);
                   10050: 
1.838     albertel 10051: 	my ($lonid) = @_;
                   10052: 	return $hostname{$lonid};
                   10053:     }
1.845     albertel 10054: 
1.838     albertel 10055:     sub all_hostnames {
1.852     albertel 10056: 	&load_hosts_tab() if (!$loaded);
                   10057: 
1.838     albertel 10058: 	return %hostname;
                   10059:     }
1.845     albertel 10060: 
1.888     albertel 10061:     sub all_names {
                   10062: 	&load_hosts_tab() if (!$loaded);
                   10063: 
                   10064: 	return %name_to_host;
                   10065:     }
                   10066: 
1.974     raeburn  10067:     sub all_host_domain {
                   10068:         &load_hosts_tab() if (!$loaded);
                   10069:         return %hostdom;
                   10070:     }
                   10071: 
1.845     albertel 10072:     sub is_library {
1.852     albertel 10073: 	&load_hosts_tab() if (!$loaded);
                   10074: 
1.845     albertel 10075: 	return exists($libserv{$_[0]});
                   10076:     }
                   10077: 
                   10078:     sub all_library {
1.852     albertel 10079: 	&load_hosts_tab() if (!$loaded);
                   10080: 
1.845     albertel 10081: 	return %libserv;
                   10082:     }
                   10083: 
1.1056.4.2  raeburn  10084:     sub unique_library {
                   10085:         #2x reverse removes all hostnames that appear more than once
                   10086:         my %unique = reverse &all_library();
                   10087:         return reverse %unique;
                   10088:     }
                   10089: 
1.841     albertel 10090:     sub get_servers {
1.852     albertel 10091: 	&load_hosts_tab() if (!$loaded);
                   10092: 
1.841     albertel 10093: 	my ($domain,$type) = @_;
                   10094: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   10095: 	                                          : %hostname;
                   10096: 	my %result;
1.842     albertel 10097: 	if (ref($domain) eq 'ARRAY') {
                   10098: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 10099: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 10100: 		    $result{$host} = $hostname;
                   10101: 		}
                   10102: 	    }
                   10103: 	} else {
                   10104: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   10105: 		if ($hostdom{$host} eq $domain) {
                   10106: 		    $result{$host} = $hostname;
                   10107: 		}
1.841     albertel 10108: 	    }
                   10109: 	}
                   10110: 	return %result;
                   10111:     }
1.845     albertel 10112: 
1.1056.4.2  raeburn  10113:     sub get_unique_servers {
                   10114:         my %unique = reverse &get_servers(@_);
                   10115:         return reverse %unique;
                   10116:     }
                   10117: 
1.844     albertel 10118:     sub host_domain {
1.852     albertel 10119: 	&load_hosts_tab() if (!$loaded);
                   10120: 
1.844     albertel 10121: 	my ($lonid) = @_;
                   10122: 	return $hostdom{$lonid};
                   10123:     }
                   10124: 
1.841     albertel 10125:     sub all_domains {
1.852     albertel 10126: 	&load_hosts_tab() if (!$loaded);
                   10127: 
1.841     albertel 10128: 	my %seen;
                   10129: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   10130: 	return @uniq;
                   10131:     }
1.1056.4.3  raeburn  10132: 
                   10133:     sub internet_dom {
                   10134:         &load_hosts_tab() if (!$loaded);
                   10135: 
                   10136:         my ($lonid) = @_;
                   10137:         return $internetdom{$lonid};
                   10138:     }
1.1       albertel 10139: }
                   10140: 
1.847     albertel 10141: { 
                   10142:     my %iphost;
1.856     albertel 10143:     my %name_to_ip;
                   10144:     my %lonid_to_ip;
1.869     albertel 10145: 
1.847     albertel 10146:     sub get_hosts_from_ip {
                   10147: 	my ($ip) = @_;
                   10148: 	my %iphosts = &get_iphost();
                   10149: 	if (ref($iphosts{$ip})) {
                   10150: 	    return @{$iphosts{$ip}};
                   10151: 	}
                   10152: 	return;
1.839     albertel 10153:     }
1.864     albertel 10154:     
                   10155:     sub reset_hosts_ip_info {
                   10156: 	undef(%iphost);
                   10157: 	undef(%name_to_ip);
                   10158: 	undef(%lonid_to_ip);
                   10159:     }
1.856     albertel 10160: 
                   10161:     sub get_host_ip {
                   10162: 	my ($lonid) = @_;
                   10163: 	if (exists($lonid_to_ip{$lonid})) {
                   10164: 	    return $lonid_to_ip{$lonid};
                   10165: 	}
                   10166: 	my $name=&hostname($lonid);
                   10167:    	my $ip = gethostbyname($name);
                   10168: 	return if (!$ip || length($ip) ne 4);
                   10169: 	$ip=inet_ntoa($ip);
                   10170: 	$name_to_ip{$name}   = $ip;
                   10171: 	$lonid_to_ip{$lonid} = $ip;
                   10172: 	return $ip;
                   10173:     }
1.847     albertel 10174:     
                   10175:     sub get_iphost {
1.869     albertel 10176: 	my ($ignore_cache) = @_;
1.894     albertel 10177: 
1.869     albertel 10178: 	if (!$ignore_cache) {
                   10179: 	    if (%iphost) {
                   10180: 		return %iphost;
                   10181: 	    }
                   10182: 	    my ($ip_info,$cached)=
                   10183: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   10184: 	    if ($cached) {
                   10185: 		%iphost      = %{$ip_info->[0]};
                   10186: 		%name_to_ip  = %{$ip_info->[1]};
                   10187: 		%lonid_to_ip = %{$ip_info->[2]};
                   10188: 		return %iphost;
                   10189: 	    }
                   10190: 	}
1.894     albertel 10191: 
                   10192: 	# get yesterday's info for fallback
                   10193: 	my %old_name_to_ip;
                   10194: 	my ($ip_info,$cached)=
                   10195: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   10196: 	if ($cached) {
                   10197: 	    %old_name_to_ip = %{$ip_info->[1]};
                   10198: 	}
                   10199: 
1.888     albertel 10200: 	my %name_to_host = &all_names();
                   10201: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 10202: 	    my $ip;
                   10203: 	    if (!exists($name_to_ip{$name})) {
                   10204: 		$ip = gethostbyname($name);
                   10205: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 10206: 		    if (defined($old_name_to_ip{$name})) {
                   10207: 			$ip = $old_name_to_ip{$name};
                   10208: 			&logthis("Can't find $name defaulting to old $ip");
                   10209: 		    } else {
                   10210: 			&logthis("Name $name no IP found");
                   10211: 			next;
                   10212: 		    }
                   10213: 		} else {
                   10214: 		    $ip=inet_ntoa($ip);
1.847     albertel 10215: 		}
                   10216: 		$name_to_ip{$name} = $ip;
                   10217: 	    } else {
                   10218: 		$ip = $name_to_ip{$name};
1.653     albertel 10219: 	    }
1.888     albertel 10220: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   10221: 		$lonid_to_ip{$id} = $ip;
                   10222: 	    }
                   10223: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 10224: 	}
1.869     albertel 10225: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   10226: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 10227: 				      48*60*60);
1.869     albertel 10228: 
1.847     albertel 10229: 	return %iphost;
1.598     albertel 10230:     }
                   10231: 
1.992     raeburn  10232:     #
                   10233:     #  Given a DNS returns the loncapa host name for that DNS 
                   10234:     # 
                   10235:     sub host_from_dns {
                   10236:         my ($dns) = @_;
                   10237:         my @hosts;
                   10238:         my $ip;
                   10239: 
1.993     raeburn  10240:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  10241:             $ip = $name_to_ip{$dns};
                   10242:         }
                   10243:         if (!$ip) {
                   10244:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   10245:             if (length($ip) == 4) { 
                   10246: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   10247:             }
                   10248:         }
                   10249:         if ($ip) {
                   10250: 	    @hosts = get_hosts_from_ip($ip);
                   10251: 	    return $hosts[0];
                   10252:         }
                   10253:         return undef;
1.986     foxr     10254:     }
1.992     raeburn  10255: 
1.1056.4.3  raeburn  10256:     sub get_internet_names {
                   10257:         my ($lonid) = @_;
                   10258:         return if ($lonid eq '');
                   10259:         my ($idnref,$cached)=
                   10260:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   10261:         if ($cached) {
                   10262:             return $idnref;
                   10263:         }
                   10264:         my $ip = &get_host_ip($lonid);
                   10265:         my @hosts = &get_hosts_from_ip($ip);
                   10266:         my %iphost = &get_iphost();
                   10267:         my (@idns,%seen);
                   10268:         foreach my $id (@hosts) {
                   10269:             my $dom = &host_domain($id);
                   10270:             my $prim_id = &domain($dom,'primary');
                   10271:             my $prim_ip = &get_host_ip($prim_id);
                   10272:             next if ($seen{$prim_ip});
                   10273:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   10274:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   10275:                     my $intdom = &internet_dom($id);
                   10276:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   10277:                         push(@idns,$intdom);
                   10278:                     }
                   10279:                 }
                   10280:             }
                   10281:             $seen{$prim_ip} = 1;
                   10282:         }
                   10283:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   10284:     }
                   10285: 
                   10286: }
                   10287: 
                   10288: sub all_loncaparevs {
                   10289:     return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10);
1.986     foxr     10290: }
                   10291: 
1.862     albertel 10292: BEGIN {
                   10293: 
                   10294: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   10295:     unless ($readit) {
                   10296: {
                   10297:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   10298:     %perlvar = (%perlvar,%{$configvars});
                   10299: }
                   10300: 
                   10301: 
1.1       albertel 10302: # ------------------------------------------------------ Read spare server file
                   10303: {
1.448     albertel 10304:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 10305: 
                   10306:     while (my $configline=<$config>) {
                   10307:        chomp($configline);
1.284     matthew  10308:        if ($configline) {
1.784     albertel 10309: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 10310: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 10311: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 10312:        }
                   10313:     }
1.448     albertel 10314:     close($config);
1.1       albertel 10315: }
1.11      www      10316: # ------------------------------------------------------------ Read permissions
                   10317: {
1.448     albertel 10318:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      10319: 
                   10320:     while (my $configline=<$config>) {
1.448     albertel 10321: 	chomp($configline);
                   10322: 	if ($configline) {
                   10323: 	    my ($role,$perm)=split(/ /,$configline);
                   10324: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   10325: 	}
1.11      www      10326:     }
1.448     albertel 10327:     close($config);
1.11      www      10328: }
                   10329: 
                   10330: # -------------------------------------------- Read plain texts for permissions
                   10331: {
1.448     albertel 10332:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      10333: 
                   10334:     while (my $configline=<$config>) {
1.448     albertel 10335: 	chomp($configline);
                   10336: 	if ($configline) {
1.742     raeburn  10337: 	    my ($short,@plain)=split(/:/,$configline);
                   10338:             %{$prp{$short}} = ();
                   10339: 	    if (@plain > 0) {
                   10340:                 $prp{$short}{'std'} = $plain[0];
                   10341:                 for (my $i=1; $i<@plain; $i++) {
                   10342:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   10343:                 }
                   10344:             }
1.448     albertel 10345: 	}
1.135     www      10346:     }
1.448     albertel 10347:     close($config);
1.135     www      10348: }
                   10349: 
                   10350: # ---------------------------------------------------------- Read package table
                   10351: {
1.448     albertel 10352:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      10353: 
                   10354:     while (my $configline=<$config>) {
1.483     albertel 10355: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 10356: 	chomp($configline);
                   10357: 	my ($short,$plain)=split(/:/,$configline);
                   10358: 	my ($pack,$name)=split(/\&/,$short);
                   10359: 	if ($plain ne '') {
                   10360: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   10361: 	    $packagetab{$short}=$plain; 
                   10362: 	}
1.11      www      10363:     }
1.448     albertel 10364:     close($config);
1.329     matthew  10365: }
                   10366: 
1.1056.4.3  raeburn  10367: # ---------------------------------------------------------- Read loncaparev table
                   10368: {
                   10369:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   10370:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   10371:             while (my $configline=<$config>) {
                   10372:                 chomp($configline);
                   10373:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   10374:                 $loncaparevs{$hostid}=$loncaparev;
                   10375:             }
                   10376:             close($config);
                   10377:         }
                   10378:     }
                   10379: }
                   10380: 
                   10381: # ---------------------------------------------------------- Read serverhostID table
                   10382: {
                   10383:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   10384:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   10385:             while (my $configline=<$config>) {
                   10386:                 chomp($configline);
                   10387:                 my ($name,$id)=split(/:/,$configline);
                   10388:                 $serverhomeIDs{$name}=$id;
                   10389:             }
                   10390:             close($config);
                   10391:         }
                   10392:     }
                   10393: }
                   10394: 
1.1056.4.5  raeburn  10395: {
                   10396:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   10397:     if (-e $file) {
                   10398:         my $parser = HTML::LCParser->new($file);
                   10399:         while (my $token = $parser->get_token()) {
                   10400:             if ($token->[0] eq 'S') {
                   10401:                 my $item = $token->[1];
                   10402:                 my $name = $token->[2]{'name'};
                   10403:                 my $value = $token->[2]{'value'};
                   10404:                 if ($item ne '' && $name ne '' && $value ne '') {
                   10405:                     my $release = $parser->get_text();
                   10406:                     $release =~ s/(^\s*|\s*$ )//gx;
                   10407:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   10408:                 }
                   10409:             }
                   10410:         }
                   10411:     }
                   10412: }
                   10413: 
1.329     matthew  10414: # ------------- set up temporary directory
                   10415: {
                   10416:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   10417: 
1.11      www      10418: }
                   10419: 
1.794     albertel 10420: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   10421: 				'compress_threshold'=> 20_000,
                   10422:  			        });
1.185     www      10423: 
1.281     www      10424: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      10425: $dumpcount=0;
1.958     www      10426: $locknum=0;
1.22      www      10427: 
1.163     harris41 10428: &logtouch();
1.672     albertel 10429: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      10430: $readit=1;
1.564     albertel 10431:     {
                   10432: 	use integer;
                   10433: 	my $test=(2**32)+1;
1.568     albertel 10434: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 10435: 	&logthis(" Detected 64bit platform ($_64bit)");
                   10436:     }
1.195     www      10437: }
1.1       albertel 10438: }
1.179     www      10439: 
1.1       albertel 10440: 1;
1.191     harris41 10441: __END__
                   10442: 
1.243     albertel 10443: =pod
                   10444: 
1.191     harris41 10445: =head1 NAME
                   10446: 
1.243     albertel 10447: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 10448: 
                   10449: =head1 SYNOPSIS
                   10450: 
1.243     albertel 10451: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 10452: 
                   10453:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   10454: 
1.243     albertel 10455: Common parameters:
                   10456: 
                   10457: =over 4
                   10458: 
                   10459: =item *
                   10460: 
                   10461: $uname : an internal username (if $cname expecting a course Id specifically)
                   10462: 
                   10463: =item *
                   10464: 
                   10465: $udom : a domain (if $cdom expecting a course's domain specifically)
                   10466: 
                   10467: =item *
                   10468: 
                   10469: $symb : a resource instance identifier
                   10470: 
                   10471: =item *
                   10472: 
                   10473: $namespace : the name of a .db file that contains the data needed or
                   10474: being set.
                   10475: 
                   10476: =back
                   10477: 
1.394     bowersj2 10478: =head1 OVERVIEW
1.191     harris41 10479: 
1.394     bowersj2 10480: lonnet provides subroutines which interact with the
                   10481: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   10482: about classes, users, and resources.
1.243     albertel 10483: 
                   10484: For many of these objects you can also use this to store data about
                   10485: them or modify them in various ways.
1.191     harris41 10486: 
1.394     bowersj2 10487: =head2 Symbs
1.191     harris41 10488: 
1.394     bowersj2 10489: To identify a specific instance of a resource, LON-CAPA uses symbols
                   10490: or "symbs"X<symb>. These identifiers are built from the URL of the
                   10491: map, the resource number of the resource in the map, and the URL of
                   10492: the resource itself. The latter is somewhat redundant, but might help
                   10493: if maps change.
                   10494: 
                   10495: An example is
                   10496: 
                   10497:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   10498: 
                   10499: The respective map entry is
                   10500: 
                   10501:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   10502:   title="Problem 2">
                   10503:  </resource>
                   10504: 
                   10505: Symbs are used by the random number generator, as well as to store and
                   10506: restore data specific to a certain instance of for example a problem.
                   10507: 
                   10508: =head2 Storing And Retrieving Data
                   10509: 
                   10510: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   10511: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   10512: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   10513: is is the non-critical message twin of cstore. These functions are for
                   10514: handlers to store a perl hash to a user's permanent data space in an
                   10515: easy manner, and to retrieve it again on another call. It is expected
                   10516: that a handler would use this once at the beginning to retrieve data,
                   10517: and then again once at the end to send only the new data back.
                   10518: 
                   10519: The data is stored in the user's data directory on the user's
                   10520: homeserver under the ID of the course.
                   10521: 
                   10522: The hash that is returned by restore will have all of the previous
                   10523: value for all of the elements of the hash.
                   10524: 
                   10525: Example:
                   10526: 
                   10527:  #creating a hash
                   10528:  my %hash;
                   10529:  $hash{'foo'}='bar';
                   10530: 
                   10531:  #storing it
                   10532:  &Apache::lonnet::cstore(\%hash);
                   10533: 
                   10534:  #changing a value
                   10535:  $hash{'foo'}='notbar';
                   10536: 
                   10537:  #adding a new value
                   10538:  $hash{'bar'}='foo';
                   10539:  &Apache::lonnet::cstore(\%hash);
                   10540: 
                   10541:  #retrieving the hash
                   10542:  my %history=&Apache::lonnet::restore();
                   10543: 
                   10544:  #print the hash
                   10545:  foreach my $key (sort(keys(%history))) {
                   10546:    print("\%history{$key} = $history{$key}");
                   10547:  }
                   10548: 
                   10549: Will print out:
1.191     harris41 10550: 
1.394     bowersj2 10551:  %history{1:foo} = bar
                   10552:  %history{1:keys} = foo:timestamp
                   10553:  %history{1:timestamp} = 990455579
                   10554:  %history{2:bar} = foo
                   10555:  %history{2:foo} = notbar
                   10556:  %history{2:keys} = foo:bar:timestamp
                   10557:  %history{2:timestamp} = 990455580
                   10558:  %history{bar} = foo
                   10559:  %history{foo} = notbar
                   10560:  %history{timestamp} = 990455580
                   10561:  %history{version} = 2
                   10562: 
                   10563: Note that the special hash entries C<keys>, C<version> and
                   10564: C<timestamp> were added to the hash. C<version> will be equal to the
                   10565: total number of versions of the data that have been stored. The
                   10566: C<timestamp> attribute will be the UNIX time the hash was
                   10567: stored. C<keys> is available in every historical section to list which
                   10568: keys were added or changed at a specific historical revision of a
                   10569: hash.
                   10570: 
                   10571: B<Warning>: do not store the hash that restore returns directly. This
                   10572: will cause a mess since it will restore the historical keys as if the
                   10573: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 10574: 
1.394     bowersj2 10575: Calling convention:
1.191     harris41 10576: 
1.394     bowersj2 10577:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   10578:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 10579: 
1.394     bowersj2 10580: For more detailed information, see lonnet specific documentation.
1.191     harris41 10581: 
1.394     bowersj2 10582: =head1 RETURN MESSAGES
1.191     harris41 10583: 
1.394     bowersj2 10584: =over 4
1.191     harris41 10585: 
1.394     bowersj2 10586: =item * B<con_lost>: unable to contact remote host
1.191     harris41 10587: 
1.394     bowersj2 10588: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   10589: when the connection is brought back up
1.191     harris41 10590: 
1.394     bowersj2 10591: =item * B<con_failed>: unable to contact remote host and unable to save message
                   10592: for later delivery
1.191     harris41 10593: 
1.967     bisitz   10594: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 10595: 
1.394     bowersj2 10596: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 10597: that was requested
1.191     harris41 10598: 
1.243     albertel 10599: =back
1.191     harris41 10600: 
1.243     albertel 10601: =head1 PUBLIC SUBROUTINES
1.191     harris41 10602: 
1.243     albertel 10603: =head2 Session Environment Functions
1.191     harris41 10604: 
1.243     albertel 10605: =over 4
1.191     harris41 10606: 
1.394     bowersj2 10607: =item * 
                   10608: X<appenv()>
1.949     raeburn  10609: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 10610: the user envirnoment file, and will be restored for each access this
1.620     albertel 10611: user makes during this session, also modifies the %env for the current
1.949     raeburn  10612: process. Optional rolesarrayref - if defined contains a reference to an array
                   10613: of roles which are exempt from the restriction on modifying user.role entries 
                   10614: in the user's environment.db and in %env.    
1.191     harris41 10615: 
                   10616: =item *
1.394     bowersj2 10617: X<delenv()>
1.987     raeburn  10618: B<delenv($delthis,$regexp)>: removes all items from the session
                   10619: environment file that begin with $delthis. If the 
                   10620: optional second arg - $regexp - is true, $delthis is treated as a 
                   10621: regular expression, otherwise \Q$delthis\E is used. 
                   10622: The values are also deleted from the current processes %env.
1.191     harris41 10623: 
1.795     albertel 10624: =item * get_env_multiple($name) 
                   10625: 
                   10626: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   10627: values may be defined and end up as an array ref.
                   10628: 
                   10629: returns an array of values
                   10630: 
1.243     albertel 10631: =back
                   10632: 
                   10633: =head2 User Information
1.191     harris41 10634: 
1.243     albertel 10635: =over 4
1.191     harris41 10636: 
                   10637: =item *
1.394     bowersj2 10638: X<queryauthenticate()>
                   10639: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 10640: authentication scheme
                   10641: 
                   10642: =item *
1.394     bowersj2 10643: X<authenticate()>
1.1056.4.3  raeburn  10644: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 10645: authenticate user from domain's lib servers (first use the current
                   10646: one). C<$upass> should be the users password.
1.1056.4.3  raeburn  10647: $checkdefauth is optional (value is 1 if a check should be made to
                   10648:    authenticate user using default authentication method, and allow
                   10649:    account creation if username does not have account in the domain).
                   10650: $clientcancheckhost is optional (value is 1 if checking whether the
                   10651:    server can host will occur on the client side in lonauth.pm).
1.191     harris41 10652: 
                   10653: =item *
1.394     bowersj2 10654: X<homeserver()>
                   10655: B<homeserver($uname,$udom)>: find the server which has
                   10656: the user's directory and files (there must be only one), this caches
                   10657: the answer, and also caches if there is a borken connection.
1.191     harris41 10658: 
                   10659: =item *
1.394     bowersj2 10660: X<idget()>
                   10661: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   10662: (IDs are a unique resource in a domain, there must be only 1 ID per
                   10663: username, and only 1 username per ID in a specific domain) (returns
                   10664: hash: id=>name,id=>name)
1.191     harris41 10665: 
                   10666: =item *
1.394     bowersj2 10667: X<idrget()>
                   10668: B<idrget($udom,@unames)>: find the IDs behind a list of
                   10669: usernames (returns hash: name=>id,name=>id)
1.191     harris41 10670: 
                   10671: =item *
1.394     bowersj2 10672: X<idput()>
                   10673: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 10674: 
                   10675: =item *
1.394     bowersj2 10676: X<rolesinit()>
                   10677: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 10678: 
                   10679: =item *
1.551     albertel 10680: X<getsection()>
                   10681: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 10682: course $cname, return section name/number or '' for "not in course"
                   10683: and '-1' for "no section"
                   10684: 
                   10685: =item *
1.394     bowersj2 10686: X<userenvironment()>
                   10687: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 10688: passed in @what from the requested user's environment, returns a hash
                   10689: 
1.858     raeburn  10690: =item * 
                   10691: X<userlog_query()>
1.859     albertel 10692: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   10693: activity.log file. %filters defines filters applied when parsing the
                   10694: log file. These can be start or end timestamps, or the type of action
                   10695: - log to look for Login or Logout events, check for Checkin or
                   10696: Checkout, role for role selection. The response is in the form
                   10697: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   10698: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  10699: 
1.243     albertel 10700: =back
                   10701: 
                   10702: =head2 User Roles
                   10703: 
                   10704: =over 4
                   10705: 
                   10706: =item *
                   10707: 
1.810     raeburn  10708: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 10709:  F: full access
                   10710:  U,I,K: authentication modes (cxx only)
                   10711:  '': forbidden
                   10712:  1: user needs to choose course
                   10713:  2: browse allowed
1.766     albertel 10714:  A: passphrase authentication needed
1.243     albertel 10715: 
                   10716: =item *
                   10717: 
                   10718: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   10719: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   10720: and course level
                   10721: 
                   10722: =item *
                   10723: 
1.988     raeburn  10724: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   10725: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  10726: $type is Course (default) or Community.
1.988     raeburn  10727: If $forcedefault evaluates to true, text returned will be default 
                   10728: text for $type. Otherwise, if this is a course, the text returned 
                   10729: will be a custom name for the role (if defined in the course's 
                   10730: environment).  If no custom name is defined the default is returned.
                   10731:    
1.832     raeburn  10732: =item *
                   10733: 
1.935     raeburn  10734: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  10735: All arguments are optional. Returns a hash of a roles, either for
                   10736: co-author/assistant author roles for a user's Construction Space
1.906     albertel 10737: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  10738: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   10739: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   10740: For each key, value is set to colon-separated start and end times for
                   10741: the role.  If no username and domain are specified, will default to
1.934     raeburn  10742: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  10743: of role statuses (active, future or previous), roles 
                   10744: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   10745: to restrict the list of roles reported. If no array ref is 
                   10746: provided for types, will default to return only active roles.
1.834     albertel 10747: 
1.243     albertel 10748: =back
                   10749: 
                   10750: =head2 User Modification
                   10751: 
                   10752: =over 4
                   10753: 
                   10754: =item *
                   10755: 
1.957     raeburn  10756: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 10757: user for the level given by URL.  Optional start and end dates (leave empty
                   10758: string or zero for "no date")
1.191     harris41 10759: 
                   10760: =item *
                   10761: 
1.243     albertel 10762: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   10763: change a users, password, possible return values are: ok,
                   10764: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   10765: refused
1.191     harris41 10766: 
                   10767: =item *
                   10768: 
1.243     albertel 10769: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 10770: 
                   10771: =item *
                   10772: 
1.1056.4.1  raeburn  10773: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   10774:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   10775: 
                   10776: will update user information (firstname,middlename,lastname,generation,
                   10777: permanentemail), and if forceid is true, student/employee ID also.
                   10778: A user's institutional affiliation(s) can also be updated.
                   10779: User information fields will not be overwritten with empty entries 
                   10780: unless the field is included in the $candelete array reference.
                   10781: This array is included when a single user is modified via "Manage Users",
                   10782: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 10783: 
                   10784: =item *
                   10785: 
1.286     matthew  10786: modifystudent
                   10787: 
1.957     raeburn  10788: modify a student's enrollment and identification information.
1.286     matthew  10789: The course id is resolved based on the current users environment.  
                   10790: This means the envoking user must be a course coordinator or otherwise
                   10791: associated with a course.
                   10792: 
1.297     matthew  10793: This call is essentially a wrapper for lonnet::modifyuser and
                   10794: lonnet::modify_student_enrollment
1.286     matthew  10795: 
                   10796: Inputs: 
                   10797: 
                   10798: =over 4
                   10799: 
1.957     raeburn  10800: =item B<$udom> Student's loncapa domain
1.286     matthew  10801: 
1.957     raeburn  10802: =item B<$uname> Student's loncapa login name
1.286     matthew  10803: 
1.964     bisitz   10804: =item B<$uid> Student/Employee ID
1.286     matthew  10805: 
1.957     raeburn  10806: =item B<$umode> Student's authentication mode
1.286     matthew  10807: 
1.957     raeburn  10808: =item B<$upass> Student's password
1.286     matthew  10809: 
1.957     raeburn  10810: =item B<$first> Student's first name
1.286     matthew  10811: 
1.957     raeburn  10812: =item B<$middle> Student's middle name
1.286     matthew  10813: 
1.957     raeburn  10814: =item B<$last> Student's last name
1.286     matthew  10815: 
1.957     raeburn  10816: =item B<$gene> Student's generation
1.286     matthew  10817: 
1.957     raeburn  10818: =item B<$usec> Student's section in course
1.286     matthew  10819: 
                   10820: =item B<$end> Unix time of the roles expiration
                   10821: 
                   10822: =item B<$start> Unix time of the roles start date
                   10823: 
                   10824: =item B<$forceid> If defined, allow $uid to be changed
                   10825: 
                   10826: =item B<$desiredhome> server to use as home server for student
                   10827: 
1.957     raeburn  10828: =item B<$email> Student's permanent e-mail address
                   10829: 
                   10830: =item B<$type> Type of enrollment (auto or manual)
                   10831: 
1.963     raeburn  10832: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   10833: 
                   10834: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  10835: 
1.963     raeburn  10836: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  10837: 
1.963     raeburn  10838: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  10839: 
1.963     raeburn  10840: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  10841: 
1.286     matthew  10842: =back
1.297     matthew  10843: 
                   10844: =item *
                   10845: 
                   10846: modify_student_enrollment
                   10847: 
                   10848: Change a students enrollment status in a class.  The environment variable
                   10849: 'role.request.course' must be defined for this function to proceed.
                   10850: 
                   10851: Inputs:
                   10852: 
                   10853: =over 4
                   10854: 
                   10855: =item $udom, students domain
                   10856: 
                   10857: =item $uname, students name
                   10858: 
                   10859: =item $uid, students user id
                   10860: 
                   10861: =item $first, students first name
                   10862: 
                   10863: =item $middle
                   10864: 
                   10865: =item $last
                   10866: 
                   10867: =item $gene
                   10868: 
                   10869: =item $usec
                   10870: 
                   10871: =item $end
                   10872: 
                   10873: =item $start
                   10874: 
1.957     raeburn  10875: =item $type
                   10876: 
                   10877: =item $locktype
                   10878: 
                   10879: =item $cid
                   10880: 
                   10881: =item $selfenroll
                   10882: 
                   10883: =item $context
                   10884: 
1.297     matthew  10885: =back
                   10886: 
1.191     harris41 10887: 
                   10888: =item *
                   10889: 
1.243     albertel 10890: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   10891: custom role; give a custom role to a user for the level given by URL.  Specify
                   10892: name and domain of role author, and role name
1.191     harris41 10893: 
                   10894: =item *
                   10895: 
1.243     albertel 10896: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 10897: 
                   10898: =item *
                   10899: 
1.243     albertel 10900: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   10901: 
                   10902: =back
                   10903: 
                   10904: =head2 Course Infomation
                   10905: 
                   10906: =over 4
1.191     harris41 10907: 
                   10908: =item *
                   10909: 
1.631     albertel 10910: coursedescription($courseid) : returns a hash of information about the
                   10911: specified course id, including all environment settings for the
                   10912: course, the description of the course will be in the hash under the
                   10913: key 'description'
1.191     harris41 10914: 
                   10915: =item *
                   10916: 
1.624     albertel 10917: resdata($name,$domain,$type,@which) : request for current parameter
                   10918: setting for a specific $type, where $type is either 'course' or 'user',
                   10919: @what should be a list of parameters to ask about. This routine caches
                   10920: answers for 5 minutes.
1.243     albertel 10921: 
1.877     foxr     10922: =item *
                   10923: 
                   10924: get_courseresdata($courseid, $domain) : dump the entire course resource
                   10925: data base, returning a hash that is keyed by the resource name and has
                   10926: values that are the resource value.  I believe that the timestamps and
                   10927: versions are also returned.
                   10928: 
                   10929: 
1.243     albertel 10930: =back
                   10931: 
                   10932: =head2 Course Modification
                   10933: 
                   10934: =over 4
1.191     harris41 10935: 
                   10936: =item *
                   10937: 
1.243     albertel 10938: writecoursepref($courseid,%prefs) : write preferences (environment
                   10939: database) for a course
1.191     harris41 10940: 
                   10941: =item *
                   10942: 
1.1011    raeburn  10943: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   10944: 
                   10945: =item *
                   10946: 
1.1038    raeburn  10947: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 10948: 
                   10949: =back
                   10950: 
                   10951: =head2 Resource Subroutines
                   10952: 
                   10953: =over 4
1.191     harris41 10954: 
                   10955: =item *
                   10956: 
1.243     albertel 10957: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 10958: 
                   10959: =item *
                   10960: 
1.243     albertel 10961: repcopy($filename) : subscribes to the requested file, and attempts to
                   10962: replicate from the owning library server, Might return
1.607     raeburn  10963: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   10964: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 10965: resource. Expects the local filesystem pathname
                   10966: (/home/httpd/html/res/....)
                   10967: 
                   10968: =back
                   10969: 
                   10970: =head2 Resource Information
                   10971: 
                   10972: =over 4
1.191     harris41 10973: 
                   10974: =item *
                   10975: 
1.243     albertel 10976: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   10977: a vairety of different possible values, $varname should be a request
                   10978: string, and the other parameters can be used to specify who and what
                   10979: one is asking about.
                   10980: 
                   10981: Possible values for $varname are environment.lastname (or other item
                   10982: from the envirnment hash), user.name (or someother aspect about the
                   10983: user), resource.0.maxtries (or some other part and parameter of a
                   10984: resource)
1.204     albertel 10985: 
                   10986: =item *
                   10987: 
1.243     albertel 10988: directcondval($number) : get current value of a condition; reads from a state
                   10989: string
1.204     albertel 10990: 
                   10991: =item *
                   10992: 
1.243     albertel 10993: condval($condidx) : value of condition index based on state
1.204     albertel 10994: 
                   10995: =item *
                   10996: 
1.243     albertel 10997: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   10998: resource's metadata, $what should be either a specific key, or either
                   10999: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   11000: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   11001: 
                   11002: this function automatically caches all requests
1.191     harris41 11003: 
                   11004: =item *
                   11005: 
1.243     albertel 11006: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   11007: network of library servers; returns file handle of where SQL and regex results
                   11008: will be stored for query
1.191     harris41 11009: 
                   11010: =item *
                   11011: 
1.243     albertel 11012: symbread($filename) : return symbolic list entry (filename argument optional);
                   11013: returns the data handle
1.191     harris41 11014: 
                   11015: =item *
                   11016: 
1.243     albertel 11017: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 11018: a possible symb for the URL in $thisfn, and if is an encryypted
                   11019: resource that the user accessed using /enc/ returns a 1 on success, 0
                   11020: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 11021: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 11022: 
1.191     harris41 11023: 
                   11024: =item *
                   11025: 
1.243     albertel 11026: symbclean($symb) : removes versions numbers from a symb, returns the
                   11027: cleaned symb
1.191     harris41 11028: 
                   11029: =item *
                   11030: 
1.243     albertel 11031: is_on_map($uri) : checks if the $uri is somewhere on the current
                   11032: course map, user must be in a course for it to work.
1.191     harris41 11033: 
                   11034: =item *
                   11035: 
1.243     albertel 11036: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 11037: 
                   11038: =item *
                   11039: 
1.243     albertel 11040: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   11041: a random seed, all arguments are optional, if they aren't sent it uses the
                   11042: environment to derive them. Note: if symb isn't sent and it can't get one
                   11043: from &symbread it will use the current time as its return value
1.191     harris41 11044: 
                   11045: =item *
                   11046: 
1.243     albertel 11047: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   11048: unfakeable, receipt
1.191     harris41 11049: 
                   11050: =item *
                   11051: 
1.620     albertel 11052: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 11053: 
                   11054: =item *
                   11055: 
1.243     albertel 11056: countacc($url) : count the number of accesses to a given URL
1.191     harris41 11057: 
                   11058: =item *
                   11059: 
1.243     albertel 11060: 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 11061: 
                   11062: =item *
                   11063: 
1.243     albertel 11064: 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 11065: 
                   11066: =item *
                   11067: 
1.243     albertel 11068: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 11069: 
                   11070: =item *
                   11071: 
1.243     albertel 11072: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   11073: forcing spreadsheet to reevaluate the resource scores next time.
                   11074: 
                   11075: =back
                   11076: 
                   11077: =head2 Storing/Retreiving Data
                   11078: 
                   11079: =over 4
1.191     harris41 11080: 
                   11081: =item *
                   11082: 
1.243     albertel 11083: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   11084: for this url; hashref needs to be given and should be a \%hashname; the
                   11085: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 11086: be derived from the env
1.191     harris41 11087: 
                   11088: =item *
                   11089: 
1.243     albertel 11090: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   11091: uses critical subroutine
1.191     harris41 11092: 
                   11093: =item *
                   11094: 
1.243     albertel 11095: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   11096: all args are optional
1.191     harris41 11097: 
                   11098: =item *
                   11099: 
1.717     albertel 11100: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   11101: dumps the complete (or key matching regexp) namespace into a hash
                   11102: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   11103: normally &store()ed into
                   11104: 
                   11105: $range should be either an integer '100' (give me the first 100
                   11106:                                            matching records)
                   11107:               or be  two integers sperated by a - with no spaces
                   11108:                  '30-50' (give me the 30th through the 50th matching
                   11109:                           records)
                   11110: 
                   11111: 
                   11112: =item *
                   11113: 
                   11114: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   11115: replaces a &store() version of data with a replacement set of data
                   11116: for a particular resource in a namespace passed in the $storehash hash 
                   11117: reference
                   11118: 
                   11119: =item *
                   11120: 
1.243     albertel 11121: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   11122: works very similar to store/cstore, but all data is stored in a
                   11123: temporary location and can be reset using tmpreset, $storehash should
                   11124: be a hash reference, returns nothing on success
1.191     harris41 11125: 
                   11126: =item *
                   11127: 
1.243     albertel 11128: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   11129: similar to restore, but all data is stored in a temporary location and
                   11130: can be reset using tmpreset. Returns a hash of values on success,
                   11131: error string otherwise.
1.191     harris41 11132: 
                   11133: =item *
                   11134: 
1.243     albertel 11135: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   11136: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 11137: 
                   11138: =item *
                   11139: 
1.243     albertel 11140: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11141: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 11142: 
                   11143: =item *
                   11144: 
1.243     albertel 11145: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   11146: namesp ($udom and $uname are optional)
1.191     harris41 11147: 
                   11148: =item *
                   11149: 
1.702     albertel 11150: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 11151: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 11152: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  11153: 
1.702     albertel 11154: $range should be either an integer '100' (give me the first 100
                   11155:                                            matching records)
                   11156:               or be  two integers sperated by a - with no spaces
                   11157:                  '30-50' (give me the 30th through the 50th matching
                   11158:                           records)
1.449     matthew  11159: =item *
                   11160: 
                   11161: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   11162: $store can be a scalar, an array reference, or if the amount to be 
                   11163: incremented is > 1, a hash reference.
                   11164: 
                   11165: ($udom and $uname are optional)
1.191     harris41 11166: 
                   11167: =item *
                   11168: 
1.243     albertel 11169: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   11170: ($udom and $uname are optional)
1.191     harris41 11171: 
                   11172: =item *
                   11173: 
1.243     albertel 11174: cput($namespace,$storehash,$udom,$uname) : critical put
                   11175: ($udom and $uname are optional)
1.191     harris41 11176: 
                   11177: =item *
                   11178: 
1.748     albertel 11179: newput($namespace,$storehash,$udom,$uname) :
                   11180: 
                   11181: Attempts to store the items in the $storehash, but only if they don't
                   11182: currently exist, if this succeeds you can be certain that you have 
                   11183: successfully created a new key value pair in the $namespace db.
                   11184: 
                   11185: 
                   11186: Args:
                   11187:  $namespace: name of database to store values to
                   11188:  $storehash: hashref to store to the db
                   11189:  $udom: (optional) domain of user containing the db
                   11190:  $uname: (optional) name of user caontaining the db
                   11191: 
                   11192: Returns:
                   11193:  'ok' -> succeeded in storing all keys of $storehash
                   11194:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   11195:                         least <key> already existed in the db (other
                   11196:                         requested keys may also already exist)
1.967     bisitz   11197:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 11198:  'con_lost' -> unable to contact request server
                   11199:  'refused' -> action was not allowed by remote machine
                   11200: 
                   11201: 
                   11202: =item *
                   11203: 
1.243     albertel 11204: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11205: reference filled in from namesp (encrypts the return communication)
                   11206: ($udom and $uname are optional)
1.191     harris41 11207: 
                   11208: =item *
                   11209: 
1.243     albertel 11210: log($udom,$name,$home,$message) : write to permanent log for user; use
                   11211: critical subroutine
                   11212: 
1.806     raeburn  11213: =item *
                   11214: 
1.860     raeburn  11215: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   11216: array reference filled in from namespace found in domain level on either
                   11217: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  11218: 
                   11219: =item *
                   11220: 
1.860     raeburn  11221: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   11222: domain level either on specified domain server ($uhome) or primary domain 
                   11223: server ($udom and $uhome are optional)
1.806     raeburn  11224: 
1.943     raeburn  11225: =item * 
                   11226: 
                   11227: get_domain_defaults($target_domain) : returns hash with defaults for
                   11228: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   11229: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   11230: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   11231: Values are retrieved from cache (if current), or from domain's configuration.db
                   11232: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   11233: or lonTabs/domain.tab. 
                   11234: 
                   11235: %domdefaults = &get_auth_defaults($target_domain);
                   11236: 
1.243     albertel 11237: =back
                   11238: 
                   11239: =head2 Network Status Functions
                   11240: 
                   11241: =over 4
1.191     harris41 11242: 
                   11243: =item *
                   11244: 
                   11245: dirlist($uri) : return directory list based on URI
                   11246: 
                   11247: =item *
                   11248: 
1.243     albertel 11249: spareserver() : find server with least workload from spare.tab
                   11250: 
1.986     foxr     11251: 
                   11252: =item *
                   11253: 
                   11254: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   11255: if there is no corresponding loncapa host.
                   11256: 
1.243     albertel 11257: =back
                   11258: 
1.986     foxr     11259: 
1.243     albertel 11260: =head2 Apache Request
                   11261: 
                   11262: =over 4
1.191     harris41 11263: 
                   11264: =item *
                   11265: 
1.243     albertel 11266: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   11267: localhost, posts hash
                   11268: 
                   11269: =back
                   11270: 
                   11271: =head2 Data to String to Data
                   11272: 
                   11273: =over 4
1.191     harris41 11274: 
                   11275: =item *
                   11276: 
1.243     albertel 11277: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   11278: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 11279: 
                   11280: =item *
                   11281: 
1.243     albertel 11282: hashref2str($hashref) : convert a hashref into a string complete with
                   11283: escaping and '=' and '&' separators, supports elements that are
                   11284: arrayrefs and hashrefs
1.191     harris41 11285: 
                   11286: =item *
                   11287: 
1.243     albertel 11288: arrayref2str($arrayref) : convert an arrayref into a string complete
                   11289: with escaping and '&' separators, supports elements that are arrayrefs
                   11290: and hashrefs
1.191     harris41 11291: 
                   11292: =item *
                   11293: 
1.243     albertel 11294: str2hash($string) : convert string to hash using unescaping and
                   11295: splitting on '=' and '&', supports elements that are arrayrefs and
                   11296: hashrefs
1.191     harris41 11297: 
                   11298: =item *
                   11299: 
1.243     albertel 11300: str2array($string) : convert string to hash using unescaping and
                   11301: splitting on '&', supports elements that are arrayrefs and hashrefs
                   11302: 
                   11303: =back
                   11304: 
                   11305: =head2 Logging Routines
                   11306: 
                   11307: =over 4
                   11308: 
                   11309: These routines allow one to make log messages in the lonnet.log and
                   11310: lonnet.perm logfiles.
1.191     harris41 11311: 
                   11312: =item *
                   11313: 
1.243     albertel 11314: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 11315: 
                   11316: =item *
                   11317: 
1.243     albertel 11318: logthis() : append message to the normal lonnet.log file, it gets
                   11319: preiodically rolled over and deleted.
1.191     harris41 11320: 
                   11321: =item *
                   11322: 
1.243     albertel 11323: logperm() : append a permanent message to lonnet.perm.log, this log
                   11324: file never gets deleted by any automated portion of the system, only
                   11325: messages of critical importance should go in here.
                   11326: 
                   11327: =back
                   11328: 
                   11329: =head2 General File Helper Routines
                   11330: 
                   11331: =over 4
1.191     harris41 11332: 
                   11333: =item *
                   11334: 
1.481     raeburn  11335: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   11336: (a) files in /uploaded
                   11337:   (i) If a local copy of the file exists - 
                   11338:       compares modification date of local copy with last-modified date for 
                   11339:       definitive version stored on home server for course. If local copy is 
                   11340:       stale, requests a new version from the home server and stores it. 
                   11341:       If the original has been removed from the home server, then local copy 
                   11342:       is unlinked.
                   11343:   (ii) If local copy does not exist -
                   11344:       requests the file from the home server and stores it. 
                   11345:   
                   11346:   If $caller is 'uploadrep':  
                   11347:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   11348:     for request for files originally uploaded via DOCS. 
                   11349:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   11350:   
                   11351:   Otherwise:
                   11352:      This indicates a call from the content generation phase of the request.
                   11353:      -  returns the entire contents of the file or -1.
                   11354:      
                   11355: (b) files in /res
                   11356:    - returns the entire contents of a file or -1; 
                   11357:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 11358: 
1.712     albertel 11359: 
                   11360: =item *
                   11361: 
                   11362: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   11363:                   reference
                   11364: 
                   11365: returns either a stat() list of data about the file or an empty list
                   11366: if the file doesn't exist or couldn't find out about it (connection
                   11367: problems or user unknown)
                   11368: 
1.191     harris41 11369: =item *
                   11370: 
1.243     albertel 11371: filelocation($dir,$file) : returns file system location of a file
                   11372: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   11373: directory that relative $file lookups are to looked in ($dir of /a/dir
                   11374: and a file of ../bob will become /a/bob)
1.191     harris41 11375: 
                   11376: =item *
                   11377: 
                   11378: hreflocation($dir,$file) : returns file system location or a URL; same as
                   11379: filelocation except for hrefs
                   11380: 
                   11381: =item *
                   11382: 
                   11383: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   11384: 
1.243     albertel 11385: =back
                   11386: 
1.608     albertel 11387: =head2 Usererfile file routines (/uploaded*)
                   11388: 
                   11389: =over 4
                   11390: 
                   11391: =item *
                   11392: 
                   11393: userfileupload(): main rotine for putting a file in a user or course's
                   11394:                   filespace, arguments are,
                   11395: 
1.620     albertel 11396:  formname - required - this is the name of the element in $env where the
1.608     albertel 11397:            filename, and the contents of the file to create/modifed exist
1.620     albertel 11398:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   11399:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 11400:  coursedoc - if true, store the file in the course of the active role
                   11401:              of the current user
                   11402:  subdir - required - subdirectory to put the file in under ../userfiles/
                   11403:          if undefined, it will be placed in "unknown"
                   11404: 
                   11405:  (This routine calls clean_filename() to remove any dangerous
                   11406:  characters from the filename, and then calls finuserfileupload() to
                   11407:  complete the transaction)
                   11408: 
                   11409:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11410:  and /adm/notfound.html if unsuccessful
                   11411: 
                   11412: =item *
                   11413: 
                   11414: clean_filename(): routine for cleaing a filename up for storage in
                   11415:                  userfile space, argument is:
                   11416: 
                   11417:  filename - proposed filename
                   11418: 
                   11419: returns: the new clean filename
                   11420: 
                   11421: =item *
                   11422: 
                   11423: finishuserfileupload(): routine that creaes and sends the file to
                   11424: userspace, probably shouldn't be called directly
                   11425: 
                   11426:   docuname: username or courseid of destination for the file
                   11427:   docudom: domain of user/course of destination for the file
                   11428:   formname: same as for userfileupload()
                   11429:   fname: filename (inculding subdirectories) for the file
                   11430: 
                   11431:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11432:  and /adm/notfound.html if unsuccessful
                   11433: 
                   11434: =item *
                   11435: 
                   11436: renameuserfile(): renames an existing userfile to a new name
                   11437: 
                   11438:   Args:
                   11439:    docuname: username or courseid of destination for the file
                   11440:    docudom: domain of user/course of destination for the file
                   11441:    old: current file name (including any subdirs under userfiles)
                   11442:    new: desired file name (including any subdirs under userfiles)
                   11443: 
                   11444: =item *
                   11445: 
                   11446: mkdiruserfile(): creates a directory is a userfiles dir
                   11447: 
                   11448:   Args:
                   11449:    docuname: username or courseid of destination for the file
                   11450:    docudom: domain of user/course of destination for the file
                   11451:    dir: dir to create (including any subdirs under userfiles)
                   11452: 
                   11453: =item *
                   11454: 
                   11455: removeuserfile(): removes a file that exists in userfiles
                   11456: 
                   11457:   Args:
                   11458:    docuname: username or courseid of destination for the file
                   11459:    docudom: domain of user/course of destination for the file
                   11460:    fname: filname to delete (including any subdirs under userfiles)
                   11461: 
                   11462: =item *
                   11463: 
                   11464: removeuploadedurl(): convience function for removeuserfile()
                   11465: 
                   11466:   Args:
                   11467:    url:  a full /uploaded/... url to delete
                   11468: 
1.747     albertel 11469: =item * 
                   11470: 
                   11471: get_portfile_permissions():
                   11472:   Args:
                   11473:     domain: domain of user or course contain the portfolio files
                   11474:     user: name of user or num of course contain the portfolio files
                   11475:   Returns:
                   11476:     hashref of a dump of the proper file_permissions.db
                   11477:    
                   11478: 
                   11479: =item * 
                   11480: 
                   11481: get_access_controls():
                   11482: 
                   11483: Args:
                   11484:   current_permissions: the hash ref returned from get_portfile_permissions()
                   11485:   group: (optional) the group you want the files associated with
                   11486:   file: (optional) the file you want access info on
                   11487: 
                   11488: Returns:
1.749     raeburn  11489:     a hash (keys are file names) of hashes containing
                   11490:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   11491:         values are XML containing access control settings (see below) 
1.747     albertel 11492: 
                   11493: Internal notes:
                   11494: 
1.749     raeburn  11495:  access controls are stored in file_permissions.db as key=value pairs.
                   11496:     key -> path to file/file_name\0uniqueID:scope_end_start
                   11497:         where scope -> public,guest,course,group,domains or users.
                   11498:               end -> UNIX time for end of access (0 -> no end date)
                   11499:               start -> UNIX time for start of access
                   11500: 
                   11501:     value -> XML description of access control
                   11502:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   11503:             <start></start>
                   11504:             <end></end>
                   11505: 
                   11506:             <password></password>  for scope type = guest
                   11507: 
                   11508:             <domain></domain>     for scope type = course or group
                   11509:             <number></number>
                   11510:             <roles id="">
                   11511:              <role></role>
                   11512:              <access></access>
                   11513:              <section></section>
                   11514:              <group></group>
                   11515:             </roles>
                   11516: 
                   11517:             <dom></dom>         for scope type = domains
                   11518: 
                   11519:             <users>             for scope type = users
                   11520:              <user>
                   11521:               <uname></uname>
                   11522:               <udom></udom>
                   11523:              </user>
                   11524:             </users>
                   11525:            </scope> 
                   11526:               
                   11527:  Access data is also aggregated for each file in an additional key=value pair:
                   11528:  key -> path to file/file_name\0accesscontrol 
                   11529:  value -> reference to hash
                   11530:           hash contains key = value pairs
                   11531:           where key = uniqueID:scope_end_start
                   11532:                 value = UNIX time record was last updated
                   11533: 
                   11534:           Used to improve speed of look-ups of access controls for each file.  
                   11535:  
                   11536:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   11537: 
                   11538: modify_access_controls():
                   11539: 
                   11540: Modifies access controls for a portfolio file
                   11541: Args
                   11542: 1. file name
                   11543: 2. reference to hash of required changes,
                   11544: 3. domain
                   11545: 4. username
                   11546:   where domain,username are the domain of the portfolio owner 
                   11547:   (either a user or a course) 
                   11548: 
                   11549: Returns:
                   11550: 1. result of additions or updates ('ok' or 'error', with error message). 
                   11551: 2. result of deletions ('ok' or 'error', with error message).
                   11552: 3. reference to hash of any new or updated access controls.
                   11553: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   11554:    key = integer (inbound ID)
                   11555:    value = uniqueID  
1.747     albertel 11556: 
1.608     albertel 11557: =back
                   11558: 
1.243     albertel 11559: =head2 HTTP Helper Routines
                   11560: 
                   11561: =over 4
                   11562: 
1.191     harris41 11563: =item *
                   11564: 
                   11565: escape() : unpack non-word characters into CGI-compatible hex codes
                   11566: 
                   11567: =item *
                   11568: 
                   11569: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   11570: 
1.243     albertel 11571: =back
                   11572: 
                   11573: =head1 PRIVATE SUBROUTINES
                   11574: 
                   11575: =head2 Underlying communication routines (Shouldn't call)
                   11576: 
                   11577: =over 4
                   11578: 
                   11579: =item *
                   11580: 
                   11581: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   11582: 
                   11583: =item *
                   11584: 
                   11585: reply() : uses subreply to send a message to remote machine, logs all failures
                   11586: 
                   11587: =item *
                   11588: 
                   11589: critical() : passes a critical message to another server; if cannot
                   11590: get through then place message in connection buffer directory and
                   11591: returns con_delayed, if incapable of saving message, returns
                   11592: con_failed
                   11593: 
                   11594: =item *
                   11595: 
                   11596: reconlonc() : tries to reconnect lonc client processes.
                   11597: 
                   11598: =back
                   11599: 
                   11600: =head2 Resource Access Logging
                   11601: 
                   11602: =over 4
                   11603: 
                   11604: =item *
                   11605: 
                   11606: flushcourselogs() : flush (save) buffer logs and access logs
                   11607: 
                   11608: =item *
                   11609: 
                   11610: courselog($what) : save message for course in hash
                   11611: 
                   11612: =item *
                   11613: 
                   11614: courseacclog($what) : save message for course using &courselog().  Perform
                   11615: special processing for specific resource types (problems, exams, quizzes, etc).
                   11616: 
1.191     harris41 11617: =item *
                   11618: 
                   11619: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   11620: as a PerlChildExitHandler
1.243     albertel 11621: 
                   11622: =back
                   11623: 
                   11624: =head2 Other
                   11625: 
                   11626: =over 4
                   11627: 
                   11628: =item *
                   11629: 
                   11630: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 11631: 
                   11632: =back
                   11633: 
                   11634: =cut
1.877     foxr     11635: 

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