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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1159  ! www         4: # $Id: lonnet.pm,v 1.1158 2012/03/14 20:53:50 www 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.1138    raeburn    79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     80:             %managerstab);
1.871     albertel   81: 
                     82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        85:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        86: 
1.1       albertel   87: use IO::Socket;
1.31      www        88: use GDBM_File;
1.208     albertel   89: use HTML::LCParser;
1.88      www        90: use Fcntl qw(:flock);
1.870     albertel   91: use Storable qw(thaw nfreeze);
1.539     albertel   92: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   93: use Cache::Memcached;
1.676     albertel   94: use Digest::MD5;
1.790     albertel   95: use Math::Random;
1.1024    raeburn    96: use File::MMagic;
1.807     albertel   97: use LONCAPA qw(:DEFAULT :match);
1.740     www        98: use LONCAPA::Configuration;
1.1117    foxr       99: 
1.1090    raeburn   100: use File::Copy;
1.676     albertel  101: 
1.195     www       102: my $readit;
1.550     foxr      103: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  104: 
1.619     albertel  105: require Exporter;
                    106: 
                    107: our @ISA = qw (Exporter);
                    108: our @EXPORT = qw(%env);
                    109: 
1.449     matthew   110: 
1.1       albertel  111: # --------------------------------------------------------------------- Logging
1.729     www       112: {
                    113:     my $logid;
                    114:     sub instructor_log {
1.957     raeburn   115: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    116:         if (($cnum eq '') || ($cdom eq '')) {
                    117:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    118:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    119:         }
1.729     www       120: 	$logid++;
1.957     raeburn   121:         my $now = time();
                    122: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       123: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       124: 				    { $id => {
                    125: 					'exe_uname' => $env{'user.name'},
                    126: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   127: 					'exe_time'  => $now,
1.730     www       128: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    129: 					'delflag'   => $delflag,
                    130: 					'logentry'  => $storehash,
                    131: 					'uname'     => $uname,
                    132: 					'udom'      => $udom,
                    133: 				    }
1.957     raeburn   134: 				  },$cdom,$cnum);
1.729     www       135:     }
                    136: }
1.1       albertel  137: 
1.163     harris41  138: sub logtouch {
                    139:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  140:     unless (-e "$execdir/logs/lonnet.log") {	
                    141: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  142: 	close $fh;
                    143:     }
                    144:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    145:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    146: }
                    147: 
1.1       albertel  148: sub logthis {
                    149:     my $message=shift;
                    150:     my $execdir=$perlvar{'lonDaemons'};
                    151:     my $now=time;
                    152:     my $local=localtime($now);
1.448     albertel  153:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      154: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    155: 	print $fh $logstring;
1.448     albertel  156: 	close($fh);
                    157:     }
1.1       albertel  158:     return 1;
                    159: }
                    160: 
                    161: sub logperm {
                    162:     my $message=shift;
                    163:     my $execdir=$perlvar{'lonDaemons'};
                    164:     my $now=time;
                    165:     my $local=localtime($now);
1.448     albertel  166:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    167: 	print $fh "$now:$message:$local\n";
                    168: 	close($fh);
                    169:     }
1.1       albertel  170:     return 1;
                    171: }
                    172: 
1.850     albertel  173: sub create_connection {
1.853     albertel  174:     my ($hostname,$lonid) = @_;
1.851     albertel  175:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  176: 				     Type    => SOCK_STREAM,
                    177: 				     Timeout => 10);
                    178:     return 0 if (!$client);
1.890     albertel  179:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  180:     my $result = <$client>;
                    181:     chomp($result);
                    182:     return 1 if ($result eq 'done');
                    183:     return 0;
                    184: }
                    185: 
1.983     raeburn   186: sub get_server_timezone {
                    187:     my ($cnum,$cdom) = @_;
                    188:     my $home=&homeserver($cnum,$cdom);
                    189:     if ($home ne 'no_host') {
                    190:         my $cachetime = 24*3600;
                    191:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    192:         if (defined($cached)) {
                    193:             return $timezone;
                    194:         } else {
                    195:             my $timezone = &reply('servertimezone',$home);
                    196:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    197:         }
                    198:     }
                    199: }
1.850     albertel  200: 
1.1106    raeburn   201: sub get_server_distarch {
                    202:     my ($lonhost,$ignore_cache) = @_;
                    203:     if (defined($lonhost)) {
                    204:         if (!defined(&hostname($lonhost))) {
                    205:             return;
                    206:         }
                    207:         my $cachetime = 12*3600;
                    208:         if (!$ignore_cache) {
                    209:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    210:             if (defined($cached)) {
                    211:                 return $distarch;
                    212:             }
                    213:         }
                    214:         my $rep = &reply('serverdistarch',$lonhost);
                    215:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    216:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    217:                 $rep eq '') {
                    218:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    219:         }
                    220:     }
                    221:     return;
                    222: }
                    223: 
1.993     raeburn   224: sub get_server_loncaparev {
1.1073    raeburn   225:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   226:     if (defined($lonhost)) {
                    227:         if (!defined(&hostname($lonhost))) {
                    228:             undef($lonhost);
                    229:         }
                    230:     }
                    231:     if (!defined($lonhost)) {
                    232:         if (defined(&domain($dom,'primary'))) {
                    233:             $lonhost=&domain($dom,'primary');
                    234:             if ($lonhost eq 'no_host') {
                    235:                 undef($lonhost);
                    236:             }
                    237:         }
                    238:     }
                    239:     if (defined($lonhost)) {
1.1073    raeburn   240:         my $cachetime = 12*3600;
                    241:         if (!$ignore_cache) {
                    242:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    243:             if (defined($cached)) {
                    244:                 return $loncaparev;
                    245:             }
                    246:         }
                    247:         my ($answer,$loncaparev);
                    248:         my @ids=&current_machine_ids();
                    249:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    250:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   251:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   252:                 $loncaparev = $1;
                    253:             }
                    254:         } else {
                    255:             $answer = &reply('serverloncaparev',$lonhost);
                    256:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    257:                 if ($caller eq 'loncron') {
                    258:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   259:                     $ua->timeout(4);
1.1073    raeburn   260:                     my $protocol = $protocol{$lonhost};
                    261:                     $protocol = 'http' if ($protocol ne 'https');
                    262:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    263:                     my $request=new HTTP::Request('GET',$url);
                    264:                     my $response=$ua->request($request);
                    265:                     unless ($response->is_error()) {
                    266:                         my $content = $response->content;
1.1081    raeburn   267:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   268:                             $loncaparev = $1;
                    269:                         }
                    270:                     }
                    271:                 } else {
                    272:                     $loncaparev = $loncaparevs{$lonhost};
                    273:                 }
1.1081    raeburn   274:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   275:                 $loncaparev = $1;
                    276:             }
1.993     raeburn   277:         }
1.1073    raeburn   278:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   279:     }
                    280: }
                    281: 
1.1074    raeburn   282: sub get_server_homeID {
                    283:     my ($hostname,$ignore_cache,$caller) = @_;
                    284:     unless ($ignore_cache) {
                    285:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    286:         if (defined($cached)) {
                    287:             return $serverhomeID;
                    288:         }
                    289:     }
                    290:     my $cachetime = 12*3600;
                    291:     my $serverhomeID;
                    292:     if ($caller eq 'loncron') { 
                    293:         my @machine_ids = &machine_ids($hostname);
                    294:         foreach my $id (@machine_ids) {
                    295:             my $response = &reply('serverhomeID',$id);
                    296:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    297:                 $serverhomeID = $response;
                    298:                 last;
                    299:             }
                    300:         }
                    301:         if ($serverhomeID eq '') {
                    302:             $serverhomeID = $machine_ids[-1];
                    303:         }
                    304:     } else {
                    305:         $serverhomeID = $serverhomeIDs{$hostname};
                    306:     }
                    307:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    308: }
                    309: 
1.1121    raeburn   310: sub get_remote_globals {
                    311:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   312:     my ($result,%returnhash,%whatneeded);
                    313:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   314:         foreach my $what (sort(keys(%{$whathash}))) {
                    315:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   316:             my ($response,$cached);
1.1121    raeburn   317:             unless ($ignore_cache) {
1.1125    raeburn   318:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   319:             }
                    320:             if (defined($cached)) {
1.1125    raeburn   321:                 $returnhash{$what} = $response;
1.1121    raeburn   322:             } else {
1.1125    raeburn   323:                 $whatneeded{$what} = 1;
1.1121    raeburn   324:             }
                    325:         }
1.1125    raeburn   326:         if (keys(%whatneeded) == 0) {
                    327:             $result = 'ok';
                    328:         } else {
1.1121    raeburn   329:             my $requested = &freeze_escape(\%whatneeded);
                    330:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   331:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    332:                 ($rep eq 'unknown_cmd')) {
                    333:                 $result = $rep;
                    334:             } else {
                    335:                 $result = 'ok';
1.1121    raeburn   336:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   337:                 foreach my $item (@pairs) {
                    338:                     my ($key,$value)=split(/=/,$item,2);
                    339:                     my $what = &unescape($key);
                    340:                     my $hashid = $lonhost.'-'.$what;
                    341:                     $returnhash{$what}=&thaw_unescape($value);
                    342:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   343:                 }
                    344:             }
                    345:         }
                    346:     }
1.1125    raeburn   347:     return ($result,\%returnhash);
1.1121    raeburn   348: }
                    349: 
1.1124    raeburn   350: sub remote_devalidate_cache {
                    351:     my ($lonhost,$name,$id) = @_;
1.1130    raeburn   352:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124    raeburn   353:     return $response;
                    354: }
                    355: 
1.1       albertel  356: # -------------------------------------------------- Non-critical communication
                    357: sub subreply {
                    358:     my ($cmd,$server)=@_;
1.838     albertel  359:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      360:     #
                    361:     #  With loncnew process trimming, there's a timing hole between lonc server
                    362:     #  process exit and the master server picking up the listen on the AF_UNIX
                    363:     #  socket.  In that time interval, a lock file will exist:
                    364: 
                    365:     my $lockfile=$peerfile.".lock";
                    366:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    367: 	sleep(1);
                    368:     }
                    369:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      370:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      371:     #
1.550     foxr      372:     #   We'll give the connection a few tries before abandoning it.  If
                    373:     #   connection is not possible, we'll con_lost back to the client.
                    374:     #   
                    375:     my $client;
                    376:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    377: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    378: 				      Type    => SOCK_STREAM,
                    379: 				      Timeout => 10);
1.869     albertel  380: 	if ($client) {
1.550     foxr      381: 	    last;		# Connected!
1.850     albertel  382: 	} else {
1.853     albertel  383: 	    &create_connection(&hostname($server),$server);
1.550     foxr      384: 	}
1.850     albertel  385:         sleep(1);		# Try again later if failed connection.
1.550     foxr      386:     }
                    387:     my $answer;
                    388:     if ($client) {
1.704     albertel  389: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      390: 	$answer=<$client>;
                    391: 	if (!$answer) { $answer="con_lost"; }
                    392: 	chomp($answer);
                    393:     } else {
                    394: 	$answer = 'con_lost';	# Failed connection.
                    395:     }
1.1       albertel  396:     return $answer;
                    397: }
                    398: 
                    399: sub reply {
                    400:     my ($cmd,$server)=@_;
1.838     albertel  401:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  402:     my $answer=subreply($cmd,$server);
1.65      www       403:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  404:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       405:                 " $cmd to $server returned $answer</font>");
                    406:     }
1.1       albertel  407:     return $answer;
                    408: }
                    409: 
                    410: # ----------------------------------------------------------- Send USR1 to lonc
                    411: 
                    412: sub reconlonc {
1.891     albertel  413:     my ($lonid) = @_;
                    414:     my $hostname = &hostname($lonid);
                    415:     if ($lonid) {
                    416: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    417: 	if ($hostname && -e $peerfile) {
                    418: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    419: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    420: 					     Type    => SOCK_STREAM,
                    421: 					     Timeout => 10);
                    422: 	    if ($client) {
                    423: 		print $client ("reset_retries\n");
                    424: 		my $answer=<$client>;
                    425: 		#reset just this one.
                    426: 	    }
                    427: 	}
                    428: 	return;
                    429:     }
                    430: 
1.836     www       431:     &logthis("Trying to reconnect lonc");
1.1       albertel  432:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  433:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  434: 	my $loncpid=<$fh>;
                    435:         chomp($loncpid);
                    436:         if (kill 0 => $loncpid) {
                    437: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    438:             kill USR1 => $loncpid;
                    439:             sleep 1;
1.836     www       440:          } else {
1.12      www       441: 	    &logthis(
1.672     albertel  442:                "<font color=\"blue\">WARNING:".
1.12      www       443:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  444:         }
                    445:     } else {
1.836     www       446: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  447:     }
                    448: }
                    449: 
                    450: # ------------------------------------------------------ Critical communication
1.12      www       451: 
1.1       albertel  452: sub critical {
                    453:     my ($cmd,$server)=@_;
1.838     albertel  454:     unless (&hostname($server)) {
1.672     albertel  455:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       456:                " Critical message to unknown server ($server)</font>");
                    457:         return 'no_such_host';
                    458:     }
1.1       albertel  459:     my $answer=reply($cmd,$server);
                    460:     if ($answer eq 'con_lost') {
                    461: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  462: 	my $answer=reply($cmd,$server);
1.1       albertel  463:         if ($answer eq 'con_lost') {
                    464:             my $now=time;
                    465:             my $middlename=$cmd;
1.5       www       466:             $middlename=substr($middlename,0,16);
1.1       albertel  467:             $middlename=~s/\W//g;
                    468:             my $dfilename=
1.305     www       469:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    470:             $dumpcount++;
1.1       albertel  471:             {
1.448     albertel  472: 		my $dfh;
                    473: 		if (open($dfh,">$dfilename")) {
                    474: 		    print $dfh "$cmd\n"; 
                    475: 		    close($dfh);
                    476: 		}
1.1       albertel  477:             }
                    478:             sleep 2;
                    479:             my $wcmd='';
                    480:             {
1.448     albertel  481: 		my $dfh;
                    482: 		if (open($dfh,"<$dfilename")) {
                    483: 		    $wcmd=<$dfh>; 
                    484: 		    close($dfh);
                    485: 		}
1.1       albertel  486:             }
                    487:             chomp($wcmd);
1.7       www       488:             if ($wcmd eq $cmd) {
1.672     albertel  489: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       490:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  491:                 &logperm("D:$server:$cmd");
                    492: 	        return 'con_delayed';
                    493:             } else {
1.672     albertel  494:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       495:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  496:                 &logperm("F:$server:$cmd");
                    497:                 return 'con_failed';
                    498:             }
                    499:         }
                    500:     }
                    501:     return $answer;
1.405     albertel  502: }
                    503: 
1.755     albertel  504: # ------------------------------------------- check if return value is an error
                    505: 
                    506: sub error {
                    507:     my ($result) = @_;
1.756     albertel  508:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  509: 	if ($2 == 2) { return undef; }
                    510: 	return $1;
                    511:     }
                    512:     return undef;
                    513: }
                    514: 
1.783     albertel  515: sub convert_and_load_session_env {
                    516:     my ($lonidsdir,$handle)=@_;
                    517:     my @profile;
                    518:     {
1.917     albertel  519: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    520: 	if (!$opened) {
1.915     albertel  521: 	    return 0;
                    522: 	}
1.783     albertel  523: 	flock($idf,LOCK_SH);
                    524: 	@profile=<$idf>;
                    525: 	close($idf);
                    526:     }
                    527:     my %temp_env;
                    528:     foreach my $line (@profile) {
1.786     albertel  529: 	if ($line !~ m/=/) {
                    530: 	    return 0;
                    531: 	}
1.783     albertel  532: 	chomp($line);
                    533: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    534: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    535:     }
                    536:     unlink("$lonidsdir/$handle.id");
                    537:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    538: 	    0640)) {
                    539: 	%disk_env = %temp_env;
                    540: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    541: 	untie(%disk_env);
                    542:     }
1.786     albertel  543:     return 1;
1.783     albertel  544: }
                    545: 
1.374     www       546: # ------------------------------------------- Transfer profile into environment
1.780     albertel  547: my $env_loaded;
                    548: sub transfer_profile_to_env {
1.788     albertel  549:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    550:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       551: 
1.720     albertel  552:     if (!defined($lonidsdir)) {
                    553: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    554:     }
                    555:     if (!defined($handle)) {
                    556:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    557:     }
                    558: 
1.786     albertel  559:     my $convert;
                    560:     {
1.917     albertel  561:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    562: 	if (!$opened) {
1.915     albertel  563: 	    return;
                    564: 	}
1.786     albertel  565: 	flock($idf,LOCK_SH);
                    566: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    567: 		&GDBM_READER(),0640)) {
                    568: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    569: 	    untie(%disk_env);
                    570: 	} else {
                    571: 	    $convert = 1;
                    572: 	}
                    573:     }
                    574:     if ($convert) {
                    575: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    576: 	    &logthis("Failed to load session, or convert session.");
                    577: 	}
1.374     www       578:     }
1.783     albertel  579: 
1.786     albertel  580:     my %remove;
1.783     albertel  581:     while ( my $envname = each(%env) ) {
1.433     matthew   582:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    583:             if ($time < time-300) {
1.783     albertel  584:                 $remove{$key}++;
1.433     matthew   585:             }
                    586:         }
                    587:     }
1.783     albertel  588: 
1.619     albertel  589:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  590:     $env_loaded=1;
1.783     albertel  591:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   592:         &delenv($expired_key);
1.374     www       593:     }
1.1       albertel  594: }
                    595: 
1.916     albertel  596: # ---------------------------------------------------- Check for valid session 
                    597: sub check_for_valid_session {
1.1155    raeburn   598:     my ($r,$name) = @_;
1.916     albertel  599:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   600:     if ($name eq '') {
                    601:         $name = 'lonID';
                    602:     }
                    603:     my $lonid=$cookies{$name};
1.916     albertel  604:     return undef if (!$lonid);
                    605: 
                    606:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   607:     my $lonidsdir;
                    608:     if ($name eq 'lonDAV') {
                    609:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    610:     } else {
                    611:         $lonidsdir=$r->dir_config('lonIDsDir');
                    612:     }
1.916     albertel  613:     return undef if (!-e "$lonidsdir/$handle.id");
                    614: 
1.917     albertel  615:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    616:     return undef if (!$opened);
1.916     albertel  617: 
                    618:     flock($idf,LOCK_SH);
                    619:     my %disk_env;
                    620:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    621: 	    &GDBM_READER(),0640)) {
                    622: 	return undef;	
                    623:     }
                    624: 
                    625:     if (!defined($disk_env{'user.name'})
                    626: 	|| !defined($disk_env{'user.domain'})) {
                    627: 	return undef;
                    628:     }
                    629:     return $handle;
                    630: }
                    631: 
1.830     albertel  632: sub timed_flock {
                    633:     my ($file,$lock_type) = @_;
                    634:     my $failed=0;
                    635:     eval {
                    636: 	local $SIG{__DIE__}='DEFAULT';
                    637: 	local $SIG{ALRM}=sub {
                    638: 	    $failed=1;
                    639: 	    die("failed lock");
                    640: 	};
                    641: 	alarm(13);
                    642: 	flock($file,$lock_type);
                    643: 	alarm(0);
                    644:     };
                    645:     if ($failed) {
                    646: 	return undef;
                    647:     } else {
                    648: 	return 1;
                    649:     }
                    650: }
                    651: 
1.5       www       652: # ---------------------------------------------------------- Append Environment
                    653: 
                    654: sub appenv {
1.949     raeburn   655:     my ($newenv,$roles) = @_;
                    656:     if (ref($newenv) eq 'HASH') {
                    657:         foreach my $key (keys(%{$newenv})) {
                    658:             my $refused = 0;
                    659: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    660:                 $refused = 1;
                    661:                 if (ref($roles) eq 'ARRAY') {
                    662:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    663:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    664:                         $refused = 0;
                    665:                     }
                    666:                 }
                    667:             }
                    668:             if ($refused) {
                    669:                 &logthis("<font color=\"blue\">WARNING: ".
                    670:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    671:                          .'</font>');
                    672: 	        delete($newenv->{$key});
                    673:             } else {
                    674:                 $env{$key}=$newenv->{$key};
                    675:             }
                    676:         }
                    677:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    678:         if ($opened
                    679: 	    && &timed_flock($env_file,LOCK_EX)
                    680: 	    &&
                    681: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    682: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    683: 	    while (my ($key,$value) = each(%{$newenv})) {
                    684: 	        $disk_env{$key} = $value;
                    685: 	    }
                    686: 	    untie(%disk_env);
1.35      www       687:         }
1.191     harris41  688:     }
1.56      www       689:     return 'ok';
                    690: }
                    691: # ----------------------------------------------------- Delete from Environment
                    692: 
                    693: sub delenv {
1.1104    raeburn   694:     my ($delthis,$regexp,$roles) = @_;
                    695:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    696:         my $refused = 1;
                    697:         if (ref($roles) eq 'ARRAY') {
                    698:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    699:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    700:                 $refused = 0;
                    701:             }
                    702:         }
                    703:         if ($refused) {
                    704:             &logthis("<font color=\"blue\">WARNING: ".
                    705:                      "Attempt to delete from environment ".$delthis);
                    706:             return 'error';
                    707:         }
1.56      www       708:     }
1.917     albertel  709:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    710:     if ($opened
1.915     albertel  711: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  712: 	&&
                    713: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    714: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  715: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   716: 	    if ($regexp) {
                    717:                 if ($key=~/^$delthis/) {
                    718:                     delete($env{$key});
                    719:                     delete($disk_env{$key});
                    720:                 } 
                    721:             } else {
                    722:                 if ($key=~/^\Q$delthis\E/) {
                    723: 		    delete($env{$key});
                    724: 		    delete($disk_env{$key});
                    725: 	        }
                    726:             }
1.448     albertel  727: 	}
1.783     albertel  728: 	untie(%disk_env);
1.5       www       729:     }
                    730:     return 'ok';
1.369     albertel  731: }
                    732: 
1.790     albertel  733: sub get_env_multiple {
                    734:     my ($name) = @_;
                    735:     my @values;
                    736:     if (defined($env{$name})) {
                    737:         # exists is it an array
                    738:         if (ref($env{$name})) {
                    739:             @values=@{ $env{$name} };
                    740:         } else {
                    741:             $values[0]=$env{$name};
                    742:         }
                    743:     }
                    744:     return(@values);
                    745: }
                    746: 
1.958     www       747: # ------------------------------------------------------------------- Locking
                    748: 
                    749: sub set_lock {
                    750:     my ($text)=@_;
                    751:     $locknum++;
                    752:     my $id=$$.'-'.$locknum;
                    753:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    754:              'session.lock.'.$id => $text});
                    755:     return $id;
                    756: }
                    757: 
                    758: sub get_locks {
                    759:     my $num=0;
                    760:     my %texts=();
                    761:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    762:        if ($lock=~/\w/) {
                    763:           $num++;
                    764:           $texts{$lock}=$env{'session.lock.'.$lock};
                    765:        }
                    766:    }
                    767:    return ($num,%texts);
                    768: }
                    769: 
                    770: sub remove_lock {
                    771:     my ($id)=@_;
                    772:     my $newlocks='';
                    773:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    774:        if (($lock=~/\w/) && ($lock ne $id)) {
                    775:           $newlocks.=','.$lock;
                    776:        }
                    777:     }
                    778:     &appenv({'session.locks' => $newlocks});
                    779:     &delenv('session.lock.'.$id);
                    780: }
                    781: 
                    782: sub remove_all_locks {
                    783:     my $activelocks=$env{'session.locks'};
                    784:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    785:        if ($lock=~/\w/) {
                    786:           &remove_lock($lock);
                    787:        }
                    788:     }
                    789: }
                    790: 
                    791: 
1.369     albertel  792: # ------------------------------------------ Find out current server userload
                    793: sub userload {
                    794:     my $numusers=0;
                    795:     {
                    796: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    797: 	my $filename;
                    798: 	my $curtime=time;
                    799: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  800: 	    next if ($filename eq '.' || $filename eq '..');
                    801: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  802: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  803: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  804: 	}
                    805: 	closedir(LONIDS);
                    806:     }
                    807:     my $userloadpercent=0;
                    808:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    809:     if ($maxuserload) {
1.371     albertel  810: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  811:     }
1.372     albertel  812:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  813:     return $userloadpercent;
1.283     www       814: }
                    815: 
1.1       albertel  816: # ------------------------------ Find server with least workload from spare.tab
1.11      www       817: 
1.1       albertel  818: sub spareserver {
1.1083    raeburn   819:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  820:     my $spare_server;
1.370     albertel  821:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  822:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    823:                                                      :  $userloadpercent;
1.1083    raeburn   824:     my ($uint_dom,$remotesessions);
                    825:     if (($udom ne '') && (&domain($udom) ne '')) {
                    826:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    827:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    828:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    829:         $remotesessions = $udomdefaults{'remotesessions'};
                    830:     }
1.1123    raeburn   831:     my $spareshash = &this_host_spares($udom);
                    832:     if (ref($spareshash) eq 'HASH') {
                    833:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    834:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    835:                 if ($uint_dom) {
                    836:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    837:                                                  $try_server));
                    838:                 }
                    839: 	        ($spare_server, $lowest_load) =
                    840: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    841:             }
1.1083    raeburn   842:         }
1.784     albertel  843: 
1.1123    raeburn   844:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    845: 
                    846:         if (!$found_server) {
                    847:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    848: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
                    849:                     if ($uint_dom) {
                    850:                         next unless (&spare_can_host($udom,$uint_dom,
                    851:                                                      $remotesessions,$try_server));
                    852:                     }
                    853: 	            ($spare_server, $lowest_load) =
                    854: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    855:                 }
                    856: 	    }
                    857:         }
1.784     albertel  858:     }
                    859: 
                    860:     if (!$want_server_name) {
1.968     raeburn   861:         my $protocol = 'http';
                    862:         if ($protocol{$spare_server} eq 'https') {
                    863:             $protocol = $protocol{$spare_server};
                    864:         }
1.1001    raeburn   865:         if (defined($spare_server)) {
                    866:             my $hostname = &hostname($spare_server);
1.1083    raeburn   867:             if (defined($hostname)) {
1.1001    raeburn   868: 	        $spare_server = $protocol.'://'.$hostname;
                    869:             }
                    870:         }
1.784     albertel  871:     }
                    872:     return $spare_server;
                    873: }
                    874: 
                    875: sub compare_server_load {
                    876:     my ($try_server, $spare_server, $lowest_load) = @_;
                    877: 
                    878:     my $loadans     = &reply('load',    $try_server);
                    879:     my $userloadans = &reply('userload',$try_server);
                    880: 
                    881:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   882: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  883:     }
                    884: 
                    885:     my $load;
                    886:     if ($loadans =~ /\d/) {
                    887: 	if ($userloadans =~ /\d/) {
                    888: 	    #both are numbers, pick the bigger one
                    889: 	    $load = ($loadans > $userloadans) ? $loadans 
                    890: 		                              : $userloadans;
1.411     albertel  891: 	} else {
1.784     albertel  892: 	    $load = $loadans;
1.411     albertel  893: 	}
1.784     albertel  894:     } else {
                    895: 	$load = $userloadans;
                    896:     }
                    897: 
                    898:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    899: 	$spare_server = $try_server;
                    900: 	$lowest_load  = $load;
1.370     albertel  901:     }
1.784     albertel  902:     return ($spare_server,$lowest_load);
1.202     matthew   903: }
1.914     albertel  904: 
                    905: # --------------------------- ask offload servers if user already has a session
                    906: sub find_existing_session {
                    907:     my ($udom,$uname) = @_;
1.1123    raeburn   908:     my $spareshash = &this_host_spares($udom);
                    909:     if (ref($spareshash) eq 'HASH') {
                    910:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    911:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    912:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    913:             }
                    914:         }
                    915:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    916:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    917:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    918:             }
                    919:         }
1.914     albertel  920:     }
                    921:     return;
                    922: }
                    923: 
                    924: # -------------------------------- ask if server already has a session for user
                    925: sub has_user_session {
                    926:     my ($lonid,$udom,$uname) = @_;
                    927:     my $result = &reply(join(':','userhassession',
                    928: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    929:     return 1 if ($result eq 'ok');
                    930: 
                    931:     return 0;
                    932: }
                    933: 
1.1076    raeburn   934: # --------- determine least loaded server in a user's domain which allows login
                    935: 
                    936: sub choose_server {
1.1115    raeburn   937:     my ($udom,$checkloginvia) = @_;
1.1076    raeburn   938:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   939:     my %servers = &get_servers($udom);
1.1076    raeburn   940:     my $lowest_load = 30000;
1.1151    raeburn   941:     my ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   942:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   943:         my $loginvia;
                    944:         if ($checkloginvia) {
                    945:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   946:             if ($loginvia) {
                    947:                 my ($server,$path) = split(/:/,$loginvia);
                    948:                 ($login_host, $lowest_load) =
                    949:                     &compare_server_load($server, $login_host, $lowest_load);
                    950:                 if ($login_host eq $server) {
                    951:                     $portal_path = $path;
1.1151    raeburn   952:                     $isredirect = 1;
1.1116    raeburn   953:                 }
                    954:             } else {
                    955:                 ($login_host, $lowest_load) =
                    956:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    957:                 if ($login_host eq $lonhost) {
                    958:                     $portal_path = '';
1.1151    raeburn   959:                     $isredirect = ''; 
1.1116    raeburn   960:                 }
                    961:             }
                    962:         } else {
1.1076    raeburn   963:             ($login_host, $lowest_load) =
1.1116    raeburn   964:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076    raeburn   965:         }
                    966:     }
                    967:     if ($login_host ne '') {
1.1116    raeburn   968:         $hostname = &hostname($login_host);
1.1076    raeburn   969:     }
1.1151    raeburn   970:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   971: }
                    972: 
1.202     matthew   973: # --------------------------------------------- Try to change a user's password
                    974: 
                    975: sub changepass {
1.799     raeburn   976:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   977:     $currentpass = &escape($currentpass);
                    978:     $newpass     = &escape($newpass);
1.1030    raeburn   979:     my $lonhost = $perlvar{'lonHostID'};
                    980:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   981: 		       $server);
                    982:     if (! $answer) {
                    983: 	&logthis("No reply on password change request to $server ".
                    984: 		 "by $uname in domain $udom.");
                    985:     } elsif ($answer =~ "^ok") {
                    986:         &logthis("$uname in $udom successfully changed their password ".
                    987: 		 "on $server.");
                    988:     } elsif ($answer =~ "^pwchange_failure") {
                    989: 	&logthis("$uname in $udom was unable to change their password ".
                    990: 		 "on $server.  The action was blocked by either lcpasswd ".
                    991: 		 "or pwchange");
                    992:     } elsif ($answer =~ "^non_authorized") {
                    993:         &logthis("$uname in $udom did not get their password correct when ".
                    994: 		 "attempting to change it on $server.");
                    995:     } elsif ($answer =~ "^auth_mode_error") {
                    996:         &logthis("$uname in $udom attempted to change their password despite ".
                    997: 		 "not being locally or internally authenticated on $server.");
                    998:     } elsif ($answer =~ "^unknown_user") {
                    999:         &logthis("$uname in $udom attempted to change their password ".
                   1000: 		 "on $server but were unable to because $server is not ".
                   1001: 		 "their home server.");
                   1002:     } elsif ($answer =~ "^refused") {
                   1003: 	&logthis("$server refused to change $uname in $udom password because ".
                   1004: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1005:     } elsif ($answer =~ "invalid_client") {
                   1006:         &logthis("$server refused to change $uname in $udom password because ".
                   1007:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1008:     }
                   1009:     return $answer;
1.1       albertel 1010: }
                   1011: 
1.169     harris41 1012: # ----------------------- Try to determine user's current authentication scheme
                   1013: 
                   1014: sub queryauthenticate {
                   1015:     my ($uname,$udom)=@_;
1.456     albertel 1016:     my $uhome=&homeserver($uname,$udom);
                   1017:     if (!$uhome) {
                   1018: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1019: 	return 'no_host';
                   1020:     }
                   1021:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1022:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1023: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1024:     }
1.456     albertel 1025:     return $answer;
1.169     harris41 1026: }
                   1027: 
1.1       albertel 1028: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1029: 
1.1       albertel 1030: sub authenticate {
1.1073    raeburn  1031:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1032:     $upass=&escape($upass);
                   1033:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1034:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1035:     my $newhome;
1.836     www      1036:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1037: # Maybe the machine was offline and only re-appeared again recently?
                   1038:         &reconlonc();
                   1039: # One more
1.952     raeburn  1040: 	$uhome=&homeserver($uname,$udom,1);
                   1041:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1042:             if (defined(&domain($udom,'primary'))) {
                   1043:                 $newhome=&domain($udom,'primary');
                   1044:             }
                   1045:             if ($newhome ne '') {
                   1046:                 $uhome = $newhome;
                   1047:             }
                   1048:         }
1.836     www      1049: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1050: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1051: 	    return 'no_host';
                   1052:         }
1.1       albertel 1053:     }
1.1073    raeburn  1054:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1055:     if ($answer eq 'authorized') {
1.952     raeburn  1056:         if ($newhome) {
                   1057:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1058:             return 'no_account_on_host'; 
                   1059:         } else {
                   1060:             &logthis("User $uname at $udom authorized by $uhome");
                   1061:             return $uhome;
                   1062:         }
1.471     albertel 1063:     }
                   1064:     if ($answer eq 'non_authorized') {
                   1065: 	&logthis("User $uname at $udom rejected by $uhome");
                   1066: 	return 'no_host'; 
1.9       www      1067:     }
1.471     albertel 1068:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1069:     return 'no_host';
                   1070: }
                   1071: 
1.1073    raeburn  1072: sub can_host_session {
1.1074    raeburn  1073:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1074:     my $canhost = 1;
1.1074    raeburn  1075:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1076:     if (ref($remotesessions) eq 'HASH') {
                   1077:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1078:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1079:                 $canhost = 0;
                   1080:             } else {
                   1081:                 $canhost = 1;
                   1082:             }
                   1083:         }
                   1084:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1085:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1086:                 $canhost = 1;
                   1087:             } else {
                   1088:                 $canhost = 0;
                   1089:             }
                   1090:         }
                   1091:         if ($canhost) {
                   1092:             if ($remotesessions->{'version'} ne '') {
                   1093:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1094:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1095:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1096:                         my $major = $1;
                   1097:                         my $minor = $2;
                   1098:                         if (($major < $reqmajor ) ||
                   1099:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1100:                             $canhost = 0;
                   1101:                         }
                   1102:                     } else {
                   1103:                         $canhost = 0;
                   1104:                     }
                   1105:                 }
                   1106:             }
                   1107:         }
                   1108:     }
                   1109:     if ($canhost) {
                   1110:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1111:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1112:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1113:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1114:                 if (($uint_dom ne '') && 
                   1115:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1116:                     $canhost = 0;
                   1117:                 } else {
                   1118:                     $canhost = 1;
                   1119:                 }
                   1120:             }
                   1121:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1122:                 if (($uint_dom ne '') && 
                   1123:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1124:                     $canhost = 1;
                   1125:                 } else {
                   1126:                     $canhost = 0;
                   1127:                 }
                   1128:             }
                   1129:         }
                   1130:     }
                   1131:     return $canhost;
                   1132: }
                   1133: 
1.1083    raeburn  1134: sub spare_can_host {
                   1135:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1136:     my $canhost=1;
                   1137:     my @intdoms;
                   1138:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1139:     if (ref($internet_names) eq 'ARRAY') {
                   1140:         @intdoms = @{$internet_names};
                   1141:     }
                   1142:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1143:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1144:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1145:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1146:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1147:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1148:                                      $remotesessions,
                   1149:                                      $defdomdefaults{'hostedsessions'});
                   1150:     }
                   1151:     return $canhost;
                   1152: }
                   1153: 
1.1123    raeburn  1154: sub this_host_spares {
                   1155:     my ($dom) = @_;
1.1126    raeburn  1156:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1157:     my @hosts = &current_machine_ids();
                   1158:     foreach my $lonhost (@hosts) {
                   1159:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1160:             $dom_in_use = $dom;
                   1161:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1162:             last;
                   1163:         }
                   1164:     }
1.1126    raeburn  1165:     if ($dom_in_use ne '') {
                   1166:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1167:     }
                   1168:     if (ref($result) ne 'HASH') {
                   1169:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1170:         $dom_in_use = &host_domain($lonhost_in_use);
                   1171:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1172:         if (ref($result) ne 'HASH') {
                   1173:             $result = \%spareid;
                   1174:         }
                   1175:     }
                   1176:     return $result;
                   1177: }
                   1178: 
                   1179: sub spares_for_offload  {
                   1180:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1181:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1182:     if (defined($cached)) {
                   1183:         return $result;
                   1184:     } else {
1.1126    raeburn  1185:         my $cachetime = 60*60*24;
                   1186:         my %domconfig =
                   1187:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1188:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1189:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1190:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1191:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1192:                 }
                   1193:             }
                   1194:         }
                   1195:     }
1.1126    raeburn  1196:     return;
1.1123    raeburn  1197: }
                   1198: 
1.1129    raeburn  1199: sub get_lonbalancer_config {
                   1200:     my ($servers) = @_;
                   1201:     my ($currbalancer,$currtargets);
                   1202:     if (ref($servers) eq 'HASH') {
                   1203:         foreach my $server (keys(%{$servers})) {
                   1204:             my %what = (
                   1205:                          spareid => 1,
                   1206:                          perlvar => 1,
                   1207:                        );
                   1208:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1209:             if ($result eq 'ok') {
                   1210:                 if (ref($returnhash) eq 'HASH') {
                   1211:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1212:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1213:                             $currbalancer = $server;
                   1214:                             $currtargets = {};
                   1215:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1216:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1217:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1218:                                 }
                   1219:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1220:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1221:                                 }
                   1222:                             }
                   1223:                             last;
                   1224:                         }
                   1225:                     }
                   1226:                 }
                   1227:             }
                   1228:         }
                   1229:     }
                   1230:     return ($currbalancer,$currtargets);
                   1231: }
                   1232: 
                   1233: sub check_loadbalancing {
                   1234:     my ($uname,$udom) = @_;
                   1235:     my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
                   1236:         $offloadto,$otherserver);
                   1237:     my $lonhost = $perlvar{'lonHostID'};
                   1238:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1239:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1240:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1241:     my $serverhomedom = &host_domain($lonhost);
                   1242: 
                   1243:     my $cachetime = 60*60*24;
                   1244: 
                   1245:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1246:         $dom_in_use = $udom;
                   1247:         $homeintdom = 1;
                   1248:     } else {
                   1249:         $dom_in_use = $serverhomedom;
                   1250:     }
                   1251:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1252:     unless (defined($cached)) {
                   1253:         my %domconfig =
                   1254:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1255:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1256:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1257:         }
                   1258:     }
                   1259:     if (ref($result) eq 'HASH') {
                   1260:         my $currbalancer = $result->{'lonhost'};
                   1261:         my $currtargets = $result->{'targets'};
                   1262:         my $currrules = $result->{'rules'};
                   1263:         if ($currbalancer ne '') {
                   1264:             my @hosts = &current_machine_ids();
                   1265:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1266:                 $is_balancer = 1;
                   1267:             }
                   1268:         }
                   1269:         if ($is_balancer) {
                   1270:             if (ref($currrules) eq 'HASH') {
                   1271:                 if ($homeintdom) {
                   1272:                     if ($uname ne '') {
                   1273:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1274:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1275:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1276:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1277:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1278:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1279:                             }
                   1280:                         }
                   1281:                         if ($rule_in_effect eq '') {
                   1282:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1283:                             if ($userenv{'inststatus'} ne '') {
                   1284:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1285:                                 my ($othertitle,$usertypes,$types) =
                   1286:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1287:                                 if (ref($types) eq 'ARRAY') {
                   1288:                                     foreach my $type (@{$types}) {
                   1289:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1290:                                             if (exists($currrules->{$type})) {
                   1291:                                                 $rule_in_effect = $currrules->{$type};
                   1292:                                             }
                   1293:                                         }
                   1294:                                     }
                   1295:                                 }
                   1296:                             } else {
                   1297:                                 if (exists($currrules->{'default'})) {
                   1298:                                     $rule_in_effect = $currrules->{'default'};
                   1299:                                 }
                   1300:                             }
                   1301:                         }
                   1302:                     } else {
                   1303:                         if (exists($currrules->{'default'})) {
                   1304:                             $rule_in_effect = $currrules->{'default'};
                   1305:                         }
                   1306:                     }
                   1307:                 } else {
                   1308:                     if ($currrules->{'_LC_external'} ne '') {
                   1309:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1310:                     }
                   1311:                 }
                   1312:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1313:                                                        $uname,$udom);
                   1314:             }
                   1315:         }
                   1316:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
                   1317:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
                   1318:         unless (defined($cached)) {
                   1319:             my %domconfig =
                   1320:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1321:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1322:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1323:             }
                   1324:         }
                   1325:         if (ref($result) eq 'HASH') {
                   1326:             my $currbalancer = $result->{'lonhost'};
                   1327:             my $currtargets = $result->{'targets'};
                   1328:             my $currrules = $result->{'rules'};
                   1329: 
                   1330:             if ($currbalancer eq $lonhost) {
                   1331:                 $is_balancer = 1;
                   1332:                 if (ref($currrules) eq 'HASH') {
                   1333:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1334:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1335:                     }
                   1336:                 }
                   1337:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1338:                                                        $uname,$udom);
                   1339:             }
                   1340:         } else {
                   1341:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1342:                 $is_balancer = 1;
                   1343:                 $offloadto = &this_host_spares($dom_in_use);
                   1344:             }
                   1345:         }
                   1346:     } else {
                   1347:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1348:             $is_balancer = 1;
                   1349:             $offloadto = &this_host_spares($dom_in_use);
                   1350:         }
                   1351:     }
                   1352:     my $lowest_load = 30000;
                   1353:     if (ref($offloadto) eq 'HASH') {
                   1354:         if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1355:             foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1356:                 ($otherserver,$lowest_load) =
                   1357:                     &compare_server_load($try_server,$otherserver,$lowest_load);
                   1358:             }
                   1359:         }
                   1360:         my $found_server = ($otherserver ne '' && $lowest_load < 100);
                   1361: 
                   1362:         if (!$found_server) {
                   1363:             if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1364:                 foreach my $try_server (@{$offloadto->{'default'}}) {
                   1365:                     ($otherserver,$lowest_load) =
                   1366:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1367:                 }
                   1368:             }
                   1369:         }
                   1370:     } elsif (ref($offloadto) eq 'ARRAY') {
                   1371:         if (@{$offloadto} == 1) {
                   1372:             $otherserver = $offloadto->[0];
                   1373:         } elsif (@{$offloadto} > 1) {
                   1374:             foreach my $try_server (@{$offloadto}) {
                   1375:                 ($otherserver,$lowest_load) =
                   1376:                     &compare_server_load($try_server,$otherserver,$lowest_load);
                   1377:             }
                   1378:         }
                   1379:     }
                   1380:     return ($is_balancer,$otherserver);
                   1381: }
                   1382: 
                   1383: sub get_loadbalancer_targets {
                   1384:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1385:     my $offloadto;
                   1386:     if ($rule_in_effect eq '') {
                   1387:         $offloadto = $currtargets;
                   1388:     } else {
                   1389:         if ($rule_in_effect eq 'homeserver') {
                   1390:             my $homeserver = &homeserver($uname,$udom);
                   1391:             if ($homeserver ne 'no_host') {
                   1392:                 $offloadto = [$homeserver];
                   1393:             }
                   1394:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1395:             my %domconfig =
                   1396:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1397:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1398:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1399:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1400:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1401:                     }
                   1402:                 }
                   1403:             } else {
                   1404:                 my %servers = &dom_servers($udom);
                   1405:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1406:                 if (&hostname($remotebalancer) ne '') {
                   1407:                     $offloadto = [$remotebalancer];
                   1408:                 }
                   1409:             }
                   1410:         } elsif (&hostname($rule_in_effect) ne '') {
                   1411:             $offloadto = [$rule_in_effect];
                   1412:         }
                   1413:     }
                   1414:     return $offloadto;
                   1415: }
                   1416: 
1.1127    raeburn  1417: sub internet_dom_servers {
                   1418:     my ($dom) = @_;
                   1419:     my (%uniqservers,%servers);
                   1420:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1421:     my @machinedoms = &machine_domains($primaryserver);
                   1422:     foreach my $mdom (@machinedoms) {
                   1423:         my %currservers = %servers;
                   1424:         my %server = &get_servers($mdom);
                   1425:         %servers = (%currservers,%server);
                   1426:     }
                   1427:     my %by_hostname;
                   1428:     foreach my $id (keys(%servers)) {
                   1429:         push(@{$by_hostname{$servers{$id}}},$id);
                   1430:     }
                   1431:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1432:         if (@{$by_hostname{$hostname}} > 1) {
                   1433:             my $match = 0;
                   1434:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1435:                 if (&host_domain($id) eq $dom) {
                   1436:                     $uniqservers{$id} = $hostname;
                   1437:                     $match = 1;
                   1438:                 }
                   1439:             }
                   1440:             unless ($match) {
                   1441:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1442:             }
                   1443:         } else {
                   1444:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1445:         }
                   1446:     }
                   1447:     return %uniqservers;
                   1448: }
                   1449: 
1.1       albertel 1450: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1451: 
1.599     albertel 1452: my %homecache;
1.1       albertel 1453: sub homeserver {
1.230     stredwic 1454:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1455:     my $index="$uname:$udom";
1.426     albertel 1456: 
1.599     albertel 1457:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1458: 
                   1459:     my %servers = &get_servers($udom,'library');
                   1460:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1461:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1462: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1463: 
                   1464: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1465: 	if ($answer eq 'found') {
                   1466: 	    delete($badServerCache{$tryserver}); 
                   1467: 	    return $homecache{$index}=$tryserver;
                   1468: 	} elsif ($answer eq 'no_host') {
                   1469: 	    $badServerCache{$tryserver}=1;
                   1470: 	}
1.1       albertel 1471:     }    
                   1472:     return 'no_host';
1.70      www      1473: }
                   1474: 
                   1475: # ------------------------------------- Find the usernames behind a list of IDs
                   1476: 
                   1477: sub idget {
                   1478:     my ($udom,@ids)=@_;
                   1479:     my %returnhash=();
                   1480:     
1.841     albertel 1481:     my %servers = &get_servers($udom,'library');
                   1482:     foreach my $tryserver (keys(%servers)) {
                   1483: 	my $idlist=join('&',@ids);
                   1484: 	$idlist=~tr/A-Z/a-z/; 
                   1485: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1486: 	my @answer=();
                   1487: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1488: 	    @answer=split(/\&/,$reply);
                   1489: 	}                    ;
                   1490: 	my $i;
                   1491: 	for ($i=0;$i<=$#ids;$i++) {
                   1492: 	    if ($answer[$i]) {
                   1493: 		$returnhash{$ids[$i]}=$answer[$i];
                   1494: 	    } 
                   1495: 	}
                   1496:     } 
1.70      www      1497:     return %returnhash;
                   1498: }
                   1499: 
                   1500: # ------------------------------------- Find the IDs behind a list of usernames
                   1501: 
                   1502: sub idrget {
                   1503:     my ($udom,@unames)=@_;
                   1504:     my %returnhash=();
1.800     albertel 1505:     foreach my $uname (@unames) {
                   1506:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1507:     }
1.70      www      1508:     return %returnhash;
                   1509: }
                   1510: 
                   1511: # ------------------------------- Store away a list of names and associated IDs
                   1512: 
                   1513: sub idput {
                   1514:     my ($udom,%ids)=@_;
                   1515:     my %servers=();
1.800     albertel 1516:     foreach my $uname (keys(%ids)) {
                   1517: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1518:         my $uhom=&homeserver($uname,$udom);
1.70      www      1519:         if ($uhom ne 'no_host') {
1.800     albertel 1520:             my $id=&escape($ids{$uname});
1.70      www      1521:             $id=~tr/A-Z/a-z/;
1.800     albertel 1522:             my $esc_unam=&escape($uname);
1.70      www      1523: 	    if ($servers{$uhom}) {
1.800     albertel 1524: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1525:             } else {
1.800     albertel 1526:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1527:             }
                   1528:         }
1.191     harris41 1529:     }
1.800     albertel 1530:     foreach my $server (keys(%servers)) {
                   1531:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1532:     }
1.344     www      1533: }
                   1534: 
1.1023    raeburn  1535: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1536: sub dump_dom {
1.1023    raeburn  1537:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn  1538:     if (!$udom) {
                   1539:         $udom=$env{'user.domain'};
                   1540:     }
                   1541:     my %returnhash;
1.1023    raeburn  1542:     if ($udom) {
                   1543:         my $uname = &get_domainconfiguser($udom);
                   1544:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn  1545:     }
                   1546:     return %returnhash;
                   1547: }
                   1548: 
1.1023    raeburn  1549: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1550: 
                   1551: sub get_dom {
1.860     raeburn  1552:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1553:     my $items='';
                   1554:     foreach my $item (@$storearr) {
                   1555:         $items.=&escape($item).'&';
                   1556:     }
                   1557:     $items=~s/\&$//;
1.860     raeburn  1558:     if (!$udom) {
                   1559:         $udom=$env{'user.domain'};
                   1560:         if (defined(&domain($udom,'primary'))) {
                   1561:             $uhome=&domain($udom,'primary');
                   1562:         } else {
1.874     albertel 1563:             undef($uhome);
1.860     raeburn  1564:         }
                   1565:     } else {
                   1566:         if (!$uhome) {
                   1567:             if (defined(&domain($udom,'primary'))) {
                   1568:                 $uhome=&domain($udom,'primary');
                   1569:             }
                   1570:         }
                   1571:     }
                   1572:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1573:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1574:         my %returnhash;
1.875     albertel 1575:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1576:             return %returnhash;
                   1577:         }
1.806     raeburn  1578:         my @pairs=split(/\&/,$rep);
                   1579:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1580:             return @pairs;
                   1581:         }
                   1582:         my $i=0;
                   1583:         foreach my $item (@$storearr) {
                   1584:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1585:             $i++;
                   1586:         }
                   1587:         return %returnhash;
                   1588:     } else {
1.880     banghart 1589:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1590:     }
                   1591: }
                   1592: 
                   1593: # -------------------------------------------- put items in domain db files 
                   1594: 
                   1595: sub put_dom {
1.860     raeburn  1596:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1597:     if (!$udom) {
                   1598:         $udom=$env{'user.domain'};
                   1599:         if (defined(&domain($udom,'primary'))) {
                   1600:             $uhome=&domain($udom,'primary');
                   1601:         } else {
1.874     albertel 1602:             undef($uhome);
1.860     raeburn  1603:         }
                   1604:     } else {
                   1605:         if (!$uhome) {
                   1606:             if (defined(&domain($udom,'primary'))) {
                   1607:                 $uhome=&domain($udom,'primary');
                   1608:             }
                   1609:         }
                   1610:     } 
                   1611:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1612:         my $items='';
                   1613:         foreach my $item (keys(%$storehash)) {
                   1614:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1615:         }
                   1616:         $items=~s/\&$//;
                   1617:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1618:     } else {
1.860     raeburn  1619:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1620:     }
                   1621: }
                   1622: 
1.1023    raeburn  1623: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1624: sub newput_dom {
1.1023    raeburn  1625:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1626:     my $result;
                   1627:     if (!$udom) {
                   1628:         $udom=$env{'user.domain'};
                   1629:     }
1.1023    raeburn  1630:     if ($udom) {
                   1631:         my $uname = &get_domainconfiguser($udom);
                   1632:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1633:     }
                   1634:     return $result;
                   1635: }
                   1636: 
1.1023    raeburn  1637: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1638: sub del_dom {
1.1023    raeburn  1639:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1640:     if (ref($storearr) eq 'ARRAY') {
                   1641:         if (!$udom) {
                   1642:             $udom=$env{'user.domain'};
                   1643:         }
1.1023    raeburn  1644:         if ($udom) {
                   1645:             my $uname = &get_domainconfiguser($udom); 
                   1646:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1647:         }
                   1648:     }
                   1649: }
                   1650: 
1.1023    raeburn  1651: # ----------------------------------construct domainconfig user for a domain 
                   1652: sub get_domainconfiguser {
                   1653:     my ($udom) = @_;
                   1654:     return $udom.'-domainconfig';
                   1655: }
                   1656: 
1.837     raeburn  1657: sub retrieve_inst_usertypes {
                   1658:     my ($udom) = @_;
                   1659:     my (%returnhash,@order);
1.989     raeburn  1660:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1661:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1662:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1663:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1664:         @order = @{$domdefs{'inststatusorder'}};
                   1665:     } else {
                   1666:         if (defined(&domain($udom,'primary'))) {
                   1667:             my $uhome=&domain($udom,'primary');
                   1668:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1669:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1670:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1671:                 return (\%returnhash,\@order);
                   1672:             }
                   1673:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1674:             my @pairs=split(/\&/,$hashitems);
                   1675:             foreach my $item (@pairs) {
                   1676:                 my ($key,$value)=split(/=/,$item,2);
                   1677:                 $key = &unescape($key);
                   1678:                 next if ($key =~ /^error: 2 /);
                   1679:                 $returnhash{$key}=&thaw_unescape($value);
                   1680:             }
                   1681:             my @esc_order = split(/\&/,$orderitems);
                   1682:             foreach my $item (@esc_order) {
                   1683:                 push(@order,&unescape($item));
                   1684:             }
                   1685:         } else {
                   1686:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1687:         }
                   1688:     }
                   1689:     return (\%returnhash,\@order);
                   1690: }
                   1691: 
1.868     raeburn  1692: sub is_domainimage {
                   1693:     my ($url) = @_;
                   1694:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1695:         if (&domain($1) ne '') {
                   1696:             return '1';
                   1697:         }
                   1698:     }
                   1699:     return;
                   1700: }
                   1701: 
1.899     raeburn  1702: sub inst_directory_query {
                   1703:     my ($srch) = @_;
                   1704:     my $udom = $srch->{'srchdomain'};
                   1705:     my %results;
                   1706:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1707:     my $outcome;
1.899     raeburn  1708:     if ($homeserver ne '') {
1.904     albertel 1709: 	my $queryid=&reply("querysend:instdirsearch:".
                   1710: 			   &escape($srch->{'srchby'}).':'.
                   1711: 			   &escape($srch->{'srchterm'}).':'.
                   1712: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1713: 	my $host=&hostname($homeserver);
                   1714: 	if ($queryid !~/^\Q$host\E\_/) {
                   1715: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1716: 	    return;
                   1717: 	}
                   1718: 	my $response = &get_query_reply($queryid);
                   1719: 	my $maxtries = 5;
                   1720: 	my $tries = 1;
                   1721: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1722: 	    $response = &get_query_reply($queryid);
                   1723: 	    $tries ++;
                   1724: 	}
                   1725: 
                   1726:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1727:             if ($response eq 'unavailable') {
                   1728:                 $outcome = $response;
                   1729:             } else {
                   1730:                 $outcome = 'ok';
                   1731:                 my @matches = split(/\n/,$response);
                   1732:                 foreach my $match (@matches) {
                   1733:                     my ($key,$value) = split(/=/,$match);
                   1734:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1735:                 }
1.899     raeburn  1736:             }
                   1737:         }
                   1738:     }
1.909     raeburn  1739:     return ($outcome,%results);
1.899     raeburn  1740: }
                   1741: 
                   1742: sub usersearch {
                   1743:     my ($srch) = @_;
                   1744:     my $dom = $srch->{'srchdomain'};
                   1745:     my %results;
                   1746:     my %libserv = &all_library();
                   1747:     my $query = 'usersearch';
                   1748:     foreach my $tryserver (keys(%libserv)) {
                   1749:         if (&host_domain($tryserver) eq $dom) {
                   1750:             my $host=&hostname($tryserver);
                   1751:             my $queryid=
1.911     raeburn  1752:                 &reply("querysend:".&escape($query).':'.
                   1753:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1754:                        &escape($srch->{'srchtype'}).':'.
                   1755:                        &escape($srch->{'srchterm'}),$tryserver);
                   1756:             if ($queryid !~/^\Q$host\E\_/) {
                   1757:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1758:                 next;
1.899     raeburn  1759:             }
                   1760:             my $reply = &get_query_reply($queryid);
                   1761:             my $maxtries = 1;
                   1762:             my $tries = 1;
                   1763:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1764:                 $reply = &get_query_reply($queryid);
                   1765:                 $tries ++;
                   1766:             }
                   1767:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1768:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1769:             } else {
1.911     raeburn  1770:                 my @matches;
                   1771:                 if ($reply =~ /\n/) {
                   1772:                     @matches = split(/\n/,$reply);
                   1773:                 } else {
                   1774:                     @matches = split(/\&/,$reply);
                   1775:                 }
1.899     raeburn  1776:                 foreach my $match (@matches) {
                   1777:                     my ($uname,$udom,%userhash);
1.911     raeburn  1778:                     foreach my $entry (split(/:/,$match)) {
                   1779:                         my ($key,$value) =
                   1780:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1781:                         $userhash{$key} = $value;
                   1782:                         if ($key eq 'username') {
                   1783:                             $uname = $value;
                   1784:                         } elsif ($key eq 'domain') {
                   1785:                             $udom = $value;
1.911     raeburn  1786:                         }
1.899     raeburn  1787:                     }
                   1788:                     $results{$uname.':'.$udom} = \%userhash;
                   1789:                 }
                   1790:             }
                   1791:         }
                   1792:     }
                   1793:     return %results;
                   1794: }
                   1795: 
1.912     raeburn  1796: sub get_instuser {
                   1797:     my ($udom,$uname,$id) = @_;
                   1798:     my $homeserver = &domain($udom,'primary');
                   1799:     my ($outcome,%results);
                   1800:     if ($homeserver ne '') {
                   1801:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1802:                            &escape($id).':'.&escape($udom),$homeserver);
                   1803:         my $host=&hostname($homeserver);
                   1804:         if ($queryid !~/^\Q$host\E\_/) {
                   1805:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1806:             return;
                   1807:         }
                   1808:         my $response = &get_query_reply($queryid);
                   1809:         my $maxtries = 5;
                   1810:         my $tries = 1;
                   1811:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1812:             $response = &get_query_reply($queryid);
                   1813:             $tries ++;
                   1814:         }
                   1815:         if (!&error($response) && $response ne 'refused') {
                   1816:             if ($response eq 'unavailable') {
                   1817:                 $outcome = $response;
                   1818:             } else {
                   1819:                 $outcome = 'ok';
                   1820:                 my @matches = split(/\n/,$response);
                   1821:                 foreach my $match (@matches) {
                   1822:                     my ($key,$value) = split(/=/,$match);
                   1823:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1824:                 }
                   1825:             }
                   1826:         }
                   1827:     }
                   1828:     my %userinfo;
                   1829:     if (ref($results{$uname}) eq 'HASH') {
                   1830:         %userinfo = %{$results{$uname}};
                   1831:     } 
                   1832:     return ($outcome,%userinfo);
                   1833: }
                   1834: 
                   1835: sub inst_rulecheck {
1.923     raeburn  1836:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1837:     my %returnhash;
                   1838:     if ($udom ne '') {
                   1839:         if (ref($rules) eq 'ARRAY') {
                   1840:             @{$rules} = map {&escape($_);} (@{$rules});
                   1841:             my $rulestr = join(':',@{$rules});
                   1842:             my $homeserver=&domain($udom,'primary');
                   1843:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1844:                 my $response;
                   1845:                 if ($item eq 'username') {                
                   1846:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1847:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1848:                                               $homeserver));
1.923     raeburn  1849:                 } elsif ($item eq 'id') {
                   1850:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1851:                                               ':'.&escape($id).':'.$rulestr,
                   1852:                                               $homeserver));
1.945     raeburn  1853:                 } elsif ($item eq 'selfcreate') {
                   1854:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1855:                                                &escape($udom).':'.&escape($uname).
                   1856:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1857:                 }
1.912     raeburn  1858:                 if ($response ne 'refused') {
                   1859:                     my @pairs=split(/\&/,$response);
                   1860:                     foreach my $item (@pairs) {
                   1861:                         my ($key,$value)=split(/=/,$item,2);
                   1862:                         $key = &unescape($key);
                   1863:                         next if ($key =~ /^error: 2 /);
                   1864:                         $returnhash{$key}=&thaw_unescape($value);
                   1865:                     }
                   1866:                 }
                   1867:             }
                   1868:         }
                   1869:     }
                   1870:     return %returnhash;
                   1871: }
                   1872: 
                   1873: sub inst_userrules {
1.923     raeburn  1874:     my ($udom,$check) = @_;
1.912     raeburn  1875:     my (%ruleshash,@ruleorder);
                   1876:     if ($udom ne '') {
                   1877:         my $homeserver=&domain($udom,'primary');
                   1878:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1879:             my $response;
                   1880:             if ($check eq 'id') {
                   1881:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1882:                                  $homeserver);
1.943     raeburn  1883:             } elsif ($check eq 'email') {
                   1884:                 $response=&reply('instemailrules:'.&escape($udom),
                   1885:                                  $homeserver);
1.923     raeburn  1886:             } else {
                   1887:                 $response=&reply('instuserrules:'.&escape($udom),
                   1888:                                  $homeserver);
                   1889:             }
1.912     raeburn  1890:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1891:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1892:                 ($response ne 'no_such_host')) {
                   1893:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1894:                 my @pairs=split(/\&/,$hashitems);
                   1895:                 foreach my $item (@pairs) {
                   1896:                     my ($key,$value)=split(/=/,$item,2);
                   1897:                     $key = &unescape($key);
                   1898:                     next if ($key =~ /^error: 2 /);
                   1899:                     $ruleshash{$key}=&thaw_unescape($value);
                   1900:                 }
                   1901:                 my @esc_order = split(/\&/,$orderitems);
                   1902:                 foreach my $item (@esc_order) {
                   1903:                     push(@ruleorder,&unescape($item));
                   1904:                 }
                   1905:             }
                   1906:         }
                   1907:     }
                   1908:     return (\%ruleshash,\@ruleorder);
                   1909: }
                   1910: 
1.976     raeburn  1911: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1912: 
                   1913: sub get_domain_defaults {
                   1914:     my ($domain) = @_;
                   1915:     my $cachetime = 60*60*24;
                   1916:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1917:     if (defined($cached)) {
                   1918:         if (ref($result) eq 'HASH') {
                   1919:             return %{$result};
                   1920:         }
                   1921:     }
                   1922:     my %domdefaults;
                   1923:     my %domconfig =
1.989     raeburn  1924:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1925:                                   'requestcourses','inststatus',
1.1073    raeburn  1926:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1927:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1928:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1929:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1930:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1931:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1932:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  1933:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  1934:     } else {
                   1935:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1936:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1937:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1938:     }
1.976     raeburn  1939:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1940:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1941:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1942:         } else {
                   1943:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1944:         } 
                   1945:         my @usertools = ('aboutme','blog','portfolio');
                   1946:         foreach my $item (@usertools) {
                   1947:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1948:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1949:             }
                   1950:         }
                   1951:     }
1.985     raeburn  1952:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1953:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1954:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1955:         }
                   1956:     }
1.989     raeburn  1957:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1958:         foreach my $item ('inststatustypes','inststatusorder') {
                   1959:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1960:         }
                   1961:     }
1.1047    raeburn  1962:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1963:         foreach my $item ('canuse_pdfforms') {
                   1964:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1965:         }
                   1966:     }
1.1073    raeburn  1967:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1968:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1969:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1970:         }
                   1971:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1972:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1973:         }
                   1974:     }
1.943     raeburn  1975:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1976:                                   $cachetime);
                   1977:     return %domdefaults;
                   1978: }
                   1979: 
1.344     www      1980: # --------------------------------------------------- Assign a key to a student
                   1981: 
                   1982: sub assign_access_key {
1.364     www      1983: #
                   1984: # a valid key looks like uname:udom#comments
                   1985: # comments are being appended
                   1986: #
1.498     www      1987:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1988:     $kdom=
1.620     albertel 1989:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1990:     $knum=
1.620     albertel 1991:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1992:     $cdom=
1.620     albertel 1993:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1994:     $cnum=
1.620     albertel 1995:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1996:     $udom=$env{'user.name'} unless (defined($udom));
                   1997:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1998:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1999:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2000:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2001:                                                   # assigned to this person
                   2002:                                                   # - this should not happen,
1.345     www      2003:                                                   # unless something went wrong
                   2004:                                                   # the first time around
                   2005: # ready to assign
1.364     www      2006:         $logentry=$1.'; '.$logentry;
1.496     www      2007:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2008:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2009: # key now belongs to user
1.346     www      2010: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2011:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2012:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2013:                 return 'ok';
                   2014:             } else {
                   2015:                 return 
                   2016:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2017: 	    }
                   2018:         } else {
                   2019:             return 'error: Could not assign key, try again later.';
                   2020:         }
1.364     www      2021:     } elsif (!$existing{$ckey}) {
1.345     www      2022: # the key does not exist
                   2023: 	return 'error: The key does not exist';
                   2024:     } else {
                   2025: # the key is somebody else's
                   2026: 	return 'error: The key is already in use';
                   2027:     }
1.344     www      2028: }
                   2029: 
1.364     www      2030: # ------------------------------------------ put an additional comment on a key
                   2031: 
                   2032: sub comment_access_key {
                   2033: #
                   2034: # a valid key looks like uname:udom#comments
                   2035: # comments are being appended
                   2036: #
                   2037:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2038:     $cdom=
1.620     albertel 2039:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2040:     $cnum=
1.620     albertel 2041:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2042:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2043:     if ($existing{$ckey}) {
                   2044:         $existing{$ckey}.='; '.$logentry;
                   2045: # ready to assign
1.367     www      2046:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2047:                                                  $cdom,$cnum) eq 'ok') {
                   2048: 	    return 'ok';
                   2049:         } else {
                   2050: 	    return 'error: Count not store comment.';
                   2051:         }
                   2052:     } else {
                   2053: # the key does not exist
                   2054: 	return 'error: The key does not exist';
                   2055:     }
                   2056: }
                   2057: 
1.344     www      2058: # ------------------------------------------------------ Generate a set of keys
                   2059: 
                   2060: sub generate_access_keys {
1.364     www      2061:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2062:     $cdom=
1.620     albertel 2063:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2064:     $cnum=
1.620     albertel 2065:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2066:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2067:     unless (($cdom) && ($cnum)) { return 0; }
                   2068:     if ($number>10000) { return 0; }
                   2069:     sleep(2); # make sure don't get same seed twice
                   2070:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2071:     my $total=0;
                   2072:     for (my $i=1;$i<=$number;$i++) {
                   2073:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2074:                   sprintf("%lx",int(100000*rand)).'-'.
                   2075:                   sprintf("%lx",int(100000*rand));
                   2076:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2077:        $newkey=~s/0/h/g; # and also 0 and O
                   2078:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2079:        if ($existing{$newkey}) {
                   2080:            $i--;
                   2081:        } else {
1.364     www      2082: 	  if (&put('accesskeys',
                   2083:               { $newkey => '# generated '.localtime().
1.620     albertel 2084:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2085:                            '; '.$logentry },
                   2086: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2087:               $total++;
                   2088: 	  }
                   2089:        }
                   2090:     }
1.620     albertel 2091:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2092:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2093:     return $total;
                   2094: }
                   2095: 
                   2096: # ------------------------------------------------------- Validate an accesskey
                   2097: 
                   2098: sub validate_access_key {
                   2099:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2100:     $cdom=
1.620     albertel 2101:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2102:     $cnum=
1.620     albertel 2103:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2104:     $udom=$env{'user.domain'} unless (defined($udom));
                   2105:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2106:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2107:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2108: }
                   2109: 
                   2110: # ------------------------------------- Find the section of student in a course
1.652     albertel 2111: sub devalidate_getsection_cache {
                   2112:     my ($udom,$unam,$courseid)=@_;
                   2113:     my $hashid="$udom:$unam:$courseid";
                   2114:     &devalidate_cache_new('getsection',$hashid);
                   2115: }
1.298     matthew  2116: 
1.815     albertel 2117: sub courseid_to_courseurl {
                   2118:     my ($courseid) = @_;
                   2119:     #already url style courseid
                   2120:     return $courseid if ($courseid =~ m{^/});
                   2121: 
                   2122:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2123: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2124: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2125: 	return "/$cdom/$cnum";
                   2126:     }
                   2127: 
                   2128:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2129:     if (exists($courseinfo{'num'})) {
                   2130: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2131:     }
                   2132: 
                   2133:     return undef;
                   2134: }
                   2135: 
1.298     matthew  2136: sub getsection {
                   2137:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2138:     my $cachetime=1800;
1.551     albertel 2139: 
                   2140:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2141:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2142:     if (defined($cached)) { return $result; }
                   2143: 
1.298     matthew  2144:     my %Pending; 
                   2145:     my %Expired;
                   2146:     #
                   2147:     # Each role can either have not started yet (pending), be active, 
                   2148:     #    or have expired.
                   2149:     #
                   2150:     # If there is an active role, we are done.
                   2151:     #
                   2152:     # If there is more than one role which has not started yet, 
                   2153:     #     choose the one which will start sooner
                   2154:     # If there is one role which has not started yet, return it.
                   2155:     #
                   2156:     # If there is more than one expired role, choose the one which ended last.
                   2157:     # If there is a role which has expired, return it.
                   2158:     #
1.815     albertel 2159:     $courseid = &courseid_to_courseurl($courseid);
1.1086    raeburn  2160:     my $extra = &freeze_escape({'skipcheck' => 1});
                   2161:     my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817     raeburn  2162:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2163:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2164:         my $section=$1;
                   2165:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2166:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2167:         my $now=time;
1.548     albertel 2168:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2169:             $Expired{$end}=$section;
                   2170:             next;
                   2171:         }
1.548     albertel 2172:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2173:             $Pending{$start}=$section;
                   2174:             next;
                   2175:         }
1.599     albertel 2176:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2177:     }
                   2178:     #
                   2179:     # Presumedly there will be few matching roles from the above
                   2180:     # loop and the sorting time will be negligible.
                   2181:     if (scalar(keys(%Pending))) {
                   2182:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2183:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2184:     } 
                   2185:     if (scalar(keys(%Expired))) {
                   2186:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2187:         my $time = pop(@sorted);
1.599     albertel 2188:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2189:     }
1.599     albertel 2190:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2191: }
1.70      www      2192: 
1.599     albertel 2193: sub save_cache {
                   2194:     &purge_remembered();
1.722     albertel 2195:     #&Apache::loncommon::validate_page();
1.620     albertel 2196:     undef(%env);
1.780     albertel 2197:     undef($env_loaded);
1.599     albertel 2198: }
1.452     albertel 2199: 
1.599     albertel 2200: my $to_remember=-1;
                   2201: my %remembered;
                   2202: my %accessed;
                   2203: my $kicks=0;
                   2204: my $hits=0;
1.849     albertel 2205: sub make_key {
                   2206:     my ($name,$id) = @_;
1.872     albertel 2207:     if (length($id) > 65 
                   2208: 	&& length(&escape($id)) > 200) {
                   2209: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2210:     }
1.849     albertel 2211:     return &escape($name.':'.$id);
                   2212: }
                   2213: 
1.599     albertel 2214: sub devalidate_cache_new {
                   2215:     my ($name,$id,$debug) = @_;
                   2216:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2217:     $id=&make_key($name,$id);
1.599     albertel 2218:     $memcache->delete($id);
                   2219:     delete($remembered{$id});
                   2220:     delete($accessed{$id});
                   2221: }
                   2222: 
                   2223: sub is_cached_new {
                   2224:     my ($name,$id,$debug) = @_;
1.849     albertel 2225:     $id=&make_key($name,$id);
1.599     albertel 2226:     if (exists($remembered{$id})) {
1.1133    foxr     2227: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2228: 	$accessed{$id}=[&gettimeofday()];
                   2229: 	$hits++;
                   2230: 	return ($remembered{$id},1);
                   2231:     }
                   2232:     my $value = $memcache->get($id);
                   2233:     if (!(defined($value))) {
                   2234: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2235: 	return (undef,undef);
1.416     albertel 2236:     }
1.599     albertel 2237:     if ($value eq '__undef__') {
                   2238: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2239: 	$value=undef;
                   2240:     }
                   2241:     &make_room($id,$value,$debug);
                   2242:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2243:     return ($value,1);
                   2244: }
                   2245: 
                   2246: sub do_cache_new {
                   2247:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2248:     $id=&make_key($name,$id);
1.599     albertel 2249:     my $setvalue=$value;
                   2250:     if (!defined($setvalue)) {
                   2251: 	$setvalue='__undef__';
                   2252:     }
1.623     albertel 2253:     if (!defined($time) ) {
                   2254: 	$time=600;
                   2255:     }
1.599     albertel 2256:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2257:     my $result = $memcache->set($id,$setvalue,$time);
                   2258:     if (! $result) {
1.872     albertel 2259: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2260: 	$memcache->disconnect_all();
1.872     albertel 2261:     }
1.600     albertel 2262:     # need to make a copy of $value
1.919     albertel 2263:     &make_room($id,$value,$debug);
1.599     albertel 2264:     return $value;
                   2265: }
                   2266: 
                   2267: sub make_room {
                   2268:     my ($id,$value,$debug)=@_;
1.919     albertel 2269: 
                   2270:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2271:                                     : $value;
1.599     albertel 2272:     if ($to_remember<0) { return; }
                   2273:     $accessed{$id}=[&gettimeofday()];
                   2274:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2275:     my $to_kick;
                   2276:     my $max_time=0;
                   2277:     foreach my $other (keys(%accessed)) {
                   2278: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2279: 	    $to_kick=$other;
                   2280: 	    $max_time=&tv_interval($accessed{$other});
                   2281: 	}
                   2282:     }
                   2283:     delete($remembered{$to_kick});
                   2284:     delete($accessed{$to_kick});
                   2285:     $kicks++;
                   2286:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2287:     return;
                   2288: }
                   2289: 
1.599     albertel 2290: sub purge_remembered {
1.604     albertel 2291:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2292:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2293:     undef(%remembered);
                   2294:     undef(%accessed);
1.428     albertel 2295: }
1.70      www      2296: # ------------------------------------- Read an entry from a user's environment
                   2297: 
                   2298: sub userenvironment {
                   2299:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2300:     my $items;
                   2301:     foreach my $item (@what) {
                   2302:         $items.=&escape($item).'&';
                   2303:     }
                   2304:     $items=~s/\&$//;
1.70      www      2305:     my %returnhash=();
1.1009    raeburn  2306:     my $uhome = &homeserver($unam,$udom);
                   2307:     unless ($uhome eq 'no_host') {
                   2308:         my @answer=split(/\&/, 
                   2309:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2310:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2311:             return %returnhash;
                   2312:         }
1.1009    raeburn  2313:         my $i;
                   2314:         for ($i=0;$i<=$#what;$i++) {
                   2315: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2316:         }
1.70      www      2317:     }
                   2318:     return %returnhash;
1.1       albertel 2319: }
                   2320: 
1.617     albertel 2321: # ---------------------------------------------------------- Get a studentphoto
                   2322: sub studentphoto {
                   2323:     my ($udom,$unam,$ext) = @_;
                   2324:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2325:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2326:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2327:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2328:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2329:             } else {
                   2330:                 my ($result,$perm_reqd)=
1.707     albertel 2331: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2332:                 if ($result eq 'ok') {
                   2333:                     if (!($perm_reqd eq 'yes')) {
                   2334:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2335:                     }
                   2336:                 }
                   2337:             }
                   2338:         }
                   2339:     } else {
                   2340:         my ($result,$perm_reqd) = 
1.707     albertel 2341: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2342:         if ($result eq 'ok') {
                   2343:             if (!($perm_reqd eq 'yes')) {
                   2344:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2345:             }
                   2346:         }
                   2347:     }
                   2348:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2349: }
                   2350: 
                   2351: sub retrievestudentphoto {
                   2352:     my ($udom,$unam,$ext,$type) = @_;
                   2353:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2354:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2355:     if ($ret eq 'ok') {
                   2356:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2357:         if ($type eq 'thumbnail') {
                   2358:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2359:         }
                   2360:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2361:         return $tokenurl;
                   2362:     } else {
                   2363:         if ($type eq 'thumbnail') {
                   2364:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2365:         } else { 
                   2366:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2367:         }
1.617     albertel 2368:     }
                   2369: }
                   2370: 
1.263     www      2371: # -------------------------------------------------------------------- New chat
                   2372: 
                   2373: sub chatsend {
1.724     raeburn  2374:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2375:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2376:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2377:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2378:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2379: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2380: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2381: }
                   2382: 
                   2383: # ------------------------------------------ Find current version of a resource
                   2384: 
                   2385: sub getversion {
                   2386:     my $fname=&clutter(shift);
                   2387:     unless ($fname=~/^\/res\//) { return -1; }
                   2388:     return &currentversion(&filelocation('',$fname));
                   2389: }
                   2390: 
                   2391: sub currentversion {
                   2392:     my $fname=shift;
                   2393:     my $author=$fname;
                   2394:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2395:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2396:     my $home=&homeserver($uname,$udom);
1.292     www      2397:     if ($home eq 'no_host') { 
                   2398:         return -1; 
                   2399:     }
1.1112    www      2400:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2401:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2402: 	return -1;
                   2403:     }
1.1112    www      2404:     return $answer;
1.263     www      2405: }
                   2406: 
1.1111    www      2407: #
                   2408: # Return special version number of resource if set by override, empty otherwise
                   2409: #
                   2410: sub usedversion {
                   2411:     my $fname=shift;
                   2412:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2413:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2414:     if ($urlversion) { return $urlversion; }
                   2415:     return '';
                   2416: }
                   2417: 
1.1       albertel 2418: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2419: 
1.1       albertel 2420: sub subscribe {
                   2421:     my $fname=shift;
1.761     raeburn  2422:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2423:     $fname=~s/[\n\r]//g;
1.1       albertel 2424:     my $author=$fname;
                   2425:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2426:     my ($udom,$uname)=split(/\//,$author);
                   2427:     my $home=homeserver($uname,$udom);
1.335     albertel 2428:     if ($home eq 'no_host') {
                   2429:         return 'not_found';
1.1       albertel 2430:     }
                   2431:     my $answer=reply("sub:$fname",$home);
1.64      www      2432:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2433: 	$answer.=' by '.$home;
                   2434:     }
1.1       albertel 2435:     return $answer;
                   2436: }
                   2437:     
1.8       www      2438: # -------------------------------------------------------------- Replicate file
                   2439: 
                   2440: sub repcopy {
                   2441:     my $filename=shift;
1.23      www      2442:     $filename=~s/\/+/\//g;
1.1142    raeburn  2443:     my $londocroot = $perlvar{'lonDocRoot'};
                   2444:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
                   2445:     if ($filename=~m{^\Q$londocroot/lonUsers/\E}) { return 'ok'; }
                   2446:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2447: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2448: 	return &repcopy_userfile($filename);
                   2449:     }
1.532     albertel 2450:     $filename=~s/[\n\r]//g;
1.8       www      2451:     my $transname="$filename.in.transfer";
1.828     www      2452: # FIXME: this should flock
1.607     raeburn  2453:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2454:     my $remoteurl=subscribe($filename);
1.64      www      2455:     if ($remoteurl =~ /^con_lost by/) {
                   2456: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2457:            return 'unavailable';
1.8       www      2458:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2459: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2460: 	   return 'not_found';
1.64      www      2461:     } elsif ($remoteurl =~ /^rejected by/) {
                   2462: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2463:            return 'forbidden';
1.20      www      2464:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2465:            return 'ok';
1.8       www      2466:     } else {
1.290     www      2467:         my $author=$filename;
                   2468:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2469:         my ($udom,$uname)=split(/\//,$author);
                   2470:         my $home=homeserver($uname,$udom);
                   2471:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2472:            my @parts=split(/\//,$filename);
                   2473:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2474:            if ($path ne "$londocroot/res") {
1.8       www      2475:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2476: 	       return 'bad_request';
1.8       www      2477:            }
                   2478:            my $count;
                   2479:            for ($count=5;$count<$#parts;$count++) {
                   2480:                $path.="/$parts[$count]";
                   2481:                if ((-e $path)!=1) {
                   2482: 		   mkdir($path,0777);
                   2483:                }
                   2484:            }
                   2485:            my $ua=new LWP::UserAgent;
                   2486:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2487:            my $response=$ua->request($request,$transname);
                   2488:            if ($response->is_error()) {
                   2489: 	       unlink($transname);
                   2490:                my $message=$response->status_line;
1.672     albertel 2491:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2492:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2493:                return 'unavailable';
1.8       www      2494:            } else {
1.16      www      2495: 	       if ($remoteurl!~/\.meta$/) {
                   2496:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2497:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2498:                   if ($mresponse->is_error()) {
                   2499: 		      unlink($filename.'.meta');
                   2500:                       &logthis(
1.672     albertel 2501:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2502:                   }
                   2503: 	       }
1.8       www      2504:                rename($transname,$filename);
1.607     raeburn  2505:                return 'ok';
1.8       www      2506:            }
1.290     www      2507:        }
1.8       www      2508:     }
1.330     www      2509: }
                   2510: 
                   2511: # ------------------------------------------------ Get server side include body
                   2512: sub ssi_body {
1.381     albertel 2513:     my ($filelink,%form)=@_;
1.606     matthew  2514:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2515:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2516:     }
1.953     www      2517:     my $output='';
                   2518:     my $response;
1.980     raeburn  2519:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2520:        ($output,$response)=&externalssi($filelink);
1.953     www      2521:     } else {
1.1004    droeschl 2522:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2523:        $filelink .= 'inhibitmenu=yes';
1.953     www      2524:        ($output,$response)=&ssi($filelink,%form);
                   2525:     }
1.778     albertel 2526:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2527:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2528:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2529:     if (wantarray) {
                   2530:         return ($output, $response);
                   2531:     } else {
                   2532:         return $output;
                   2533:     }
1.8       www      2534: }
                   2535: 
1.15      www      2536: # --------------------------------------------------------- Server Side Include
                   2537: 
1.782     albertel 2538: sub absolute_url {
                   2539:     my ($host_name) = @_;
                   2540:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2541:     if ($host_name eq '') {
                   2542: 	$host_name = $ENV{'SERVER_NAME'};
                   2543:     }
                   2544:     return $protocol.$host_name;
                   2545: }
                   2546: 
1.942     foxr     2547: #
                   2548: #   Server side include.
                   2549: # Parameters:
                   2550: #  fn     Possibly encrypted resource name/id.
                   2551: #  form   Hash that describes how the rendering should be done
                   2552: #         and other things.
1.944     foxr     2553: # Returns:
1.950     raeburn  2554: #   Scalar context: The content of the response.
                   2555: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2556: #     
1.15      www      2557: sub ssi {
                   2558: 
1.944     foxr     2559:     my ($fn,%form)=@_;
1.15      www      2560:     my $ua=new LWP::UserAgent;
1.23      www      2561:     my $request;
1.711     albertel 2562: 
                   2563:     $form{'no_update_last_known'}=1;
1.895     albertel 2564:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2565:     if (%form) {
1.782     albertel 2566:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2567:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2568:     } else {
1.782     albertel 2569:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2570:     }
                   2571: 
1.15      www      2572:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   2573:     my $response=$ua->request($request);
                   2574: 
1.944     foxr     2575:     if (wantarray) {
                   2576: 	return ($response->content, $response);
                   2577:     } else {
                   2578: 	return $response->content;
1.942     foxr     2579:     }
1.324     www      2580: }
                   2581: 
                   2582: sub externalssi {
                   2583:     my ($url)=@_;
                   2584:     my $ua=new LWP::UserAgent;
                   2585:     my $request=new HTTP::Request('GET',$url);
                   2586:     my $response=$ua->request($request);
1.954     raeburn  2587:     if (wantarray) {
                   2588:         return ($response->content, $response);
                   2589:     } else {
                   2590:         return $response->content;
                   2591:     }
1.15      www      2592: }
1.254     www      2593: 
1.492     albertel 2594: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2595: 
                   2596: sub allowuploaded {
                   2597:     my ($srcurl,$url)=@_;
                   2598:     $url=&clutter(&declutter($url));
                   2599:     my $dir=$url;
                   2600:     $dir=~s/\/[^\/]+$//;
                   2601:     my %httpref=();
                   2602:     my $httpurl=&hreflocation('',$url);
                   2603:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2604:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2605: }
1.477     raeburn  2606: 
1.478     albertel 2607: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2608: # input: action, courseID, current domain, intended
1.637     raeburn  2609: #        path to file, source of file, instruction to parse file for objects,
                   2610: #        ref to hash for embedded objects,
                   2611: #        ref to hash for codebase of java objects.
1.1095    raeburn  2612: #        reference to scalar to accommodate mime type determined
                   2613: #          from File::MMagic if $parser = parse.
1.637     raeburn  2614: #
1.485     raeburn  2615: # output: url to file (if action was uploaddoc), 
                   2616: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2617: #
1.478     albertel 2618: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2619: # course.
1.477     raeburn  2620: #
1.478     albertel 2621: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2622: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2623: #          course's home server.
1.477     raeburn  2624: #
1.478     albertel 2625: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2626: #          be copied from $source (current location) to 
                   2627: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2628: #         and will then be copied to
                   2629: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2630: #         course's home server.
1.485     raeburn  2631: #
1.481     raeburn  2632: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2633: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2634: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2635: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2636: #         in course's home server.
1.637     raeburn  2637: #
1.477     raeburn  2638: 
                   2639: sub process_coursefile {
1.1095    raeburn  2640:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2641:         $mimetype)=@_;
1.477     raeburn  2642:     my $fetchresult;
1.638     albertel 2643:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2644:     if ($action eq 'propagate') {
1.638     albertel 2645:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2646: 			     $home);
1.481     raeburn  2647:     } else {
1.477     raeburn  2648:         my $fpath = '';
                   2649:         my $fname = $file;
1.478     albertel 2650:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2651:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2652:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2653:         if ($action eq 'copy') {
                   2654:             if ($source eq '') {
                   2655:                 $fetchresult = 'no source file';
                   2656:                 return $fetchresult;
                   2657:             } else {
                   2658:                 my $destination = $filepath.'/'.$fname;
                   2659:                 rename($source,$destination);
                   2660:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2661:                                  $home);
1.481     raeburn  2662:             }
                   2663:         } elsif ($action eq 'uploaddoc') {
                   2664:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2665:             print $fh $env{'form.'.$source};
1.481     raeburn  2666:             close($fh);
1.637     raeburn  2667:             if ($parser eq 'parse') {
1.1024    raeburn  2668:                 my $mm = new File::MMagic;
1.1095    raeburn  2669:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2670:                 if ($type eq 'text/html') {
1.1024    raeburn  2671:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2672:                     unless ($parse_result eq 'ok') {
                   2673:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2674:                     }
1.637     raeburn  2675:                 }
1.1095    raeburn  2676:                 if (ref($mimetype)) {
                   2677:                     $$mimetype = $type;
                   2678:                 } 
1.637     raeburn  2679:             }
1.477     raeburn  2680:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2681:                                  $home);
1.481     raeburn  2682:             if ($fetchresult eq 'ok') {
                   2683:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2684:             } else {
                   2685:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2686:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2687:                 return '/adm/notfound.html';
                   2688:             }
1.477     raeburn  2689:         }
                   2690:     }
1.485     raeburn  2691:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2692:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2693:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2694:     }
                   2695:     return $fetchresult;
                   2696: }
                   2697: 
1.637     raeburn  2698: sub build_filepath {
                   2699:     my ($fpath) = @_;
                   2700:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2701:     unless ($fpath eq '') {
                   2702:         my @parts=split('/',$fpath);
                   2703:         foreach my $part (@parts) {
                   2704:             $filepath.= '/'.$part;
                   2705:             if ((-e $filepath)!=1) {
                   2706:                 mkdir($filepath,0777);
                   2707:             }
                   2708:         }
                   2709:     }
                   2710:     return $filepath;
                   2711: }
                   2712: 
                   2713: sub store_edited_file {
1.638     albertel 2714:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2715:     my $file = $primary_url;
                   2716:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2717:     my $fpath = '';
                   2718:     my $fname = $file;
                   2719:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2720:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2721:     my $filepath = &build_filepath($fpath);
                   2722:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2723:     print $fh $content;
                   2724:     close($fh);
1.638     albertel 2725:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2726:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2727: 			  $home);
1.637     raeburn  2728:     if ($$fetchresult eq 'ok') {
                   2729:         return '/uploaded/'.$fpath.'/'.$fname;
                   2730:     } else {
1.638     albertel 2731:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2732: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2733:         return '/adm/notfound.html';
                   2734:     }
                   2735: }
                   2736: 
1.531     albertel 2737: sub clean_filename {
1.831     albertel 2738:     my ($fname,$args)=@_;
1.315     www      2739: # Replace Windows backslashes by forward slashes
1.257     www      2740:     $fname=~s/\\/\//g;
1.831     albertel 2741:     if (!$args->{'keep_path'}) {
                   2742:         # Get rid of everything but the actual filename
                   2743: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2744:     }
1.315     www      2745: # Replace spaces by underscores
                   2746:     $fname=~s/\s+/\_/g;
                   2747: # Replace all other weird characters by nothing
1.831     albertel 2748:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2749: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2750: # numbers
                   2751:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2752:     return $fname;
                   2753: }
1.1051    raeburn  2754: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2755: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2756: # image with the same aspect ratio as the original, but with dimensions which do 
                   2757: # not exceed $resizewidth and $resizeheight.
                   2758:  
1.984     neumanie 2759: sub resizeImage {
1.1051    raeburn  2760:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2761:     my $ima = Image::Magick->new;
                   2762:     my $resized;
                   2763:     if (-e $img_path) {
                   2764:         $ima->Read($img_path);
                   2765:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2766:             my $width = $ima->Get('width');
                   2767:             my $height = $ima->Get('height');
                   2768:             if ($width > $resizewidth) {
                   2769: 	        my $factor = $width/$resizewidth;
                   2770:                 my $newheight = $height/$factor;
                   2771:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2772:                 $resized = 1;
                   2773:             }
                   2774:         }
                   2775:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2776:             my $width = $ima->Get('width');
                   2777:             my $height = $ima->Get('height');
                   2778:             if ($height > $resizeheight) {
                   2779:                 my $factor = $height/$resizeheight;
                   2780:                 my $newwidth = $width/$factor;
                   2781:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2782:                 $resized = 1;
                   2783:             }
                   2784:         }
                   2785:         if ($resized) {
                   2786:             $ima->Write($img_path);
                   2787:         }
                   2788:     }
                   2789:     return;
1.977     amueller 2790: }
                   2791: 
1.608     albertel 2792: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2793: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  2794: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  2795: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   2796: #                                    canceloverwrite, or ''. 
                   2797: #                   if 'coursedoc': upload to the current course
                   2798: #                   if 'existingfile': write file to tmp/overwrites directory 
                   2799: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   2800: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 2801: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2802: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2803: #        $allfiles - reference to hash for embedded objects
                   2804: #        $codebase - reference to hash for codebase of java objects
                   2805: #        $desuname - username for permanent storage of uploaded file
                   2806: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2807: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2808: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2809: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2810: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  2811: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  2812: #                    from File::MMagic.
1.858     raeburn  2813: # 
1.686     albertel 2814: # output: url of file in userspace, or error: <message> 
                   2815: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2816: 
1.531     albertel 2817: sub userfileupload {
1.1090    raeburn  2818:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  2819:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 2820:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2821:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2822:     $fname=&clean_filename($fname);
1.1090    raeburn  2823:     # See if there is anything left
1.257     www      2824:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  2825:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   2826:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   2827:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   2828:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  2829:         my $now = time;
1.1090    raeburn  2830:         my $filepath;
1.1095    raeburn  2831:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  2832:              $filepath = 'tmp/helprequests/'.$now;
                   2833:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   2834:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2835:                          '_'.$env{'user.domain'}.'/pending';
                   2836:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   2837:             my ($docuname,$docudom);
                   2838:             if ($destudom) {
                   2839:                 $docudom = $destudom;
                   2840:             } else {
                   2841:                 $docudom = $env{'user.domain'};
                   2842:             }
                   2843:             if ($destuname) {
                   2844:                 $docuname = $destuname;
                   2845:             } else {
                   2846:                 $docuname = $env{'user.name'};
                   2847:             }
                   2848:             if (exists($env{'form.group'})) {
                   2849:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2850:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2851:             }
                   2852:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   2853:             if ($context eq 'canceloverwrite') {
                   2854:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   2855:                 if (-e  $tempfile) {
                   2856:                     my @info = stat($tempfile);
                   2857:                     if ($info[9] eq $env{'form.timestamp'}) {
                   2858:                         unlink($tempfile);
                   2859:                     }
                   2860:                 }
                   2861:                 return;
1.523     raeburn  2862:             }
                   2863:         }
1.1090    raeburn  2864:         # Create the directory if not present
1.741     raeburn  2865:         my @parts=split(/\//,$filepath);
                   2866:         my $fullpath = $perlvar{'lonDaemons'};
                   2867:         for (my $i=0;$i<@parts;$i++) {
                   2868:             $fullpath .= '/'.$parts[$i];
                   2869:             if ((-e $fullpath)!=1) {
                   2870:                 mkdir($fullpath,0777);
                   2871:             }
                   2872:         }
                   2873:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2874:         print $fh $env{'form.'.$formname};
                   2875:         close($fh);
1.1090    raeburn  2876:         if ($context eq 'existingfile') {
                   2877:             my @info = stat($fullpath.'/'.$fname);
                   2878:             return ($fullpath.'/'.$fname,$info[9]);
                   2879:         } else {
                   2880:             return $fullpath.'/'.$fname;
                   2881:         }
1.523     raeburn  2882:     }
1.995     raeburn  2883:     if ($subdir eq 'scantron') {
                   2884:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  2885:     } else {
1.995     raeburn  2886:         $fname="$subdir/$fname";
                   2887:     }
1.1090    raeburn  2888:     if ($context eq 'coursedoc') {
1.638     albertel 2889: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2890: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2891:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2892:             return &finishuserfileupload($docuname,$docudom,
                   2893: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2894: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  2895:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  2896:         } else {
1.620     albertel 2897:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2898:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2899: 				       $fname,$formname,$parser,
1.1095    raeburn  2900: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  2901:         }
1.719     banghart 2902:     } elsif (defined($destuname)) {
                   2903:         my $docuname=$destuname;
                   2904:         my $docudom=$destudom;
1.860     raeburn  2905: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2906: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2907:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2908:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2909:     } else {
1.638     albertel 2910:         my $docuname=$env{'user.name'};
                   2911:         my $docudom=$env{'user.domain'};
1.714     raeburn  2912:         if (exists($env{'form.group'})) {
                   2913:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2914:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2915:         }
1.860     raeburn  2916: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2917: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2918:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2919:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2920:     }
1.271     www      2921: }
                   2922: 
                   2923: sub finishuserfileupload {
1.860     raeburn  2924:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  2925:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  2926:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2927:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2928:   
1.860     raeburn  2929:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2930:     $file=$fname;
                   2931:     if ($fname=~m|/|) {
                   2932:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2933: 	$path.=$fnamepath.'/';
                   2934:     }
1.259     www      2935:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2936:     my $count;
                   2937:     for ($count=4;$count<=$#parts;$count++) {
                   2938:         $filepath.="/$parts[$count]";
                   2939:         if ((-e $filepath)!=1) {
                   2940: 	    mkdir($filepath,0777);
                   2941:         }
                   2942:     }
1.984     neumanie 2943: 
1.258     www      2944: # Save the file
                   2945:     {
1.701     albertel 2946: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2947: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2948: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2949: 	    return '/adm/notfound.html';
                   2950: 	}
1.1090    raeburn  2951:         if ($context eq 'overwrite') {
1.1117    foxr     2952:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  2953:             my $target = $filepath.'/'.$file;
                   2954:             if (-e $source) {
                   2955:                 my @info = stat($source);
                   2956:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   2957:                     unless (&File::Copy::move($source,$target)) {
                   2958:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   2959:                         return "Moving from $source failed";
                   2960:                     }
                   2961:                 } else {
                   2962:                     return "Temporary file: $source had unexpected date/time for last modification";
                   2963:                 }
                   2964:             } else {
                   2965:                 return "Temporary file: $source missing";
                   2966:             }
                   2967:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 2968: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2969: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2970: 	    return '/adm/notfound.html';
                   2971: 	}
1.570     albertel 2972: 	close(FH);
1.1051    raeburn  2973:         if ($resizewidth && $resizeheight) {
                   2974:             my $mm = new File::MMagic;
                   2975:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2976:             if ($mime_type =~ m{^image/}) {
                   2977: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2978:             }  
1.977     amueller 2979: 	}
1.258     www      2980:     }
1.1152    raeburn  2981:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   2982:         if (ref($mimetype)) {
                   2983:             if ($$mimetype eq '') {
                   2984:                 my $mm = new File::MMagic;
                   2985:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   2986:                 $$mimetype = $type;
                   2987:             }
                   2988:         }
                   2989:     }
1.637     raeburn  2990:     if ($parser eq 'parse') {
1.1152    raeburn  2991:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  2992:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2993:                                                        $allfiles,$codebase);
                   2994:             unless ($parse_result eq 'ok') {
                   2995:                 &logthis('Failed to parse '.$filepath.$file.
                   2996: 	   	         ' for embedded media: '.$parse_result); 
                   2997:             }
1.637     raeburn  2998:         }
                   2999:     }
1.860     raeburn  3000:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3001:         my $input = $filepath.'/'.$file;
                   3002:         my $output = $filepath.'/'.'tn-'.$file;
                   3003:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3004:         system("convert -sample $thumbsize $input $output");
                   3005:         if (-e $filepath.'/'.'tn-'.$file) {
                   3006:             $fetchthumb  = 1; 
                   3007:         }
                   3008:     }
1.858     raeburn  3009:  
1.259     www      3010: # Notify homeserver to grep it
                   3011: #
1.984     neumanie 3012:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3013:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3014:     if ($fetchresult eq 'ok') {
1.860     raeburn  3015:         if ($fetchthumb) {
                   3016:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3017:             if ($thumbresult ne 'ok') {
                   3018:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3019:                          $docuhome.': '.$thumbresult);
                   3020:             }
                   3021:         }
1.259     www      3022: #
1.258     www      3023: # Return the URL to it
1.494     albertel 3024:         return '/uploaded/'.$path.$file;
1.263     www      3025:     } else {
1.494     albertel 3026:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3027: 		 ': '.$fetchresult);
1.263     www      3028:         return '/adm/notfound.html';
1.858     raeburn  3029:     }
1.493     albertel 3030: }
                   3031: 
1.637     raeburn  3032: sub extract_embedded_items {
1.961     raeburn  3033:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3034:     my @state = ();
                   3035:     my %javafiles = (
                   3036:                       codebase => '',
                   3037:                       code => '',
                   3038:                       archive => ''
                   3039:                     );
                   3040:     my %mediafiles = (
                   3041:                       src => '',
                   3042:                       movie => '',
                   3043:                      );
1.648     raeburn  3044:     my $p;
                   3045:     if ($content) {
                   3046:         $p = HTML::LCParser->new($content);
                   3047:     } else {
1.961     raeburn  3048:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3049:     }
1.641     albertel 3050:     while (my $t=$p->get_token()) {
1.640     albertel 3051: 	if ($t->[0] eq 'S') {
                   3052: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3053: 	    push(@state, $tagname);
1.648     raeburn  3054:             if (lc($tagname) eq 'allow') {
                   3055:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3056:             }
1.640     albertel 3057: 	    if (lc($tagname) eq 'img') {
                   3058: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3059: 	    }
1.886     albertel 3060: 	    if (lc($tagname) eq 'a') {
                   3061: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   3062: 	    }
1.645     raeburn  3063:             if (lc($tagname) eq 'script') {
                   3064:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3065:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3066:                 } else {
                   3067:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   3068:                 }
                   3069:             }
                   3070:             if (lc($tagname) eq 'link') {
                   3071:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3072:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3073:                 }
                   3074:             }
1.640     albertel 3075: 	    if (lc($tagname) eq 'object' ||
                   3076: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3077: 		foreach my $item (keys(%javafiles)) {
                   3078: 		    $javafiles{$item} = '';
                   3079: 		}
                   3080: 	    }
                   3081: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3082: 		my $name = lc($attr->{'name'});
                   3083: 		foreach my $item (keys(%javafiles)) {
                   3084: 		    if ($name eq $item) {
                   3085: 			$javafiles{$item} = $attr->{'value'};
                   3086: 			last;
                   3087: 		    }
                   3088: 		}
                   3089: 		foreach my $item (keys(%mediafiles)) {
                   3090: 		    if ($name eq $item) {
                   3091: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   3092: 			last;
                   3093: 		    }
                   3094: 		}
                   3095: 	    }
                   3096: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3097: 		foreach my $item (keys(%javafiles)) {
                   3098: 		    if ($attr->{$item}) {
                   3099: 			$javafiles{$item} = $attr->{$item};
                   3100: 			last;
                   3101: 		    }
                   3102: 		}
                   3103: 		foreach my $item (keys(%mediafiles)) {
                   3104: 		    if ($attr->{$item}) {
                   3105: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3106: 			last;
                   3107: 		    }
                   3108: 		}
                   3109: 	    }
                   3110: 	} elsif ($t->[0] eq 'E') {
                   3111: 	    my ($tagname) = ($t->[1]);
                   3112: 	    if ($javafiles{'codebase'} ne '') {
                   3113: 		$javafiles{'codebase'} .= '/';
                   3114: 	    }  
                   3115: 	    if (lc($tagname) eq 'applet' ||
                   3116: 		lc($tagname) eq 'object' ||
                   3117: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3118: 		) {
                   3119: 		foreach my $item (keys(%javafiles)) {
                   3120: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3121: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3122: 			&add_filetype($allfiles,$file,$item);
                   3123: 		    }
                   3124: 		}
                   3125: 	    } 
                   3126: 	    pop @state;
                   3127: 	}
                   3128:     }
1.637     raeburn  3129:     return 'ok';
                   3130: }
                   3131: 
1.639     albertel 3132: sub add_filetype {
                   3133:     my ($allfiles,$file,$type)=@_;
                   3134:     if (exists($allfiles->{$file})) {
                   3135: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3136: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3137: 	}
                   3138:     } else {
                   3139: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3140:     }
                   3141: }
                   3142: 
1.493     albertel 3143: sub removeuploadedurl {
1.984     neumanie 3144:     my ($url)=@_;	
                   3145:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3146:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3147: }
                   3148: 
                   3149: sub removeuserfile {
                   3150:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3151:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3152:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3153:     if ($result eq 'ok') {	
1.798     raeburn  3154:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3155:             my $metafile = $fname.'.meta';
                   3156:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3157: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3158:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3159:             my $sqlresult = 
1.823     albertel 3160:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3161:                                         'portfolio_metadata',$group,
                   3162:                                         'delete');
1.798     raeburn  3163:         }
                   3164:     }
                   3165:     return $result;
1.257     www      3166: }
1.15      www      3167: 
1.530     albertel 3168: sub mkdiruserfile {
                   3169:     my ($docuname,$docudom,$dir)=@_;
                   3170:     my $home=&homeserver($docuname,$docudom);
                   3171:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3172: }
                   3173: 
1.531     albertel 3174: sub renameuserfile {
                   3175:     my ($docuname,$docudom,$old,$new)=@_;
                   3176:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3177:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3178:                         &escape("$old").':'.&escape("$new"),$home);
                   3179:     if ($result eq 'ok') {
                   3180:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3181:             my $oldmeta = $old.'.meta';
                   3182:             my $newmeta = $new.'.meta';
                   3183:             my $metaresult = 
                   3184:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3185: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3186:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3187:             my $sqlresult = 
1.823     albertel 3188:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3189:                                         'portfolio_metadata',$group,
                   3190:                                         'delete');
1.798     raeburn  3191:         }
                   3192:     }
                   3193:     return $result;
1.531     albertel 3194: }
                   3195: 
1.14      www      3196: # ------------------------------------------------------------------------- Log
                   3197: 
                   3198: sub log {
                   3199:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3200:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3201: }
                   3202: 
                   3203: # ------------------------------------------------------------------ Course Log
1.352     www      3204: #
                   3205: # This routine flushes several buffers of non-mission-critical nature
                   3206: #
1.157     www      3207: 
                   3208: sub flushcourselogs {
1.352     www      3209:     &logthis('Flushing log buffers');
                   3210: #
                   3211: # course logs
                   3212: # This is a log of all transactions in a course, which can be used
                   3213: # for data mining purposes
                   3214: #
                   3215: # It also collects the courseid database, which lists last transaction
                   3216: # times and course titles for all courseids
                   3217: #
                   3218:     my %courseidbuffer=();
1.921     raeburn  3219:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3220:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3221: 		          &escape($courselogs{$crsid}),
                   3222: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3223: 	    delete $courselogs{$crsid};
                   3224:         } else {
                   3225:             &logthis('Failed to flush log buffer for '.$crsid);
                   3226:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3227:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3228:                         " exceeded maximum size, deleting.</font>");
                   3229:                delete $courselogs{$crsid};
                   3230:             }
1.352     www      3231:         }
1.920     raeburn  3232:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3233:             'description' => $coursedescrbuf{$crsid},
                   3234:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3235:             'type'        => $coursetypebuf{$crsid},
                   3236:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3237:         };
1.191     harris41 3238:     }
1.352     www      3239: #
                   3240: # Write course id database (reverse lookup) to homeserver of courses 
                   3241: # Is used in pickcourse
                   3242: #
1.840     albertel 3243:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3244:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3245:                                     $courseidbuffer{$crs_home},
                   3246:                                     $crs_home,'timeonly');
1.352     www      3247:     }
                   3248: #
                   3249: # File accesses
                   3250: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3251: #
1.449     matthew  3252:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3253:         if ($entry =~ /___count$/) {
                   3254:             my ($dom,$name);
1.807     albertel 3255:             ($dom,$name,undef)=
1.811     albertel 3256: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3257:             if (! defined($dom) || $dom eq '' || 
                   3258:                 ! defined($name) || $name eq '') {
1.620     albertel 3259:                 my $cid = $env{'request.course.id'};
                   3260:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3261:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3262:             }
1.450     matthew  3263:             my $value = $accesshash{$entry};
                   3264:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3265:             my %temphash=($url => $value);
1.449     matthew  3266:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3267:             if ($result eq 'ok') {
                   3268:                 delete $accesshash{$entry};
                   3269:             }
                   3270:         } else {
1.811     albertel 3271:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159  ! www      3272:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3273:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3274:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3275:                 delete $accesshash{$entry};
                   3276:             }
1.185     www      3277:         }
1.191     harris41 3278:     }
1.352     www      3279: #
                   3280: # Roles
                   3281: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3282: #
1.800     albertel 3283:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3284:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3285: 	    split(/\:/,$entry);
                   3286:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3287:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3288:                 $rudom,$runame) eq 'ok') {
                   3289: 	    delete $userrolehash{$entry};
                   3290:         }
                   3291:     }
1.662     raeburn  3292: #
                   3293: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3294: #
                   3295:     my %domrolebuffer = ();
1.1000    raeburn  3296:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3297:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3298:         if ($domrolebuffer{$rudom}) {
                   3299:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3300:                       '='.&escape($domainrolehash{$entry});
                   3301:         } else {
                   3302:             $domrolebuffer{$rudom}.=&escape($entry).
                   3303:                       '='.&escape($domainrolehash{$entry});
                   3304:         }
                   3305:         delete $domainrolehash{$entry};
                   3306:     }
                   3307:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3308: 	my %servers = &get_servers($dom,'library');
                   3309: 	foreach my $tryserver (keys(%servers)) {
                   3310: 	    unless (&reply('domroleput:'.$dom.':'.
                   3311: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3312: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3313: 	    }
1.662     raeburn  3314:         }
                   3315:     }
1.186     www      3316:     $dumpcount++;
1.157     www      3317: }
                   3318: 
                   3319: sub courselog {
                   3320:     my $what=shift;
1.158     www      3321:     $what=time.':'.$what;
1.620     albertel 3322:     unless ($env{'request.course.id'}) { return ''; }
                   3323:     $coursedombuf{$env{'request.course.id'}}=
                   3324:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3325:     $coursenumbuf{$env{'request.course.id'}}=
                   3326:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3327:     $coursehombuf{$env{'request.course.id'}}=
                   3328:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3329:     $coursedescrbuf{$env{'request.course.id'}}=
                   3330:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3331:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3332:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3333:     $courseownerbuf{$env{'request.course.id'}}=
                   3334:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3335:     $coursetypebuf{$env{'request.course.id'}}=
                   3336:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3337:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3338: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3339:     } else {
1.620     albertel 3340: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3341:     }
1.620     albertel 3342:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3343: 	&flushcourselogs();
                   3344:     }
1.158     www      3345: }
                   3346: 
                   3347: sub courseacclog {
                   3348:     my $fnsymb=shift;
1.620     albertel 3349:     unless ($env{'request.course.id'}) { return ''; }
                   3350:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3351:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3352:         $what.=':POST';
1.583     matthew  3353:         # FIXME: Probably ought to escape things....
1.800     albertel 3354: 	foreach my $key (keys(%env)) {
                   3355:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3356:                 my $formitem = $1;
                   3357:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3358:                     $what.=':'.$formitem.'='.$env{$key};
                   3359:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3360:                     $what.=':'.$formitem.'='.$env{$key};
                   3361:                 }
1.158     www      3362:             }
1.191     harris41 3363:         }
1.583     matthew  3364:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3365:         # FIXME: We should not be depending on a form parameter that someone
                   3366:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3367:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3368:             $what.= ':POST';
                   3369:             # FIXME: Probably ought to escape things....
                   3370:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3371:                                  'crsdiscuss') {
1.620     albertel 3372:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3373:             }
                   3374:         }
1.158     www      3375:     }
                   3376:     &courselog($what);
1.149     www      3377: }
                   3378: 
1.185     www      3379: sub countacc {
                   3380:     my $url=&declutter(shift);
1.458     matthew  3381:     return if (! defined($url) || $url eq '');
1.620     albertel 3382:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3383: #
                   3384: # Mark that this url was used in this course
                   3385: #
1.620     albertel 3386:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3387: #
                   3388: # Increase the access count for this resource in this child process
                   3389: #
1.281     www      3390:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3391:     $accesshash{$key}++;
1.185     www      3392: }
1.349     www      3393: 
1.361     www      3394: sub linklog {
                   3395:     my ($from,$to)=@_;
                   3396:     $from=&declutter($from);
                   3397:     $to=&declutter($to);
                   3398:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3399:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3400: }
                   3401:   
1.349     www      3402: sub userrolelog {
                   3403:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  3404:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  3405:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  3406:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  3407:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      3408:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3409:        $userrolehash
                   3410:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3411:                     =$tend.':'.$tstart;
1.662     raeburn  3412:     }
1.898     albertel 3413:     if (($env{'request.role'} =~ /dc\./) &&
                   3414: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   3415: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  3416: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   3417:          ($trole=~/^co/))) {
1.898     albertel 3418:        $userrolehash
                   3419:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3420:                     =$tend.':'.$tstart;
                   3421:     }
1.662     raeburn  3422:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   3423:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   3424:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   3425:         ($trole=~/^sc/)) {
                   3426:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3427:        $domainrolehash
                   3428:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3429:                     = $tend.':'.$tstart;
                   3430:     }
1.351     www      3431: }
                   3432: 
1.957     raeburn  3433: sub courserolelog {
                   3434:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   3435:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   3436:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   3437:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  3438:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   3439:         ($trole eq 'co')) {
1.957     raeburn  3440:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3441:             my $cdom = $1;
                   3442:             my $cnum = $2;
                   3443:             my $sec = $3;
                   3444:             my $namespace = 'rolelog';
                   3445:             my %storehash = (
                   3446:                                role    => $trole,
                   3447:                                start   => $tstart,
                   3448:                                end     => $tend,
                   3449:                                selfenroll => $selfenroll,
                   3450:                                context    => $context,
                   3451:                             );
                   3452:             if ($trole eq 'gr') {
                   3453:                 $namespace = 'groupslog';
                   3454:                 $storehash{'group'} = $sec;
                   3455:             } else {
                   3456:                 $storehash{'section'} = $sec;
                   3457:             }
                   3458:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  3459:             if (($trole ne 'st') || ($sec ne '')) {
                   3460:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   3461:             }
1.957     raeburn  3462:         }
                   3463:     }
                   3464:     return;
                   3465: }
                   3466: 
1.351     www      3467: sub get_course_adv_roles {
1.948     raeburn  3468:     my ($cid,$codes) = @_;
1.620     albertel 3469:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3470:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3471:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3472:     my %nothide=();
1.800     albertel 3473:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3474:         if ($user !~ /:/) {
                   3475: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3476:         } else {
                   3477:             $nothide{$user}=1;
                   3478:         }
1.470     www      3479:     }
1.351     www      3480:     my %returnhash=();
                   3481:     my %dumphash=
                   3482:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3483:     my $now=time;
1.997     raeburn  3484:     my %privileged;
1.1000    raeburn  3485:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3486: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3487:         if (($tstart) && ($tstart<0)) { next; }
                   3488:         if (($tend) && ($tend<$now)) { next; }
                   3489:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3490:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3491: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3492:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3493:             my %dompersonnel =
1.998     raeburn  3494:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3495:             $privileged{$domain} = {};
                   3496:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3497:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3498:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3499:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3500:                         $privileged{$udom}{$uname} = 1;
                   3501:                     }
                   3502:                 }
                   3503:             }
                   3504:         }
                   3505:         if ((exists($privileged{$domain}{$username})) && 
                   3506:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3507: 	if ($role eq 'cr') { next; }
1.948     raeburn  3508:         if ($codes) {
                   3509:             if ($section) { $role .= ':'.$section; }
                   3510:             if ($returnhash{$role}) {
                   3511:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3512:             } else {
                   3513:                 $returnhash{$role}=$username.':'.$domain;
                   3514:             }
1.351     www      3515:         } else {
1.988     raeburn  3516:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3517:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3518:             if ($returnhash{$key}) {
                   3519: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3520:             } else {
                   3521:                 $returnhash{$key}=$username.':'.$domain;
                   3522:             }
1.351     www      3523:         }
1.948     raeburn  3524:     }
1.400     www      3525:     return %returnhash;
                   3526: }
                   3527: 
                   3528: sub get_my_roles {
1.937     raeburn  3529:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3530:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3531:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3532:     my (%dumphash,%nothide);
1.1086    raeburn  3533:     if ($context eq 'userroles') {
                   3534:         my $extra = &freeze_escape({'skipcheck' => 1});
                   3535:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858     raeburn  3536:     } else {
                   3537:         %dumphash=
1.400     www      3538:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3539:         if ($hidepriv) {
                   3540:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3541:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3542:                 if ($user !~ /:/) {
                   3543:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3544:                 } else {
                   3545:                     $nothide{$user} = 1;
                   3546:                 }
                   3547:             }
                   3548:         }
1.858     raeburn  3549:     }
1.400     www      3550:     my %returnhash=();
                   3551:     my $now=time;
1.999     raeburn  3552:     my %privileged;
1.800     albertel 3553:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3554:         my ($role,$tend,$tstart);
                   3555:         if ($context eq 'userroles') {
1.1149    raeburn  3556:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  3557: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3558:         } else {
                   3559:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3560:         }
1.400     www      3561:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3562:         my $status = 'active';
1.939     raeburn  3563:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3564:             $status = 'previous';
                   3565:         } 
                   3566:         if (($tstart) && ($now<$tstart)) {
                   3567:             $status = 'future';
                   3568:         }
                   3569:         if (ref($types) eq 'ARRAY') {
                   3570:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3571:                 next;
                   3572:             } 
                   3573:         } else {
                   3574:             if ($status ne 'active') {
                   3575:                 next;
                   3576:             }
                   3577:         }
1.867     raeburn  3578:         my ($rolecode,$username,$domain,$section,$area);
                   3579:         if ($context eq 'userroles') {
                   3580:             ($area,$rolecode) = split(/_/,$entry);
                   3581:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3582:         } else {
                   3583:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3584:         }
1.832     raeburn  3585:         if (ref($roledoms) eq 'ARRAY') {
                   3586:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3587:                 next;
                   3588:             }
                   3589:         }
                   3590:         if (ref($roles) eq 'ARRAY') {
                   3591:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3592:                 if ($role =~ /^cr\//) {
                   3593:                     if (!grep(/^cr$/,@{$roles})) {
                   3594:                         next;
                   3595:                     }
1.1104    raeburn  3596:                 } elsif ($role =~ /^gr\//) {
                   3597:                     if (!grep(/^gr$/,@{$roles})) {
                   3598:                         next;
                   3599:                     }
1.922     raeburn  3600:                 } else {
                   3601:                     next;
                   3602:                 }
1.832     raeburn  3603:             }
1.867     raeburn  3604:         }
1.937     raeburn  3605:         if ($hidepriv) {
1.999     raeburn  3606:             if ($context eq 'userroles') {
                   3607:                 if ((&privileged($username,$domain)) &&
                   3608:                     (!$nothide{$username.':'.$domain})) {
                   3609:                     next;
                   3610:                 }
                   3611:             } else {
                   3612:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3613:                     my %dompersonnel =
                   3614:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3615:                     $privileged{$domain} = {};
                   3616:                     if (keys(%dompersonnel)) {
                   3617:                         foreach my $server (keys(%dompersonnel)) {
                   3618:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3619:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3620:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3621:                                     $privileged{$udom}{$uname} = $trole;
                   3622:                                 }
                   3623:                             }
                   3624:                         }
                   3625:                     }
                   3626:                 }
                   3627:                 if (exists($privileged{$domain}{$username})) {
                   3628:                     if (!$nothide{$username.':'.$domain}) {
                   3629:                         next;
                   3630:                     }
                   3631:                 }
1.937     raeburn  3632:             }
                   3633:         }
1.933     raeburn  3634:         if ($withsec) {
                   3635:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3636:                 $tstart.':'.$tend;
                   3637:         } else {
                   3638:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3639:         }
1.832     raeburn  3640:     }
1.373     www      3641:     return %returnhash;
1.399     www      3642: }
                   3643: 
                   3644: # ----------------------------------------------------- Frontpage Announcements
                   3645: #
                   3646: #
                   3647: 
                   3648: sub postannounce {
                   3649:     my ($server,$text)=@_;
1.844     albertel 3650:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3651:     unless ($text=~/\w/) { $text=''; }
                   3652:     return &reply('setannounce:'.&escape($text),$server);
                   3653: }
                   3654: 
                   3655: sub getannounce {
1.448     albertel 3656: 
                   3657:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3658: 	my $announcement='';
1.800     albertel 3659: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3660: 	close($fh);
1.399     www      3661: 	if ($announcement=~/\w/) { 
                   3662: 	    return 
                   3663:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3664:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3665: 	} else {
                   3666: 	    return '';
                   3667: 	}
                   3668:     } else {
                   3669: 	return '';
                   3670:     }
1.351     www      3671: }
1.353     www      3672: 
                   3673: # ---------------------------------------------------------- Course ID routines
                   3674: # Deal with domain's nohist_courseid.db files
                   3675: #
                   3676: 
                   3677: sub courseidput {
1.921     raeburn  3678:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3679:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3680:     my $outcome;
                   3681:     if ($caller eq 'timeonly') {
                   3682:         my $cids = '';
                   3683:         foreach my $item (keys(%$storehash)) {
                   3684:             $cids.=&escape($item).'&';
                   3685:         }
                   3686:         $cids=~s/\&$//;
                   3687:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3688:                           $coursehome);       
                   3689:     } else {
                   3690:         my $items = '';
                   3691:         foreach my $item (keys(%$storehash)) {
                   3692:             $items.= &escape($item).'='.
                   3693:                      &freeze_escape($$storehash{$item}).'&';
                   3694:         }
                   3695:         $items=~s/\&$//;
                   3696:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3697:                           $coursehome);
1.918     raeburn  3698:     }
                   3699:     if ($outcome eq 'unknown_cmd') {
                   3700:         my $what;
                   3701:         foreach my $cid (keys(%$storehash)) {
                   3702:             $what .= &escape($cid).'=';
1.921     raeburn  3703:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3704:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3705:             }
                   3706:             $what =~ s/\:$/&/;
                   3707:         }
                   3708:         $what =~ s/\&$//;  
                   3709:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3710:     } else {
                   3711:         return $outcome;
                   3712:     }
1.353     www      3713: }
                   3714: 
                   3715: sub courseiddump {
1.921     raeburn  3716:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3717:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3718:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  3719:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3720:     my $as_hash = 1;
                   3721:     my %returnhash;
                   3722:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3723:     my %libserv = &all_library();
                   3724:     foreach my $tryserver (keys(%libserv)) {
                   3725:         if ( (  $hostidflag == 1 
                   3726: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3727: 	     || (!defined($hostidflag)) ) {
                   3728: 
1.918     raeburn  3729: 	    if (($domfilter eq '') ||
                   3730: 		(&host_domain($tryserver) eq $domfilter)) {
                   3731:                 my $rep = 
                   3732:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3733:                          $sincefilter.':'.&escape($descfilter).':'.
                   3734:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3735:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3736:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3737:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3738:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3739:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3740:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071    raeburn  3741:                          &escape($creationcontext).':'.$domcloner,
                   3742:                          $tryserver);
1.918     raeburn  3743:                 my @pairs=split(/\&/,$rep);
                   3744:                 foreach my $item (@pairs) {
                   3745:                     my ($key,$value)=split(/\=/,$item,2);
                   3746:                     $key = &unescape($key);
                   3747:                     next if ($key =~ /^error: 2 /);
                   3748:                     my $result = &thaw_unescape($value);
                   3749:                     if (ref($result) eq 'HASH') {
                   3750:                         $returnhash{$key}=$result;
                   3751:                     } else {
1.921     raeburn  3752:                         my @responses = split(/:/,$value);
                   3753:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3754:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3755:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3756:                         }
1.1008    raeburn  3757:                     }
1.353     www      3758:                 }
                   3759:             }
                   3760:         }
                   3761:     }
                   3762:     return %returnhash;
                   3763: }
                   3764: 
1.1055    raeburn  3765: sub courselastaccess {
                   3766:     my ($cdom,$cnum,$hostidref) = @_;
                   3767:     my %returnhash;
                   3768:     if ($cdom && $cnum) {
                   3769:         my $chome = &homeserver($cnum,$cdom);
                   3770:         if ($chome ne 'no_host') {
                   3771:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3772:             &extract_lastaccess(\%returnhash,$rep);
                   3773:         }
                   3774:     } else {
                   3775:         if (!$cdom) { $cdom=''; }
                   3776:         my %libserv = &all_library();
                   3777:         foreach my $tryserver (keys(%libserv)) {
                   3778:             if (ref($hostidref) eq 'ARRAY') {
                   3779:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3780:             } 
                   3781:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3782:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3783:                 &extract_lastaccess(\%returnhash,$rep);
                   3784:             }
                   3785:         }
                   3786:     }
                   3787:     return %returnhash;
                   3788: }
                   3789: 
                   3790: sub extract_lastaccess {
                   3791:     my ($returnhash,$rep) = @_;
                   3792:     if (ref($returnhash) eq 'HASH') {
                   3793:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3794:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3795:                  $rep eq '') {
                   3796:             my @pairs=split(/\&/,$rep);
                   3797:             foreach my $item (@pairs) {
                   3798:                 my ($key,$value)=split(/\=/,$item,2);
                   3799:                 $key = &unescape($key);
                   3800:                 next if ($key =~ /^error: 2 /);
                   3801:                 $returnhash->{$key} = &thaw_unescape($value);
                   3802:             }
                   3803:         }
                   3804:     }
                   3805:     return;
                   3806: }
                   3807: 
1.658     raeburn  3808: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3809: 
                   3810: sub dcmailput {
1.685     raeburn  3811:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3812:     my $status = &Apache::lonnet::critical(
1.740     www      3813:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3814:        &escape($message),$server);
1.662     raeburn  3815:     return $status;
                   3816: }
                   3817: 
1.658     raeburn  3818: sub dcmaildump {
                   3819:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3820:     my %returnhash=();
1.846     albertel 3821: 
                   3822:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3823:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3824:                                                          &escape($enddate).':';
                   3825: 	my @esc_senders=map { &escape($_)} @$senders;
                   3826: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3827: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3828:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3829:             if (($key) && ($value)) {
                   3830:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3831:             }
                   3832:         }
                   3833:     }
                   3834:     return %returnhash;
                   3835: }
1.662     raeburn  3836: # ---------------------------------------------------------- Domain roles
                   3837: 
                   3838: sub get_domain_roles {
                   3839:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3840:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3841:         $startdate = '.';
                   3842:     }
1.1018    raeburn  3843:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3844:         $enddate = '.';
                   3845:     }
1.922     raeburn  3846:     my $rolelist;
                   3847:     if (ref($roles) eq 'ARRAY') {
                   3848:         $rolelist = join(':',@{$roles});
                   3849:     }
1.662     raeburn  3850:     my %personnel = ();
1.841     albertel 3851: 
                   3852:     my %servers = &get_servers($dom,'library');
                   3853:     foreach my $tryserver (keys(%servers)) {
                   3854: 	%{$personnel{$tryserver}}=();
                   3855: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3856: 					    &escape($startdate).':'.
                   3857: 					    &escape($enddate).':'.
                   3858: 					    &escape($rolelist), $tryserver))) {
                   3859: 	    my ($key,$value) = split(/\=/,$line,2);
                   3860: 	    if (($key) && ($value)) {
                   3861: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3862: 	    }
                   3863: 	}
1.662     raeburn  3864:     }
                   3865:     return %personnel;
                   3866: }
1.658     raeburn  3867: 
1.1057    www      3868: # ----------------------------------------------------------- Interval timing 
1.149     www      3869: 
1.1153    www      3870: {
                   3871: # Caches needed for speedup of navmaps
                   3872: # We don't want to cache this for very long at all (5 seconds at most)
                   3873: # 
                   3874: # The user for whom we cache
                   3875: my $cachedkey='';
                   3876: # The cached times for this user
                   3877: my %cachedtimes=();
                   3878: # When this was last done
                   3879: my $cachedtime=();
                   3880: 
                   3881: sub load_all_first_access {
1.1154    raeburn  3882:     my ($uname,$udom)=@_;
1.1156    www      3883:     if (($cachedkey eq $uname.':'.$udom) &&
1.1154    raeburn  3884:         (abs($cachedtime-time)<5)) {
                   3885:         return;
                   3886:     }
                   3887:     $cachedtime=time;
                   3888:     $cachedkey=$uname.':'.$udom;
                   3889:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      3890: }
                   3891: 
1.504     albertel 3892: sub get_first_access {
                   3893:     my ($type,$argsymb)=@_;
1.790     albertel 3894:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3895:     if ($argsymb) { $symb=$argsymb; }
                   3896:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3897:     if ($type eq 'course') {
                   3898: 	$res='course';
                   3899:     } elsif ($type eq 'map') {
1.588     albertel 3900: 	$res=&symbread($map);
                   3901:     } else {
                   3902: 	$res=$symb;
                   3903:     }
1.1153    www      3904:     &load_all_first_access($uname,$udom);
                   3905:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 3906: }
                   3907: 
                   3908: sub set_first_access {
                   3909:     my ($type)=@_;
1.790     albertel 3910:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3911:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3912:     if ($type eq 'course') {
                   3913: 	$res='course';
                   3914:     } elsif ($type eq 'map') {
1.588     albertel 3915: 	$res=&symbread($map);
                   3916:     } else {
                   3917: 	$res=$symb;
                   3918:     }
1.1153    www      3919:     $cachedkey='';
1.588     albertel 3920:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3921:     if (!$firstaccess) {
1.588     albertel 3922: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3923:     }
                   3924:     return 'already_set';
1.504     albertel 3925: }
1.1153    www      3926: }
1.110     www      3927: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3928: 
                   3929: sub expirespread {
                   3930:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3931:     my $cid=$env{'request.course.id'}; 
1.110     www      3932:     if ($cid) {
                   3933:        my $now=time;
                   3934:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3935:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3936:                             $env{'course.'.$cid.'.num'}.
1.110     www      3937: 	        	    ':nohist_expirationdates:'.
                   3938:                             &escape($key).'='.$now,
1.620     albertel 3939:                             $env{'course.'.$cid.'.home'})
1.110     www      3940:     }
                   3941:     return 'ok';
1.14      www      3942: }
                   3943: 
1.109     www      3944: # ----------------------------------------------------- Devalidate Spreadsheets
                   3945: 
                   3946: sub devalidate {
1.325     www      3947:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3948:     my $cid=$env{'request.course.id'}; 
1.109     www      3949:     if ($cid) {
1.391     matthew  3950:         # delete the stored spreadsheets for
                   3951:         # - the student level sheet of this user in course's homespace
                   3952:         # - the assessment level sheet for this resource 
                   3953:         #   for this user in user's homespace
1.553     albertel 3954: 	# - current conditional state info
1.325     www      3955: 	my $key=$uname.':'.$udom.':';
1.109     www      3956:         my $status=
1.299     matthew  3957: 	    &del('nohist_calculatedsheets',
1.391     matthew  3958: 		 [$key.'studentcalc:'],
1.620     albertel 3959: 		 $env{'course.'.$cid.'.domain'},
                   3960: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3961: 		.' '.
                   3962: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3963: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3964:         unless ($status eq 'ok ok') {
                   3965:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3966:                     $uname.' at '.$udom.' for '.
1.109     www      3967: 		    $symb.': '.$status);
1.133     albertel 3968:         }
1.553     albertel 3969: 	&delenv('user.state.'.$cid);
1.109     www      3970:     }
                   3971: }
                   3972: 
1.265     albertel 3973: sub get_scalar {
                   3974:     my ($string,$end) = @_;
                   3975:     my $value;
                   3976:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3977: 	$value = $1;
                   3978:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3979: 	$value = $1;
                   3980:     }
                   3981:     return &unescape($value);
                   3982: }
                   3983: 
                   3984: sub array2str {
                   3985:   my (@array) = @_;
                   3986:   my $result=&arrayref2str(\@array);
                   3987:   $result=~s/^__ARRAY_REF__//;
                   3988:   $result=~s/__END_ARRAY_REF__$//;
                   3989:   return $result;
                   3990: }
                   3991: 
1.204     albertel 3992: sub arrayref2str {
                   3993:   my ($arrayref) = @_;
1.265     albertel 3994:   my $result='__ARRAY_REF__';
1.204     albertel 3995:   foreach my $elem (@$arrayref) {
1.265     albertel 3996:     if(ref($elem) eq 'ARRAY') {
                   3997:       $result.=&arrayref2str($elem).'&';
                   3998:     } elsif(ref($elem) eq 'HASH') {
                   3999:       $result.=&hashref2str($elem).'&';
                   4000:     } elsif(ref($elem)) {
                   4001:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4002:     } else {
                   4003:       $result.=&escape($elem).'&';
                   4004:     }
                   4005:   }
                   4006:   $result=~s/\&$//;
1.265     albertel 4007:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4008:   return $result;
                   4009: }
                   4010: 
1.168     albertel 4011: sub hash2str {
1.204     albertel 4012:   my (%hash) = @_;
                   4013:   my $result=&hashref2str(\%hash);
1.265     albertel 4014:   $result=~s/^__HASH_REF__//;
                   4015:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4016:   return $result;
                   4017: }
                   4018: 
                   4019: sub hashref2str {
                   4020:   my ($hashref)=@_;
1.265     albertel 4021:   my $result='__HASH_REF__';
1.800     albertel 4022:   foreach my $key (sort(keys(%$hashref))) {
                   4023:     if (ref($key) eq 'ARRAY') {
                   4024:       $result.=&arrayref2str($key).'=';
                   4025:     } elsif (ref($key) eq 'HASH') {
                   4026:       $result.=&hashref2str($key).'=';
                   4027:     } elsif (ref($key)) {
1.265     albertel 4028:       $result.='=';
1.800     albertel 4029:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4030:     } else {
1.1132    raeburn  4031: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4032:     }
                   4033: 
1.800     albertel 4034:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4035:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4036:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4037:       $result.=&hashref2str($hashref->{$key}).'&';
                   4038:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4039:        $result.='&';
1.800     albertel 4040:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4041:     } else {
1.800     albertel 4042:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4043:     }
                   4044:   }
1.168     albertel 4045:   $result=~s/\&$//;
1.265     albertel 4046:   $result .= '__END_HASH_REF__';
1.168     albertel 4047:   return $result;
                   4048: }
                   4049: 
                   4050: sub str2hash {
1.265     albertel 4051:     my ($string)=@_;
                   4052:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4053:     return %$hash;
                   4054: }
                   4055: 
                   4056: sub str2hashref {
1.168     albertel 4057:   my ($string) = @_;
1.265     albertel 4058: 
                   4059:   my %hash;
                   4060: 
                   4061:   if($string !~ /^__HASH_REF__/) {
                   4062:       if (! ($string eq '' || !defined($string))) {
                   4063: 	  $hash{'error'}='Not hash reference';
                   4064:       }
                   4065:       return (\%hash, $string);
                   4066:   }
                   4067: 
                   4068:   $string =~ s/^__HASH_REF__//;
                   4069: 
                   4070:   while($string !~ /^__END_HASH_REF__/) {
                   4071:       #key
                   4072:       my $key='';
                   4073:       if($string =~ /^__HASH_REF__/) {
                   4074:           ($key, $string)=&str2hashref($string);
                   4075:           if(defined($key->{'error'})) {
                   4076:               $hash{'error'}='Bad data';
                   4077:               return (\%hash, $string);
                   4078:           }
                   4079:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4080:           ($key, $string)=&str2arrayref($string);
                   4081:           if($key->[0] eq 'Array reference error') {
                   4082:               $hash{'error'}='Bad data';
                   4083:               return (\%hash, $string);
                   4084:           }
                   4085:       } else {
                   4086:           $string =~ s/^(.*?)=//;
1.267     albertel 4087: 	  $key=&unescape($1);
1.265     albertel 4088:       }
                   4089:       $string =~ s/^=//;
                   4090: 
                   4091:       #value
                   4092:       my $value='';
                   4093:       if($string =~ /^__HASH_REF__/) {
                   4094:           ($value, $string)=&str2hashref($string);
                   4095:           if(defined($value->{'error'})) {
                   4096:               $hash{'error'}='Bad data';
                   4097:               return (\%hash, $string);
                   4098:           }
                   4099:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4100:           ($value, $string)=&str2arrayref($string);
                   4101:           if($value->[0] eq 'Array reference error') {
                   4102:               $hash{'error'}='Bad data';
                   4103:               return (\%hash, $string);
                   4104:           }
                   4105:       } else {
                   4106: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4107:       }
                   4108:       $string =~ s/^&//;
                   4109: 
                   4110:       $hash{$key}=$value;
1.204     albertel 4111:   }
1.265     albertel 4112: 
                   4113:   $string =~ s/^__END_HASH_REF__//;
                   4114: 
                   4115:   return (\%hash, $string);
1.204     albertel 4116: }
                   4117: 
                   4118: sub str2array {
1.265     albertel 4119:     my ($string)=@_;
                   4120:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4121:     return @$array;
                   4122: }
                   4123: 
                   4124: sub str2arrayref {
1.204     albertel 4125:   my ($string) = @_;
1.265     albertel 4126:   my @array;
                   4127: 
                   4128:   if($string !~ /^__ARRAY_REF__/) {
                   4129:       if (! ($string eq '' || !defined($string))) {
                   4130: 	  $array[0]='Array reference error';
                   4131:       }
                   4132:       return (\@array, $string);
                   4133:   }
                   4134: 
                   4135:   $string =~ s/^__ARRAY_REF__//;
                   4136: 
                   4137:   while($string !~ /^__END_ARRAY_REF__/) {
                   4138:       my $value='';
                   4139:       if($string =~ /^__HASH_REF__/) {
                   4140:           ($value, $string)=&str2hashref($string);
                   4141:           if(defined($value->{'error'})) {
                   4142:               $array[0] ='Array reference error';
                   4143:               return (\@array, $string);
                   4144:           }
                   4145:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4146:           ($value, $string)=&str2arrayref($string);
                   4147:           if($value->[0] eq 'Array reference error') {
                   4148:               $array[0] ='Array reference error';
                   4149:               return (\@array, $string);
                   4150:           }
                   4151:       } else {
                   4152: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4153:       }
                   4154:       $string =~ s/^&//;
                   4155: 
                   4156:       push(@array, $value);
1.191     harris41 4157:   }
1.265     albertel 4158: 
                   4159:   $string =~ s/^__END_ARRAY_REF__//;
                   4160: 
                   4161:   return (\@array, $string);
1.168     albertel 4162: }
                   4163: 
1.167     albertel 4164: # -------------------------------------------------------------------Temp Store
                   4165: 
1.168     albertel 4166: sub tmpreset {
                   4167:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4168:   if (!$symb) {
                   4169:     $symb=&symbread();
1.620     albertel 4170:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4171:   }
                   4172:   $symb=escape($symb);
                   4173: 
1.620     albertel 4174:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4175:   $namespace=~s/\//\_/g;
                   4176:   $namespace=~s/\W//g;
                   4177: 
1.620     albertel 4178:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4179:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4180:   if ($domain eq 'public' && $stuname eq 'public') {
                   4181:       $stuname=$ENV{'REMOTE_ADDR'};
                   4182:   }
1.1117    foxr     4183:   my $path=LONCAPA::tempdir();
1.168     albertel 4184:   my %hash;
                   4185:   if (tie(%hash,'GDBM_File',
                   4186: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4187: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4188:     foreach my $key (keys(%hash)) {
1.180     albertel 4189:       if ($key=~ /:$symb/) {
1.168     albertel 4190: 	delete($hash{$key});
                   4191:       }
                   4192:     }
                   4193:   }
                   4194: }
                   4195: 
1.167     albertel 4196: sub tmpstore {
1.168     albertel 4197:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4198: 
                   4199:   if (!$symb) {
                   4200:     $symb=&symbread();
1.620     albertel 4201:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4202:   }
                   4203:   $symb=escape($symb);
                   4204: 
                   4205:   if (!$namespace) {
                   4206:     # I don't think we would ever want to store this for a course.
                   4207:     # it seems this will only be used if we don't have a course.
1.620     albertel 4208:     #$namespace=$env{'request.course.id'};
1.168     albertel 4209:     #if (!$namespace) {
1.620     albertel 4210:       $namespace=$env{'request.state'};
1.168     albertel 4211:     #}
                   4212:   }
                   4213:   $namespace=~s/\//\_/g;
                   4214:   $namespace=~s/\W//g;
1.620     albertel 4215:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4216:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4217:   if ($domain eq 'public' && $stuname eq 'public') {
                   4218:       $stuname=$ENV{'REMOTE_ADDR'};
                   4219:   }
1.168     albertel 4220:   my $now=time;
                   4221:   my %hash;
1.1117    foxr     4222:   my $path=LONCAPA::tempdir();
1.168     albertel 4223:   if (tie(%hash,'GDBM_File',
                   4224: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4225: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4226:     $hash{"version:$symb"}++;
                   4227:     my $version=$hash{"version:$symb"};
                   4228:     my $allkeys=''; 
                   4229:     foreach my $key (keys(%$storehash)) {
                   4230:       $allkeys.=$key.':';
1.591     albertel 4231:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4232:     }
                   4233:     $hash{"$version:$symb:timestamp"}=$now;
                   4234:     $allkeys.='timestamp';
                   4235:     $hash{"$version:keys:$symb"}=$allkeys;
                   4236:     if (untie(%hash)) {
                   4237:       return 'ok';
                   4238:     } else {
                   4239:       return "error:$!";
                   4240:     }
                   4241:   } else {
                   4242:     return "error:$!";
                   4243:   }
                   4244: }
1.167     albertel 4245: 
1.168     albertel 4246: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4247: 
1.168     albertel 4248: sub tmprestore {
                   4249:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4250: 
1.168     albertel 4251:   if (!$symb) {
                   4252:     $symb=&symbread();
1.620     albertel 4253:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4254:   }
                   4255:   $symb=escape($symb);
                   4256: 
1.620     albertel 4257:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4258: 
1.620     albertel 4259:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4260:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4261:   if ($domain eq 'public' && $stuname eq 'public') {
                   4262:       $stuname=$ENV{'REMOTE_ADDR'};
                   4263:   }
1.168     albertel 4264:   my %returnhash;
                   4265:   $namespace=~s/\//\_/g;
                   4266:   $namespace=~s/\W//g;
                   4267:   my %hash;
1.1117    foxr     4268:   my $path=LONCAPA::tempdir();
1.168     albertel 4269:   if (tie(%hash,'GDBM_File',
                   4270: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4271: 	  &GDBM_READER(),0640)) {
1.168     albertel 4272:     my $version=$hash{"version:$symb"};
                   4273:     $returnhash{'version'}=$version;
                   4274:     my $scope;
                   4275:     for ($scope=1;$scope<=$version;$scope++) {
                   4276:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4277:       my @keys=split(/:/,$vkeys);
                   4278:       my $key;
                   4279:       $returnhash{"$scope:keys"}=$vkeys;
                   4280:       foreach $key (@keys) {
1.591     albertel 4281: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4282: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4283:       }
                   4284:     }
1.168     albertel 4285:     if (!(untie(%hash))) {
                   4286:       return "error:$!";
                   4287:     }
                   4288:   } else {
                   4289:     return "error:$!";
                   4290:   }
                   4291:   return %returnhash;
1.167     albertel 4292: }
                   4293: 
1.9       www      4294: # ----------------------------------------------------------------------- Store
                   4295: 
                   4296: sub store {
1.124     www      4297:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4298:     my $home='';
                   4299: 
1.168     albertel 4300:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4301: 
1.213     www      4302:     $symb=&symbclean($symb);
1.122     albertel 4303:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4304: 
1.620     albertel 4305:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4306:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4307: 
                   4308:     &devalidate($symb,$stuname,$domain);
1.109     www      4309: 
                   4310:     $symb=escape($symb);
1.187     www      4311:     if (!$namespace) { 
1.620     albertel 4312:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4313:           return ''; 
                   4314:        } 
                   4315:     }
1.620     albertel 4316:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4317: 
                   4318:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4319:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4320: 
1.12      www      4321:     my $namevalue='';
1.800     albertel 4322:     foreach my $key (keys(%$storehash)) {
                   4323:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4324:     }
1.12      www      4325:     $namevalue=~s/\&$//;
1.187     www      4326:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4327:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4328: }
                   4329: 
1.47      www      4330: # -------------------------------------------------------------- Critical Store
                   4331: 
                   4332: sub cstore {
1.124     www      4333:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4334:     my $home='';
                   4335: 
1.168     albertel 4336:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4337: 
1.213     www      4338:     $symb=&symbclean($symb);
1.122     albertel 4339:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4340: 
1.620     albertel 4341:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4342:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4343: 
                   4344:     &devalidate($symb,$stuname,$domain);
1.109     www      4345: 
                   4346:     $symb=escape($symb);
1.187     www      4347:     if (!$namespace) { 
1.620     albertel 4348:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4349:           return ''; 
                   4350:        } 
                   4351:     }
1.620     albertel 4352:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4353: 
                   4354:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4355:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4356: 
1.47      www      4357:     my $namevalue='';
1.800     albertel 4358:     foreach my $key (keys(%$storehash)) {
                   4359:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4360:     }
1.47      www      4361:     $namevalue=~s/\&$//;
1.187     www      4362:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4363:     return critical
                   4364:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4365: }
                   4366: 
1.9       www      4367: # --------------------------------------------------------------------- Restore
                   4368: 
                   4369: sub restore {
1.124     www      4370:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4371:     my $home='';
                   4372: 
1.168     albertel 4373:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4374: 
1.122     albertel 4375:     if (!$symb) {
                   4376:       unless ($symb=escape(&symbread())) { return ''; }
                   4377:     } else {
1.213     www      4378:       $symb=&escape(&symbclean($symb));
1.122     albertel 4379:     }
1.188     www      4380:     if (!$namespace) { 
1.620     albertel 4381:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4382:           return ''; 
                   4383:        } 
                   4384:     }
1.620     albertel 4385:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4386:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4387:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4388:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4389: 
1.12      www      4390:     my %returnhash=();
1.800     albertel 4391:     foreach my $line (split(/\&/,$answer)) {
                   4392: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4393:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4394:     }
1.75      www      4395:     my $version;
                   4396:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4397:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4398:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4399:        }
1.75      www      4400:     }
1.13      www      4401:     return %returnhash;
1.34      www      4402: }
                   4403: 
                   4404: # ---------------------------------------------------------- Course Description
1.1118    foxr     4405: #
                   4406: #  
1.34      www      4407: 
                   4408: sub coursedescription {
1.731     albertel 4409:     my ($courseid,$args)=@_;
1.34      www      4410:     $courseid=~s/^\///;
1.49      www      4411:     $courseid=~s/\_/\//g;
1.34      www      4412:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4413:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4414:     my $normalid=$cdomain.'_'.$cnum;
                   4415:     # need to always cache even if we get errors otherwise we keep 
                   4416:     # trying and trying and trying to get the course description.
                   4417:     my %envhash=();
                   4418:     my %returnhash=();
1.731     albertel 4419:     
                   4420:     my $expiretime=600;
                   4421:     if ($env{'request.course.id'} eq $normalid) {
                   4422: 	$expiretime=120;
                   4423:     }
                   4424: 
                   4425:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4426:     if (!$args->{'freshen_cache'}
                   4427: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4428: 	foreach my $key (keys(%env)) {
                   4429: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4430: 	    my ($setting) = $1;
                   4431: 	    $returnhash{$setting} = $env{$key};
                   4432: 	}
                   4433: 	return %returnhash;
                   4434:     }
                   4435: 
1.1118    foxr     4436:     # get the data again
                   4437: 
1.731     albertel 4438:     if (!$args->{'one_time'}) {
                   4439: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4440:     }
1.811     albertel 4441: 
1.34      www      4442:     if ($chome ne 'no_host') {
1.302     albertel 4443:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4444:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4445: 	   my $username = $env{'user.name'}; # Defult username
                   4446: 	   if(defined $args->{'user'}) {
                   4447: 	       $username = $args->{'user'};
                   4448: 	   }
1.129     albertel 4449:            $returnhash{'home'}= $chome;
                   4450: 	   $returnhash{'domain'} = $cdomain;
                   4451: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4452:            if (!defined($returnhash{'type'})) {
                   4453:                $returnhash{'type'} = 'Course';
                   4454:            }
1.130     albertel 4455:            while (my ($name,$value) = each %returnhash) {
1.53      www      4456:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4457:            }
1.270     www      4458:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4459:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4460: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4461:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4462:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4463:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4464:        }
                   4465:     }
1.731     albertel 4466:     if (!$args->{'one_time'}) {
1.949     raeburn  4467: 	&appenv(\%envhash);
1.731     albertel 4468:     }
1.302     albertel 4469:     return %returnhash;
1.461     www      4470: }
                   4471: 
1.1080    raeburn  4472: sub update_released_required {
                   4473:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4474:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4475:         $cid = $env{'request.course.id'};
                   4476:         $cdom = $env{'course.'.$cid.'.domain'};
                   4477:         $cnum = $env{'course.'.$cid.'.num'};
                   4478:         $chome = $env{'course.'.$cid.'.home'};
                   4479:     }
                   4480:     if ($needsrelease) {
                   4481:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4482:         my $needsupdate;
                   4483:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4484:             $needsupdate = 1;
                   4485:         } else {
                   4486:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4487:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4488:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4489:                 $needsupdate = 1;
                   4490:             }
                   4491:         }
                   4492:         if ($needsupdate) {
                   4493:             my %needshash = (
                   4494:                              'internal.releaserequired' => $needsrelease,
                   4495:                             );
                   4496:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4497:             if ($putresult eq 'ok') {
                   4498:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4499:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4500:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4501:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4502:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4503:                 }
                   4504:             }
                   4505:         }
                   4506:     }
                   4507:     return;
                   4508: }
                   4509: 
1.461     www      4510: # -------------------------------------------------See if a user is privileged
                   4511: 
                   4512: sub privileged {
                   4513:     my ($username,$domain)=@_;
                   4514:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   4515: 			&homeserver($username,$domain));
1.1033    raeburn  4516:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   4517:         ($rolesdump =~ /^error:/)) {
                   4518:         return 0;
                   4519:     }
1.461     www      4520:     my $now=time;
                   4521:     if ($rolesdump ne '') {
1.800     albertel 4522:         foreach my $entry (split(/&/,$rolesdump)) {
                   4523: 	    if ($entry!~/^rolesdef_/) {
                   4524: 		my ($area,$role)=split(/=/,$entry);
1.461     www      4525: 		$area=~s/\_\w\w$//;
                   4526: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   4527: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   4528: 		    my $active=1;
                   4529: 		    if ($tend) {
                   4530: 			if ($tend<$now) { $active=0; }
                   4531: 		    }
                   4532: 		    if ($tstart) {
                   4533: 			if ($tstart>$now) { $active=0; }
                   4534: 		    }
                   4535: 		    if ($active) { return 1; }
                   4536: 		}
                   4537: 	    }
                   4538: 	}
                   4539:     }
                   4540:     return 0;
1.9       www      4541: }
1.1       albertel 4542: 
1.103     harris41 4543: # -------------------------------------------------------- Get user privileges
1.11      www      4544: 
                   4545: sub rolesinit {
                   4546:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  4547:     my $now=time;
                   4548:     my %userroles = ('user.login.time' => $now);
1.1086    raeburn  4549:     my $extra = &freeze_escape({'skipcheck' => 1});
1.1078    raeburn  4550:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033    raeburn  4551:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
1.1078    raeburn  4552:         ($rolesdump =~ /^error:/)) {
1.1033    raeburn  4553:         return \%userroles;
                   4554:     }
1.11      www      4555:     my %allroles=();
1.678     raeburn  4556:     my %allgroups=();   
1.11      www      4557: 
                   4558:     if ($rolesdump ne '') {
1.800     albertel 4559:         foreach my $entry (split(/&/,$rolesdump)) {
                   4560: 	  if ($entry!~/^rolesdef_/) {
                   4561:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 4562: 	    $area=~s/\_\w\w$//;
1.678     raeburn  4563:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 4564: 	    if ($role=~/^cr/) { 
1.807     albertel 4565: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4566: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 4567: 		    ($tend,$tstart)=split('_',$trest);
                   4568: 		} else {
                   4569: 		    $trole=$role;
                   4570: 		}
1.678     raeburn  4571:             } elsif ($role =~ m|^gr/|) {
                   4572:                 ($trole,$tend,$tstart) = split(/_/,$role);
1.1104    raeburn  4573:                 next if ($tstart eq '-1');
1.678     raeburn  4574:                 ($trole,$group_privs) = split(/\//,$trole);
                   4575:                 $group_privs = &unescape($group_privs);
1.587     albertel 4576: 	    } else {
                   4577: 		($trole,$tend,$tstart)=split(/_/,$role);
                   4578: 	    }
1.743     albertel 4579: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4580: 					 $username);
                   4581: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  4582:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   4583:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      4584:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 4585: 		my $spec=$trole.'.'.$area;
                   4586: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   4587: 		if ($trole =~ /^cr\//) {
1.567     raeburn  4588:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  4589:                 } elsif ($trole eq 'gr') {
                   4590:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 4591: 		} else {
1.567     raeburn  4592:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 4593: 		}
1.12      www      4594:             }
1.662     raeburn  4595:           }
1.191     harris41 4596:         }
1.743     albertel 4597:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4598:         $userroles{'user.adv'}    = $adv;
                   4599: 	$userroles{'user.author'} = $author;
1.620     albertel 4600:         $env{'user.adv'}=$adv;
1.11      www      4601:     }
1.743     albertel 4602:     return \%userroles;  
1.11      www      4603: }
                   4604: 
1.567     raeburn  4605: sub set_arearole {
                   4606:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4607: # log the associated role with the area
                   4608:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4609:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4610: }
                   4611: 
                   4612: sub custom_roleprivs {
                   4613:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4614:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4615:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4616:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4617:         my ($rdummy,$roledef)=
                   4618:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4619:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4620:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4621:             if (defined($syspriv)) {
1.1043    raeburn  4622:                 if ($trest =~ /^$match_community$/) {
                   4623:                     $syspriv =~ s/bre\&S//; 
                   4624:                 }
1.567     raeburn  4625:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4626:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4627:             }
                   4628:             if ($tdomain ne '') {
                   4629:                 if (defined($dompriv)) {
                   4630:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4631:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4632:                 }
                   4633:                 if (($trest ne '') && (defined($coursepriv))) {
                   4634:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4635:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4636:                 }
                   4637:             }
                   4638:         }
                   4639:     }
                   4640: }
                   4641: 
1.678     raeburn  4642: sub group_roleprivs {
                   4643:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4644:     my $access = 1;
                   4645:     my $now = time;
                   4646:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4647:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4648:     if ($access) {
1.811     albertel 4649:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4650:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4651:     }
                   4652: }
1.567     raeburn  4653: 
                   4654: sub standard_roleprivs {
                   4655:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4656:     if (defined($pr{$trole.':s'})) {
                   4657:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4658:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4659:     }
                   4660:     if ($tdomain ne '') {
                   4661:         if (defined($pr{$trole.':d'})) {
                   4662:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4663:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4664:         }
                   4665:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4666:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4667:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4668:         }
                   4669:     }
                   4670: }
                   4671: 
                   4672: sub set_userprivs {
1.1064    raeburn  4673:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4674:     my $author=0;
                   4675:     my $adv=0;
1.678     raeburn  4676:     my %grouproles = ();
                   4677:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  4678:         my @groupkeys; 
1.1000    raeburn  4679:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  4680:             push(@groupkeys,$role);
                   4681:         }
                   4682:         if (ref($groups_roles) eq 'HASH') {
                   4683:             foreach my $key (keys(%{$groups_roles})) {
                   4684:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4685:                     push(@groupkeys,$key);
                   4686:                 }
                   4687:             }
                   4688:         }
                   4689:         if (@groupkeys > 0) {
                   4690:             foreach my $role (@groupkeys) {
                   4691:                 my ($trole,$area,$sec,$extendedarea);
                   4692:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4693:                     $trole = $1;
                   4694:                     $area = $2;
                   4695:                     $sec = $3;
                   4696:                     $extendedarea = $area.$sec;
                   4697:                     if (exists($$allgroups{$area})) {
                   4698:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4699:                             my $spec = $trole.'.'.$extendedarea;
                   4700:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4701:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  4702:                         }
1.678     raeburn  4703:                     }
                   4704:                 }
                   4705:             }
                   4706:         }
                   4707:     }
1.800     albertel 4708:     foreach my $group (keys(%grouproles)) {
                   4709:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4710:     }
1.800     albertel 4711:     foreach my $role (keys(%{$allroles})) {
                   4712:         my %thesepriv;
1.941     raeburn  4713:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4714:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4715:             if ($item ne '') {
                   4716:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4717:                 if ($restrictions eq '') {
                   4718:                     $thesepriv{$privilege}='F';
                   4719:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4720:                     $thesepriv{$privilege}.=$restrictions;
                   4721:                 }
                   4722:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4723:             }
                   4724:         }
                   4725:         my $thesestr='';
1.1104    raeburn  4726:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 4727: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4728: 	}
                   4729:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4730:     }
                   4731:     return ($author,$adv);
                   4732: }
                   4733: 
1.994     raeburn  4734: sub role_status {
1.1104    raeburn  4735:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4736:     my @pwhere = ();
                   4737:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4738:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4739:         unless (!defined($$role) || $$role eq '') {
                   4740:             $$where=join('.',@pwhere);
                   4741:             $$trolecode=$$role.'.'.$$where;
                   4742:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4743:             $$tstatus='is';
1.1104    raeburn  4744:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  4745:                 $$tstatus='future';
1.1034    raeburn  4746:                 if ($$tstart<$now) {
                   4747:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4748:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  4749:                             my (%allroles,%allgroups,$group_privs,
                   4750:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4751:                             my %userroles = (
                   4752:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4753:                             );
1.1064    raeburn  4754:                             @rolecodes = ('cm'); 
1.1002    raeburn  4755:                             my $spec=$$role.'.'.$$where;
                   4756:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4757:                             if ($$role =~ /^cr\//) {
                   4758:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  4759:                                 push(@rolecodes,'cr');
1.1002    raeburn  4760:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  4761:                                 push(@rolecodes,$$role);
1.1002    raeburn  4762:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4763:                                                     $env{'user.name'});
1.1064    raeburn  4764:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4765:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4766:                                 $group_privs = &unescape($group_privs);
                   4767:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  4768:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
1.1104    raeburn  4769:                                 &get_groups_roles($tdomain,$trest,
                   4770:                                                   \%course_roles,\@rolecodes,
                   4771:                                                   \%groups_roles);
1.1002    raeburn  4772:                             } else {
1.1064    raeburn  4773:                                 push(@rolecodes,$$role);
1.1002    raeburn  4774:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4775:                             }
1.1064    raeburn  4776:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4777:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4778:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4779:                         }
                   4780:                     }
1.1034    raeburn  4781:                     $$tstatus = 'is';
1.1002    raeburn  4782:                 }
1.994     raeburn  4783:             }
                   4784:             if ($$tend) {
1.1104    raeburn  4785:                 if ($$tend<$update) {
1.994     raeburn  4786:                     $$tstatus='expired';
                   4787:                 } elsif ($$tend<$now) {
                   4788:                     $$tstatus='will_not';
                   4789:                 }
                   4790:             }
                   4791:         }
                   4792:     }
                   4793: }
                   4794: 
1.1104    raeburn  4795: sub get_groups_roles {
                   4796:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   4797:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   4798:                   (ref($rolecodes) eq 'ARRAY') && 
                   4799:                   (ref($groups_roles) eq 'HASH')); 
                   4800:     if (keys(%{$cdom_courseroles}) > 0) {
                   4801:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   4802:         if ($cdom ne '' && $cnum ne '') {
                   4803:             foreach my $key (keys(%{$cdom_courseroles})) {
                   4804:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   4805:                     my $crsrole = $1;
                   4806:                     my $crssec = $2;
                   4807:                     if ($crsrole =~ /^cr/) {
                   4808:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   4809:                             push(@{$rolecodes},'cr');
                   4810:                         }
                   4811:                     } else {
                   4812:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   4813:                             push(@{$rolecodes},$crsrole);
                   4814:                         }
                   4815:                     }
                   4816:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   4817:                     if ($crssec ne '') {
                   4818:                         $rolekey .= "/$crssec";
                   4819:                     }
                   4820:                     $rolekey .= './';
                   4821:                     $groups_roles->{$rolekey} = $rolecodes;
                   4822:                 }
                   4823:             }
                   4824:         }
                   4825:     }
                   4826:     return;
                   4827: }
                   4828: 
                   4829: sub delete_env_groupprivs {
                   4830:     my ($where,$courseroles,$possroles) = @_;
                   4831:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   4832:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   4833:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   4834:         %{$courseroles->{$udom}} =
                   4835:             &get_my_roles('','','userroles',['active'],
                   4836:                           $possroles,[$udom],1);
                   4837:     }
                   4838:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   4839:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   4840:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   4841:             my $area = '/'.$cdom.'/'.$cnum;
                   4842:             my $privkey = "user.priv.$crsrole.$area";
                   4843:             if ($crssec ne '') {
                   4844:                 $privkey .= '/'.$crssec;
                   4845:             }
                   4846:             $privkey .= ".$area/$group";
                   4847:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   4848:         }
                   4849:     }
                   4850:     return;
                   4851: }
                   4852: 
1.994     raeburn  4853: sub check_adhoc_privs {
1.1104    raeburn  4854:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  4855:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4856:     if ($env{$cckey}) {
                   4857:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  4858:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4859:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  4860:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4861:         }
                   4862:     } else {
1.1088    raeburn  4863:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4864:     }
                   4865: }
                   4866: 
                   4867: sub set_adhoc_privileges {
                   4868: # role can be cc or ca
1.1088    raeburn  4869:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  4870:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4871:     my $spec = $role.'.'.$area;
                   4872:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4873:                                   $env{'user.name'});
                   4874:     my %ccrole = ();
                   4875:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4876:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4877:     &appenv(\%userroles,[$role,'cm']);
                   4878:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  4879:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   4880:         &appenv( {'request.role'        => $spec,
                   4881:                   'request.role.domain' => $dcdom,
                   4882:                   'request.course.sec'  => ''
                   4883:                  }
                   4884:                );
                   4885:         my $tadv=0;
                   4886:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   4887:         &appenv({'request.role.adv'    => $tadv});
                   4888:     }
1.994     raeburn  4889: }
                   4890: 
1.12      www      4891: # --------------------------------------------------------------- get interface
                   4892: 
                   4893: sub get {
1.131     albertel 4894:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4895:    my $items='';
1.800     albertel 4896:    foreach my $item (@$storearr) {
                   4897:        $items.=&escape($item).'&';
1.191     harris41 4898:    }
1.12      www      4899:    $items=~s/\&$//;
1.620     albertel 4900:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4901:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4902:    my $uhome=&homeserver($uname,$udomain);
                   4903: 
1.133     albertel 4904:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4905:    my @pairs=split(/\&/,$rep);
1.273     albertel 4906:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4907:      return @pairs;
                   4908:    }
1.15      www      4909:    my %returnhash=();
1.42      www      4910:    my $i=0;
1.800     albertel 4911:    foreach my $item (@$storearr) {
                   4912:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4913:       $i++;
1.191     harris41 4914:    }
1.15      www      4915:    return %returnhash;
1.27      www      4916: }
                   4917: 
                   4918: # --------------------------------------------------------------- del interface
                   4919: 
                   4920: sub del {
1.133     albertel 4921:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4922:    my $items='';
1.800     albertel 4923:    foreach my $item (@$storearr) {
                   4924:        $items.=&escape($item).'&';
1.191     harris41 4925:    }
1.984     neumanie 4926: 
1.27      www      4927:    $items=~s/\&$//;
1.620     albertel 4928:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4929:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4930:    my $uhome=&homeserver($uname,$udomain);
                   4931:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4932: }
                   4933: 
                   4934: # -------------------------------------------------------------- dump interface
                   4935: 
                   4936: sub dump {
1.1086    raeburn  4937:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755     albertel 4938:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4939:     if (!$uname) { $uname=$env{'user.name'}; }
                   4940:     my $uhome=&homeserver($uname,$udomain);
                   4941:     if ($regexp) {
                   4942: 	$regexp=&escape($regexp);
                   4943:     } else {
                   4944: 	$regexp='.';
                   4945:     }
1.1086    raeburn  4946:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755     albertel 4947:     my @pairs=split(/\&/,$rep);
                   4948:     my %returnhash=();
1.1098    foxr     4949:     if (!($rep =~ /^error/ )) {
                   4950: 	foreach my $item (@pairs) {
                   4951: 	    my ($key,$value)=split(/=/,$item,2);
                   4952: 	    $key = &unescape($key);
                   4953: 	    next if ($key =~ /^error: 2 /);
                   4954: 	    $returnhash{$key}=&thaw_unescape($value);
                   4955: 	}
1.755     albertel 4956:     }
                   4957:     return %returnhash;
1.407     www      4958: }
                   4959: 
1.1098    foxr     4960: 
1.717     albertel 4961: # --------------------------------------------------------- dumpstore interface
                   4962: 
                   4963: sub dumpstore {
                   4964:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4965:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4966:    if (!$uname) { $uname=$env{'user.name'}; }
                   4967:    my $uhome=&homeserver($uname,$udomain);
                   4968:    if ($regexp) {
                   4969:        $regexp=&escape($regexp);
                   4970:    } else {
                   4971:        $regexp='.';
                   4972:    }
                   4973:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4974:    my @pairs=split(/\&/,$rep);
                   4975:    my %returnhash=();
                   4976:    foreach my $item (@pairs) {
                   4977:        my ($key,$value)=split(/=/,$item,2);
                   4978:        next if ($key =~ /^error: 2 /);
                   4979:        $returnhash{$key}=&thaw_unescape($value);
                   4980:    }
                   4981:    return %returnhash;
1.717     albertel 4982: }
                   4983: 
1.407     www      4984: # -------------------------------------------------------------- keys interface
                   4985: 
                   4986: sub getkeys {
                   4987:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4988:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4989:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4990:    my $uhome=&homeserver($uname,$udomain);
                   4991:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4992:    my @keyarray=();
1.800     albertel 4993:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4994:       next if ($key =~ /^error: 2 /);
1.800     albertel 4995:       push(@keyarray,&unescape($key));
1.407     www      4996:    }
                   4997:    return @keyarray;
1.318     matthew  4998: }
                   4999: 
1.319     matthew  5000: # --------------------------------------------------------------- currentdump
                   5001: sub currentdump {
1.328     matthew  5002:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5003:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5004:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5005:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5006:    my $uhome = &homeserver($sname,$sdom);
                   5007:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  5008:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5009:    #
1.318     matthew  5010:    my %returnhash=();
1.319     matthew  5011:    #
                   5012:    if ($rep eq "unknown_cmd") { 
                   5013:        # an old lond will not know currentdump
                   5014:        # Do a dump and make it look like a currentdump
1.822     albertel 5015:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5016:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5017:        my %hash = @tmp;
                   5018:        @tmp=();
1.424     matthew  5019:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5020:    } else {
                   5021:        my @pairs=split(/\&/,$rep);
1.800     albertel 5022:        foreach my $pair (@pairs) {
                   5023:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5024:            my ($symb,$param) = split(/:/,$key);
                   5025:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5026:                                                         &thaw_unescape($value);
1.319     matthew  5027:        }
1.191     harris41 5028:    }
1.12      www      5029:    return %returnhash;
1.424     matthew  5030: }
                   5031: 
                   5032: sub convert_dump_to_currentdump{
                   5033:     my %hash = %{shift()};
                   5034:     my %returnhash;
                   5035:     # Code ripped from lond, essentially.  The only difference
                   5036:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5037:     # we might run in to problems with parameter names =~ /^v\./
                   5038:     while (my ($key,$value) = each(%hash)) {
                   5039:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5040: 	$symb  = &unescape($symb);
                   5041: 	$param = &unescape($param);
1.424     matthew  5042:         next if ($v eq 'version' || $symb eq 'keys');
                   5043:         next if (exists($returnhash{$symb}) &&
                   5044:                  exists($returnhash{$symb}->{$param}) &&
                   5045:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5046:         $returnhash{$symb}->{$param}=$value;
                   5047:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5048:     }
                   5049:     #
                   5050:     # Remove all of the keys in the hashes which keep track of
                   5051:     # the version of the parameter.
                   5052:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5053:         # use a foreach because we are going to delete from the hash.
                   5054:         foreach my $key (keys(%$param_hash)) {
                   5055:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5056:         }
                   5057:     }
                   5058:     return \%returnhash;
1.12      www      5059: }
                   5060: 
1.627     albertel 5061: # ------------------------------------------------------ critical inc interface
                   5062: 
                   5063: sub cinc {
                   5064:     return &inc(@_,'critical');
                   5065: }
                   5066: 
1.449     matthew  5067: # --------------------------------------------------------------- inc interface
                   5068: 
                   5069: sub inc {
1.627     albertel 5070:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5071:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5072:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5073:     my $uhome=&homeserver($uname,$udomain);
                   5074:     my $items='';
                   5075:     if (! ref($store)) {
                   5076:         # got a single value, so use that instead
                   5077:         $items = &escape($store).'=&';
                   5078:     } elsif (ref($store) eq 'SCALAR') {
                   5079:         $items = &escape($$store).'=&';        
                   5080:     } elsif (ref($store) eq 'ARRAY') {
                   5081:         $items = join('=&',map {&escape($_);} @{$store});
                   5082:     } elsif (ref($store) eq 'HASH') {
                   5083:         while (my($key,$value) = each(%{$store})) {
                   5084:             $items.= &escape($key).'='.&escape($value).'&';
                   5085:         }
                   5086:     }
                   5087:     $items=~s/\&$//;
1.627     albertel 5088:     if ($critical) {
                   5089: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5090:     } else {
                   5091: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5092:     }
1.449     matthew  5093: }
                   5094: 
1.12      www      5095: # --------------------------------------------------------------- put interface
                   5096: 
                   5097: sub put {
1.134     albertel 5098:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5099:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5100:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5101:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5102:    my $items='';
1.800     albertel 5103:    foreach my $item (keys(%$storehash)) {
                   5104:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5105:    }
1.12      www      5106:    $items=~s/\&$//;
1.134     albertel 5107:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5108: }
                   5109: 
1.631     albertel 5110: # ------------------------------------------------------------ newput interface
                   5111: 
                   5112: sub newput {
                   5113:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5114:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5115:    if (!$uname) { $uname=$env{'user.name'}; }
                   5116:    my $uhome=&homeserver($uname,$udomain);
                   5117:    my $items='';
                   5118:    foreach my $key (keys(%$storehash)) {
                   5119:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5120:    }
                   5121:    $items=~s/\&$//;
                   5122:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5123: }
                   5124: 
                   5125: # ---------------------------------------------------------  putstore interface
                   5126: 
1.524     raeburn  5127: sub putstore {
1.715     albertel 5128:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5129:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5130:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5131:    my $uhome=&homeserver($uname,$udomain);
                   5132:    my $items='';
1.715     albertel 5133:    foreach my $key (keys(%$storehash)) {
                   5134:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5135:    }
1.715     albertel 5136:    $items=~s/\&$//;
1.716     albertel 5137:    my $esc_symb=&escape($symb);
                   5138:    my $esc_v=&escape($version);
1.715     albertel 5139:    my $reply =
1.716     albertel 5140:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5141: 	      $uhome);
                   5142:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5143:        # gfall back to way things use to be done
1.715     albertel 5144:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5145: 			    $uname);
1.524     raeburn  5146:    }
1.715     albertel 5147:    return $reply;
                   5148: }
                   5149: 
                   5150: sub old_putstore {
1.716     albertel 5151:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5152:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5153:     if (!$uname) { $uname=$env{'user.name'}; }
                   5154:     my $uhome=&homeserver($uname,$udomain);
                   5155:     my %newstorehash;
1.800     albertel 5156:     foreach my $item (keys(%$storehash)) {
                   5157: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5158: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5159:     }
                   5160:     my $items='';
                   5161:     my %allitems = ();
1.800     albertel 5162:     foreach my $item (keys(%newstorehash)) {
                   5163: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5164: 	    my $key = $1.':keys:'.$2;
                   5165: 	    $allitems{$key} .= $3.':';
                   5166: 	}
1.800     albertel 5167: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5168:     }
1.800     albertel 5169:     foreach my $item (keys(%allitems)) {
                   5170: 	$allitems{$item} =~ s/\:$//;
                   5171: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5172:     }
                   5173:     $items=~s/\&$//;
                   5174:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5175: }
                   5176: 
1.47      www      5177: # ------------------------------------------------------ critical put interface
                   5178: 
                   5179: sub cput {
1.134     albertel 5180:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5181:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5182:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5183:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5184:    my $items='';
1.800     albertel 5185:    foreach my $item (keys(%$storehash)) {
                   5186:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5187:    }
1.47      www      5188:    $items=~s/\&$//;
1.134     albertel 5189:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5190: }
                   5191: 
                   5192: # -------------------------------------------------------------- eget interface
                   5193: 
                   5194: sub eget {
1.133     albertel 5195:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5196:    my $items='';
1.800     albertel 5197:    foreach my $item (@$storearr) {
                   5198:        $items.=&escape($item).'&';
1.191     harris41 5199:    }
1.12      www      5200:    $items=~s/\&$//;
1.620     albertel 5201:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5202:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5203:    my $uhome=&homeserver($uname,$udomain);
                   5204:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5205:    my @pairs=split(/\&/,$rep);
                   5206:    my %returnhash=();
1.42      www      5207:    my $i=0;
1.800     albertel 5208:    foreach my $item (@$storearr) {
                   5209:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5210:       $i++;
1.191     harris41 5211:    }
1.12      www      5212:    return %returnhash;
                   5213: }
                   5214: 
1.667     albertel 5215: # ------------------------------------------------------------ tmpput interface
                   5216: sub tmpput {
1.802     raeburn  5217:     my ($storehash,$server,$context)=@_;
1.667     albertel 5218:     my $items='';
1.800     albertel 5219:     foreach my $item (keys(%$storehash)) {
                   5220: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5221:     }
                   5222:     $items=~s/\&$//;
1.802     raeburn  5223:     if (defined($context)) {
                   5224:         $items .= ':'.&escape($context);
                   5225:     }
1.667     albertel 5226:     return &reply("tmpput:$items",$server);
                   5227: }
                   5228: 
                   5229: # ------------------------------------------------------------ tmpget interface
                   5230: sub tmpget {
1.688     albertel 5231:     my ($token,$server)=@_;
                   5232:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5233:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5234:     my %returnhash;
                   5235:     foreach my $item (split(/\&/,$rep)) {
                   5236: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5237:         next if ($key =~ /^error: 2 /);
1.667     albertel 5238: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5239:     }
                   5240:     return %returnhash;
                   5241: }
                   5242: 
1.1113    raeburn  5243: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5244: sub tmpdel {
                   5245:     my ($token,$server)=@_;
                   5246:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5247:     return &reply("tmpdel:$token",$server);
                   5248: }
                   5249: 
1.765     albertel 5250: # -------------------------------------------------- portfolio access checking
                   5251: 
                   5252: sub portfolio_access {
1.766     albertel 5253:     my ($requrl) = @_;
1.765     albertel 5254:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5255:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5256:     if ($result) {
                   5257:         my %setters;
                   5258:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5259:             my ($startblock,$endblock) =
                   5260:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5261:             if ($startblock && $endblock) {
                   5262:                 return 'B';
                   5263:             }
                   5264:         } else {
                   5265:             my ($startblock,$endblock) =
                   5266:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5267:             if ($startblock && $endblock) {
                   5268:                 return 'B';
                   5269:             }
                   5270:         }
                   5271:     }
1.765     albertel 5272:     if ($result eq 'ok') {
1.766     albertel 5273:        return 'F';
1.765     albertel 5274:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5275:        return 'A';
1.765     albertel 5276:     }
1.766     albertel 5277:     return '';
1.765     albertel 5278: }
                   5279: 
                   5280: sub get_portfolio_access {
1.767     albertel 5281:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5282: 
                   5283:     if (!ref($access_hash)) {
                   5284: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5285: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5286: 						   $file_name);
                   5287: 	$access_hash = $access_controls{$file_name};
                   5288:     }
                   5289: 
1.765     albertel 5290:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5291:     my $now = time;
                   5292:     if (ref($access_hash) eq 'HASH') {
                   5293:         foreach my $key (keys(%{$access_hash})) {
                   5294:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5295:             if ($start > $now) {
                   5296:                 next;
                   5297:             }
                   5298:             if ($end && $end<$now) {
                   5299:                 next;
                   5300:             }
                   5301:             if ($scope eq 'public') {
                   5302:                 $public = $key;
                   5303:                 last;
                   5304:             } elsif ($scope eq 'guest') {
                   5305:                 $guest = $key;
                   5306:             } elsif ($scope eq 'domains') {
                   5307:                 push(@domains,$key);
                   5308:             } elsif ($scope eq 'users') {
                   5309:                 push(@users,$key);
                   5310:             } elsif ($scope eq 'course') {
                   5311:                 push(@courses,$key);
                   5312:             } elsif ($scope eq 'group') {
                   5313:                 push(@groups,$key);
                   5314:             }
                   5315:         }
                   5316:         if ($public) {
                   5317:             return 'ok';
                   5318:         }
                   5319:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5320:             if ($guest) {
                   5321:                 return $guest;
                   5322:             }
                   5323:         } else {
                   5324:             if (@domains > 0) {
                   5325:                 foreach my $domkey (@domains) {
                   5326:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5327:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5328:                             return 'ok';
                   5329:                         }
                   5330:                     }
                   5331:                 }
                   5332:             }
                   5333:             if (@users > 0) {
                   5334:                 foreach my $userkey (@users) {
1.865     raeburn  5335:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5336:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5337:                             if (ref($item) eq 'HASH') {
                   5338:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5339:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5340:                                     return 'ok';
                   5341:                                 }
                   5342:                             }
                   5343:                         }
                   5344:                     } 
1.765     albertel 5345:                 }
                   5346:             }
                   5347:             my %roleshash;
                   5348:             my @courses_and_groups = @courses;
                   5349:             push(@courses_and_groups,@groups); 
                   5350:             if (@courses_and_groups > 0) {
                   5351:                 my (%allgroups,%allroles); 
                   5352:                 my ($start,$end,$role,$sec,$group);
                   5353:                 foreach my $envkey (%env) {
1.1060    raeburn  5354:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5355:                         my $cid = $2.'_'.$3; 
                   5356:                         if ($1 eq 'gr') {
                   5357:                             $group = $4;
                   5358:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5359:                         } else {
                   5360:                             if ($4 eq '') {
                   5361:                                 $sec = 'none';
                   5362:                             } else {
                   5363:                                 $sec = $4;
                   5364:                             }
                   5365:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5366:                         }
1.811     albertel 5367:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5368:                         my $cid = $2.'_'.$3;
                   5369:                         if ($4 eq '') {
                   5370:                             $sec = 'none';
                   5371:                         } else {
                   5372:                             $sec = $4;
                   5373:                         }
                   5374:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5375:                     }
                   5376:                 }
                   5377:                 if (keys(%allroles) == 0) {
                   5378:                     return;
                   5379:                 }
                   5380:                 foreach my $key (@courses_and_groups) {
                   5381:                     my %content = %{$$access_hash{$key}};
                   5382:                     my $cnum = $content{'number'};
                   5383:                     my $cdom = $content{'domain'};
                   5384:                     my $cid = $cdom.'_'.$cnum;
                   5385:                     if (!exists($allroles{$cid})) {
                   5386:                         next;
                   5387:                     }    
                   5388:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5389:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5390:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5391:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5392:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5393:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5394:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5395:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5396:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5397:                                         if (grep/^all$/,@sections) {
                   5398:                                             return 'ok';
                   5399:                                         } else {
                   5400:                                             if (grep/^$sec$/,@sections) {
                   5401:                                                 return 'ok';
                   5402:                                             }
                   5403:                                         }
                   5404:                                     }
                   5405:                                 }
                   5406:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5407:                                     if (grep/^none$/,@groups) {
                   5408:                                         return 'ok';
                   5409:                                     }
                   5410:                                 } else {
                   5411:                                     if (grep/^all$/,@groups) {
                   5412:                                         return 'ok';
                   5413:                                     } 
                   5414:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5415:                                         if (grep/^$group$/,@groups) {
                   5416:                                             return 'ok';
                   5417:                                         }
                   5418:                                     }
                   5419:                                 } 
                   5420:                             }
                   5421:                         }
                   5422:                     }
                   5423:                 }
                   5424:             }
                   5425:             if ($guest) {
                   5426:                 return $guest;
                   5427:             }
                   5428:         }
                   5429:     }
                   5430:     return;
                   5431: }
                   5432: 
                   5433: sub course_group_datechecker {
                   5434:     my ($dates,$now,$status) = @_;
                   5435:     my ($start,$end) = split(/\./,$dates);
                   5436:     if (!$start && !$end) {
                   5437:         return 'ok';
                   5438:     }
                   5439:     if (grep/^active$/,@{$status}) {
                   5440:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5441:             return 'ok';
                   5442:         }
                   5443:     }
                   5444:     if (grep/^previous$/,@{$status}) {
                   5445:         if ($end > $now ) {
                   5446:             return 'ok';
                   5447:         }
                   5448:     }
                   5449:     if (grep/^future$/,@{$status}) {
                   5450:         if ($start > $now) {
                   5451:             return 'ok';
                   5452:         }
                   5453:     }
                   5454:     return; 
                   5455: }
                   5456: 
                   5457: sub parse_portfolio_url {
                   5458:     my ($url) = @_;
                   5459: 
                   5460:     my ($type,$udom,$unum,$group,$file_name);
                   5461:     
1.823     albertel 5462:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5463: 	$type = 1;
                   5464:         $udom = $1;
                   5465:         $unum = $2;
                   5466:         $file_name = $3;
1.823     albertel 5467:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5468: 	$type = 2;
                   5469:         $udom = $1;
                   5470:         $unum = $2;
                   5471:         $group = $3;
                   5472:         $file_name = $3.'/'.$4;
                   5473:     }
                   5474:     if (wantarray) {
                   5475: 	return ($type,$udom,$unum,$file_name,$group);
                   5476:     }
                   5477:     return $type;
                   5478: }
                   5479: 
                   5480: sub is_portfolio_url {
                   5481:     my ($url) = @_;
                   5482:     return scalar(&parse_portfolio_url($url));
                   5483: }
                   5484: 
1.798     raeburn  5485: sub is_portfolio_file {
                   5486:     my ($file) = @_;
1.820     raeburn  5487:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5488:         return 1;
                   5489:     }
                   5490:     return;
                   5491: }
                   5492: 
1.976     raeburn  5493: sub usertools_access {
1.1084    raeburn  5494:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  5495:     my ($access,%tools);
                   5496:     if ($context eq '') {
                   5497:         $context = 'tools';
                   5498:     }
                   5499:     if ($context eq 'requestcourses') {
                   5500:         %tools = (
                   5501:                       official   => 1,
                   5502:                       unofficial => 1,
1.1006    raeburn  5503:                       community  => 1,
1.985     raeburn  5504:                  );
                   5505:     } else {
                   5506:         %tools = (
                   5507:                       aboutme   => 1,
                   5508:                       blog      => 1,
                   5509:                       portfolio => 1,
                   5510:                  );
                   5511:     }
1.976     raeburn  5512:     return if (!defined($tools{$tool}));
                   5513: 
                   5514:     if ((!defined($udom)) || (!defined($uname))) {
                   5515:         $udom = $env{'user.domain'};
                   5516:         $uname = $env{'user.name'};
                   5517:     }
                   5518: 
1.978     raeburn  5519:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5520:         if ($action ne 'reload') {
1.985     raeburn  5521:             if ($context eq 'requestcourses') {
                   5522:                 return $env{'environment.canrequest.'.$tool};
                   5523:             } else {
                   5524:                 return $env{'environment.availabletools.'.$tool};
                   5525:             }
                   5526:         }
1.976     raeburn  5527:     }
                   5528: 
                   5529:     my ($toolstatus,$inststatus);
                   5530: 
1.985     raeburn  5531:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5532:          ($action ne 'reload')) {
                   5533:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5534:         $inststatus = $env{'environment.inststatus'};
                   5535:     } else {
1.1084    raeburn  5536:         if (ref($userenvref) eq 'HASH') {
                   5537:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   5538:             $inststatus = $userenvref->{'inststatus'};
                   5539:         } else {
                   5540:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   5541:             $toolstatus = $userenv{$context.'.'.$tool};
                   5542:             $inststatus = $userenv{'inststatus'};
                   5543:         }
1.976     raeburn  5544:     }
                   5545: 
                   5546:     if ($toolstatus ne '') {
                   5547:         if ($toolstatus) {
                   5548:             $access = 1;
                   5549:         } else {
                   5550:             $access = 0;
                   5551:         }
                   5552:         return $access;
                   5553:     }
                   5554: 
1.1084    raeburn  5555:     my ($is_adv,%domdef);
                   5556:     if (ref($is_advref) eq 'HASH') {
                   5557:         $is_adv = $is_advref->{'is_adv'};
                   5558:     } else {
                   5559:         $is_adv = &is_advanced_user($udom,$uname);
                   5560:     }
                   5561:     if (ref($domdefref) eq 'HASH') {
                   5562:         %domdef = %{$domdefref};
                   5563:     } else {
                   5564:         %domdef = &get_domain_defaults($udom);
                   5565:     }
1.976     raeburn  5566:     if (ref($domdef{$tool}) eq 'HASH') {
                   5567:         if ($is_adv) {
                   5568:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5569:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5570:                     $access = 1;
                   5571:                 } else {
                   5572:                     $access = 0;
                   5573:                 }
                   5574:                 return $access;
                   5575:             }
                   5576:         }
                   5577:         if ($inststatus ne '') {
                   5578:             my ($hasaccess,$hasnoaccess);
                   5579:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5580:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5581:                     if ($domdef{$tool}{$affiliation}) {
                   5582:                         $hasaccess = 1;
                   5583:                     } else {
                   5584:                         $hasnoaccess = 1;
                   5585:                     }
                   5586:                 }
                   5587:             }
                   5588:             if ($hasaccess || $hasnoaccess) {
                   5589:                 if ($hasaccess) {
                   5590:                     $access = 1;
                   5591:                 } elsif ($hasnoaccess) {
                   5592:                     $access = 0; 
                   5593:                 }
                   5594:                 return $access;
                   5595:             }
                   5596:         } else {
                   5597:             if ($domdef{$tool}{'default'} ne '') {
                   5598:                 if ($domdef{$tool}{'default'}) {
                   5599:                     $access = 1;
                   5600:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5601:                     $access = 0;
                   5602:                 }
                   5603:                 return $access;
                   5604:             }
                   5605:         }
                   5606:     } else {
1.985     raeburn  5607:         if ($context eq 'tools') {
                   5608:             $access = 1;
                   5609:         } else {
                   5610:             $access = 0;
                   5611:         }
1.976     raeburn  5612:         return $access;
                   5613:     }
                   5614: }
                   5615: 
1.1050    raeburn  5616: sub is_course_owner {
                   5617:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5618:     if (($udom eq '') || ($uname eq '')) {
                   5619:         $udom = $env{'user.domain'};
                   5620:         $uname = $env{'user.name'};
                   5621:     }
                   5622:     unless (($udom eq '') || ($uname eq '')) {
                   5623:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5624:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5625:                 return 1;
                   5626:             } else {
                   5627:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5628:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5629:                     return 1;
                   5630:                 }
                   5631:             }
                   5632:         }
                   5633:     }
                   5634:     return;
                   5635: }
                   5636: 
1.976     raeburn  5637: sub is_advanced_user {
                   5638:     my ($udom,$uname) = @_;
1.1085    raeburn  5639:     if ($udom ne '' && $uname ne '') {
                   5640:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  5641:             if (wantarray) {
                   5642:                 return ($env{'user.adv'},$env{'user.author'});
                   5643:             } else {
                   5644:                 return $env{'user.adv'};
                   5645:             }
1.1085    raeburn  5646:         }
                   5647:     }
1.976     raeburn  5648:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5649:     my %allroles;
1.1128    raeburn  5650:     my ($is_adv,$is_author);
1.976     raeburn  5651:     foreach my $role (keys(%roleshash)) {
                   5652:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5653:         my $area = '/'.$tdomain.'/'.$trest;
                   5654:         if ($sec ne '') {
                   5655:             $area .= '/'.$sec;
                   5656:         }
                   5657:         if (($area ne '') && ($trole ne '')) {
                   5658:             my $spec=$trole.'.'.$area;
                   5659:             if ($trole =~ /^cr\//) {
                   5660:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5661:             } elsif ($trole ne 'gr') {
                   5662:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5663:             }
1.1128    raeburn  5664:             if ($trole eq 'au') {
                   5665:                 $is_author = 1;
                   5666:             }
1.976     raeburn  5667:         }
                   5668:     }
                   5669:     foreach my $role (keys(%allroles)) {
                   5670:         last if ($is_adv);
                   5671:         foreach my $item (split(/:/,$allroles{$role})) {
                   5672:             if ($item ne '') {
                   5673:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5674:                 if ($privilege eq 'adv') {
                   5675:                     $is_adv = 1;
                   5676:                     last;
                   5677:                 }
                   5678:             }
                   5679:         }
                   5680:     }
1.1128    raeburn  5681:     if (wantarray) {
                   5682:         return ($is_adv,$is_author);
                   5683:     }
1.976     raeburn  5684:     return $is_adv;
                   5685: }
1.798     raeburn  5686: 
1.1035    raeburn  5687: sub check_can_request {
1.1036    raeburn  5688:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5689:     my $canreq = 0;
                   5690:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5691:     my @options = ('approval','validate','autolimit');
                   5692:     my $optregex = join('|',@options);
                   5693:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5694:         foreach my $type (@{$types}) {
                   5695:             if (&usertools_access($env{'user.name'},
                   5696:                                   $env{'user.domain'},
                   5697:                                   $type,undef,'requestcourses')) {
                   5698:                 $canreq ++;
1.1036    raeburn  5699:                 if (ref($request_domains) eq 'HASH') {
                   5700:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5701:                 }
1.1035    raeburn  5702:                 if ($dom eq $env{'user.domain'}) {
                   5703:                     $can_request->{$type} = 1;
                   5704:                 }
                   5705:             }
                   5706:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5707:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5708:                 if (@curr > 0) {
1.1036    raeburn  5709:                     foreach my $item (@curr) {
                   5710:                         if (ref($request_domains) eq 'HASH') {
                   5711:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5712:                             if ($otherdom ne '') {
                   5713:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5714:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5715:                                         push(@{$request_domains->{$type}},$otherdom);
                   5716:                                     }
                   5717:                                 } else {
                   5718:                                     push(@{$request_domains->{$type}},$otherdom);
                   5719:                                 }
                   5720:                             }
                   5721:                         }
                   5722:                     }
                   5723:                     unless($dom eq $env{'user.domain'}) {
                   5724:                         $canreq ++;
1.1035    raeburn  5725:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5726:                             $can_request->{$type} = 1;
                   5727:                         }
                   5728:                     }
                   5729:                 }
                   5730:             }
                   5731:         }
                   5732:     }
                   5733:     return $canreq;
                   5734: }
                   5735: 
1.341     www      5736: # ---------------------------------------------- Custom access rule evaluation
                   5737: 
                   5738: sub customaccess {
                   5739:     my ($priv,$uri)=@_;
1.807     albertel 5740:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5741:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5742:     $udom = &LONCAPA::clean_domain($udom);
                   5743:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5744:     my $access=0;
1.800     albertel 5745:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5746: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5747: 	if ($type eq 'user') {
                   5748: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5749: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5750: 		if ($tdom) {
                   5751: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5752: 		}
1.896     albertel 5753: 		if ($tuname) {
                   5754: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5755: 		}
                   5756: 		$access=($effect eq 'allow');
                   5757: 		last;
                   5758: 	    }
                   5759: 	} else {
                   5760: 	    if ($role) {
                   5761: 		if ($role ne $urole) { next; }
                   5762: 	    }
                   5763: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5764: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5765: 		if ($tdom) {
                   5766: 		    if ($tdom ne $udom) { next; }
                   5767: 		}
                   5768: 		if ($tcrs) {
                   5769: 		    if ($tcrs ne $ucrs) { next; }
                   5770: 		}
                   5771: 		if ($tsec) {
                   5772: 		    if ($tsec ne $usec) { next; }
                   5773: 		}
                   5774: 		$access=($effect eq 'allow');
                   5775: 		last;
                   5776: 	    }
                   5777: 	    if ($realm eq '' && $role eq '') {
                   5778: 		$access=($effect eq 'allow');
                   5779: 	    }
1.402     bowersj2 5780: 	}
1.341     www      5781:     }
                   5782:     return $access;
                   5783: }
                   5784: 
1.103     harris41 5785: # ------------------------------------------------- Check for a user privilege
1.12      www      5786: 
                   5787: sub allowed {
1.810     raeburn  5788:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5789:     my $ver_orguri=$uri;
1.439     www      5790:     $uri=&deversion($uri);
1.152     www      5791:     my $orguri=$uri;
1.52      www      5792:     $uri=&declutter($uri);
1.809     raeburn  5793: 
1.810     raeburn  5794:     if ($priv eq 'evb') {
                   5795: # Evade communication block restrictions for specified role in a course
                   5796:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5797:             return $1;
                   5798:         } else {
                   5799:             return;
                   5800:         }
                   5801:     }
                   5802: 
1.620     albertel 5803:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5804: # Free bre access to adm and meta resources
1.775     albertel 5805:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5806: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5807: 	&& ($priv eq 'bre')) {
1.14      www      5808: 	return 'F';
1.159     www      5809:     }
                   5810: 
1.545     banghart 5811: # Free bre access to user's own portfolio contents
1.714     raeburn  5812:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5813:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5814: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5815:         my %setters;
                   5816:         my ($startblock,$endblock) = 
                   5817:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5818:         if ($startblock && $endblock) {
                   5819:             return 'B';
                   5820:         } else {
                   5821:             return 'F';
                   5822:         }
1.545     banghart 5823:     }
                   5824: 
1.762     raeburn  5825: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5826:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5827:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5828:         if (exists($env{'request.course.id'})) {
                   5829:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5830:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5831:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5832:                 my $courseprivid=$env{'request.course.id'};
                   5833:                 $courseprivid=~s/\_/\//;
                   5834:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5835:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5836:                     return $1; 
1.762     raeburn  5837:                 } else {
                   5838:                     if ($env{'request.course.sec'}) {
                   5839:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5840:                     }
                   5841:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5842:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5843:                         return $2;
                   5844:                     }
1.714     raeburn  5845:                 }
                   5846:             }
                   5847:         }
                   5848:     }
                   5849: 
1.159     www      5850: # Free bre to public access
                   5851: 
                   5852:     if ($priv eq 'bre') {
1.238     www      5853:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5854: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5855:            return 'F'; 
                   5856:         }
1.238     www      5857:         if ($copyright eq 'priv') {
                   5858:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5859: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5860: 		return '';
                   5861:             }
                   5862:         }
                   5863:         if ($copyright eq 'domain') {
                   5864:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5865: 	    unless (($env{'user.domain'} eq $1) ||
                   5866:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5867: 		return '';
                   5868:             }
1.262     matthew  5869:         }
1.620     albertel 5870:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5871:             # Library role, so allow browsing of resources in this domain.
                   5872:             return 'F';
1.238     www      5873:         }
1.341     www      5874:         if ($copyright eq 'custom') {
                   5875: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5876:         }
1.14      www      5877:     }
1.264     matthew  5878:     # Domain coordinator is trying to create a course
1.620     albertel 5879:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5880:         # uri is the requested domain in this case.
                   5881:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5882:         # a role of dc for the domain in question.
1.620     albertel 5883:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5884:     }
1.29      www      5885: 
1.52      www      5886:     my $thisallowed='';
                   5887:     my $statecond=0;
                   5888:     my $courseprivid='';
                   5889: 
1.1039    raeburn  5890:     my $ownaccess;
1.1043    raeburn  5891:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  5892:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5893:         if ($uri eq '') {
                   5894:             $ownaccess = 1;
                   5895:         } else {
                   5896:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5897:                 my $udom = $env{'user.domain'};
                   5898:                 my $uname = $env{'user.name'};
                   5899:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5900:                     $ownaccess = 1;
1.1040    raeburn  5901:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5902:                     unless ($uri =~ m{\.\./}) {
                   5903:                         $ownaccess = 1;
                   5904:                     }
                   5905:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5906:                     my $now = time;
                   5907:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5908:                         my $adom = $1;
                   5909:                         foreach my $key (keys(%env)) {
1.1042    raeburn  5910:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  5911:                                 my ($start,$end) = split('.',$env{$key});
                   5912:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5913:                                     $ownaccess = 1;
                   5914:                                     last;
                   5915:                                 }
                   5916:                             }
                   5917:                         }
                   5918:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5919:                         my $adom = $1;
                   5920:                         my $aname = $2;
1.1042    raeburn  5921:                         foreach my $role ('ca','aa') { 
                   5922:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   5923:                                 my ($start,$end) =
                   5924:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   5925:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5926:                                     $ownaccess = 1;
                   5927:                                     last;
                   5928:                                 }
1.1039    raeburn  5929:                             }
                   5930:                         }
                   5931:                     }
                   5932:                 }
                   5933:             }
                   5934:         }
                   5935:     }
                   5936: 
1.52      www      5937: # Course
                   5938: 
1.620     albertel 5939:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5940:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5941:             $thisallowed.=$1;
                   5942:         }
1.52      www      5943:     }
1.29      www      5944: 
1.52      www      5945: # Domain
                   5946: 
1.620     albertel 5947:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5948:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5949:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5950:             $thisallowed.=$1;
                   5951:         }
1.12      www      5952:     }
1.52      www      5953: 
1.1141    raeburn  5954: # User who is not author or co-author might still be able to edit
                   5955: # resource of an author in the domain (e.g., if Domain Coordinator).
                   5956:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   5957:         (&allowed('mdc',$env{'request.course.id'}))) {
                   5958:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   5959:             $thisallowed.=$1;
                   5960:         }
                   5961:     }
                   5962: 
1.52      www      5963: # Course: uri itself is a course
1.66      www      5964:     my $courseuri=$uri;
                   5965:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5966:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5967: 
1.620     albertel 5968:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5969:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5970:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5971:             $thisallowed.=$1;
                   5972:         }
1.12      www      5973:     }
1.29      www      5974: 
1.665     albertel 5975: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5976: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5977:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5978: 	$thisallowed='';
1.671     raeburn  5979:         my ($match)=&is_on_map($uri);
                   5980:         if ($match) {
                   5981:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5982:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5983:                 $thisallowed.=$1;
                   5984:             }
                   5985:         } else {
1.705     albertel 5986:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5987:             if ($refuri) {
                   5988:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5989:                     $thisallowed='F';
1.671     raeburn  5990:                 } else {
                   5991:                     $refuri=&declutter($refuri);
                   5992:                     my ($match) = &is_on_map($refuri);
                   5993:                     if ($match) {
                   5994:                         $thisallowed='F';
                   5995:                     }
1.669     raeburn  5996:                 }
1.671     raeburn  5997:             }
                   5998:         }
1.314     www      5999:     }
1.492     albertel 6000: 
1.766     albertel 6001:     if ($priv eq 'bre'
                   6002: 	&& $thisallowed ne 'F' 
                   6003: 	&& $thisallowed ne '2'
                   6004: 	&& &is_portfolio_url($uri)) {
                   6005: 	$thisallowed = &portfolio_access($uri);
                   6006:     }
                   6007:     
1.52      www      6008: # Full access at system, domain or course-wide level? Exit.
1.29      www      6009:     if ($thisallowed=~/F/) {
                   6010: 	return 'F';
                   6011:     }
                   6012: 
1.52      www      6013: # If this is generating or modifying users, exit with special codes
1.29      www      6014: 
1.643     www      6015:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6016: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6017: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6018: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6019: 	    unless ($auname) { return $thisallowed; }
                   6020: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6021: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6022: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6023: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6024: 	}
1.52      www      6025: 	return $thisallowed;
                   6026:     }
                   6027: #
1.103     harris41 6028: # Gathered so far: system, domain and course wide privileges
1.52      www      6029: #
                   6030: # Course: See if uri or referer is an individual resource that is part of 
                   6031: # the course
                   6032: 
1.620     albertel 6033:     if ($env{'request.course.id'}) {
1.232     www      6034: 
1.620     albertel 6035:        $courseprivid=$env{'request.course.id'};
                   6036:        if ($env{'request.course.sec'}) {
                   6037:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6038:        }
                   6039:        $courseprivid=~s/\_/\//;
                   6040:        my $checkreferer=1;
1.232     www      6041:        my ($match,$cond)=&is_on_map($uri);
                   6042:        if ($match) {
                   6043:            $statecond=$cond;
1.620     albertel 6044:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6045:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      6046:                $thisallowed.=$1;
                   6047:                $checkreferer=0;
                   6048:            }
1.29      www      6049:        }
1.83      www      6050:        
1.148     www      6051:        if ($checkreferer) {
1.620     albertel 6052: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6053:             unless ($refuri) {
1.800     albertel 6054:                 foreach my $key (keys(%env)) {
                   6055: 		    if ($key=~/^httpref\..*\*/) {
                   6056: 			my $pattern=$key;
1.156     www      6057:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6058:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6059:                         $pattern=~s/\//\\\//g;
1.152     www      6060:                         if ($orguri=~/$pattern/) {
1.800     albertel 6061: 			    $refuri=$env{$key};
1.148     www      6062:                         }
                   6063:                     }
1.191     harris41 6064:                 }
1.148     www      6065:             }
1.232     www      6066: 
1.148     www      6067:          if ($refuri) { 
1.152     www      6068: 	  $refuri=&declutter($refuri);
1.232     www      6069:           my ($match,$cond)=&is_on_map($refuri);
                   6070:             if ($match) {
                   6071:               my $refstatecond=$cond;
1.620     albertel 6072:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6073:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      6074:                   $thisallowed.=$1;
1.53      www      6075:                   $uri=$refuri;
                   6076:                   $statecond=$refstatecond;
1.52      www      6077:               }
                   6078:           }
1.148     www      6079:         }
1.29      www      6080:        }
1.52      www      6081:    }
1.29      www      6082: 
1.52      www      6083: #
1.103     harris41 6084: # Gathered now: all privileges that could apply, and condition number
1.52      www      6085: # 
                   6086: #
                   6087: # Full or no access?
                   6088: #
1.29      www      6089: 
1.52      www      6090:     if ($thisallowed=~/F/) {
                   6091: 	return 'F';
                   6092:     }
1.29      www      6093: 
1.52      www      6094:     unless ($thisallowed) {
                   6095:         return '';
                   6096:     }
1.29      www      6097: 
1.52      www      6098: # Restrictions exist, deal with them
                   6099: #
                   6100: #   C:according to course preferences
                   6101: #   R:according to resource settings
                   6102: #   L:unless locked
                   6103: #   X:according to user session state
                   6104: #
                   6105: 
                   6106: # Possibly locked functionality, check all courses
1.54      www      6107: # Locks might take effect only after 10 minutes cache expiration for other
                   6108: # courses, and 2 minutes for current course
1.52      www      6109: 
                   6110:     my $envkey;
                   6111:     if ($thisallowed=~/L/) {
1.1000    raeburn  6112:         foreach $envkey (keys(%env)) {
1.54      www      6113:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6114:                my $courseid=$2;
                   6115:                my $roleid=$1.'.'.$2;
1.92      www      6116:                $courseid=~s/^\///;
1.54      www      6117:                my $expiretime=600;
1.620     albertel 6118:                if ($env{'request.role'} eq $roleid) {
1.54      www      6119: 		  $expiretime=120;
                   6120:                }
                   6121: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6122:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6123:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6124: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6125:                }
1.620     albertel 6126:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6127:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6128: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6129:                        &log($env{'user.domain'},$env{'user.name'},
                   6130:                             $env{'user.home'},
1.57      www      6131:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6132:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6133:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6134: 		       return '';
                   6135:                    }
                   6136:                }
1.620     albertel 6137:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6138:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6139: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6140:                        &log($env{'user.domain'},$env{'user.name'},
                   6141:                             $env{'user.home'},
1.57      www      6142:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6143:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6144:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6145: 		       return '';
                   6146:                    }
                   6147:                }
                   6148: 	   }
1.29      www      6149:        }
1.52      www      6150:     }
                   6151:    
                   6152: #
                   6153: # Rest of the restrictions depend on selected course
                   6154: #
                   6155: 
1.620     albertel 6156:     unless ($env{'request.course.id'}) {
1.766     albertel 6157: 	if ($thisallowed eq 'A') {
                   6158: 	    return 'A';
1.814     raeburn  6159:         } elsif ($thisallowed eq 'B') {
                   6160:             return 'B';
1.766     albertel 6161: 	} else {
                   6162: 	    return '1';
                   6163: 	}
1.52      www      6164:     }
1.29      www      6165: 
1.52      www      6166: #
                   6167: # Now user is definitely in a course
                   6168: #
1.53      www      6169: 
                   6170: 
                   6171: # Course preferences
                   6172: 
                   6173:    if ($thisallowed=~/C/) {
1.620     albertel 6174:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6175:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6176:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6177: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6178: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6179: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6180: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6181: 			$env{'request.course.id'});
                   6182: 	   }
1.237     www      6183:            return '';
                   6184:        }
                   6185: 
1.620     albertel 6186:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6187: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6188: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6189: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6190: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6191: 			$env{'request.course.id'});
                   6192: 	   }
1.54      www      6193:            return '';
                   6194:        }
1.53      www      6195:    }
                   6196: 
                   6197: # Resource preferences
                   6198: 
                   6199:    if ($thisallowed=~/R/) {
1.620     albertel 6200:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6201:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6202: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6203: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6204: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6205: 	   }
                   6206: 	   return '';
1.54      www      6207:        }
1.53      www      6208:    }
1.30      www      6209: 
1.246     www      6210: # Restricted by state or randomout?
1.30      www      6211: 
1.52      www      6212:    if ($thisallowed=~/X/) {
1.620     albertel 6213:       if ($env{'acc.randomout'}) {
1.579     albertel 6214: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6215:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6216:             return ''; 
                   6217:          }
1.247     www      6218:       }
                   6219:       if (&condval($statecond)) {
1.52      www      6220: 	 return '2';
                   6221:       } else {
                   6222:          return '';
                   6223:       }
                   6224:    }
1.30      www      6225: 
1.766     albertel 6226:     if ($thisallowed eq 'A') {
                   6227: 	return 'A';
1.814     raeburn  6228:     } elsif ($thisallowed eq 'B') {
                   6229:         return 'B';
1.766     albertel 6230:     }
1.52      www      6231:    return 'F';
1.232     www      6232: }
1.1133    foxr     6233: #
                   6234: #   Removes the versino from a URI and
                   6235: #   splits it in to its filename and path to the filename.
                   6236: #   Seems like File::Basename could have done this more clearly.
                   6237: #   Parameters:
                   6238: #      $uri   - input URI
                   6239: #   Returns:
                   6240: #     Two element list consisting of 
                   6241: #     $pathname  - the URI up to and excluding the trailing /
                   6242: #     $filename  - The part of the URI following the last /
                   6243: #  NOTE:
                   6244: #    Another realization of this is simply:
                   6245: #    use File::Basename;
                   6246: #    ...
                   6247: #    $uri = shift;
                   6248: #    $filename = basename($uri);
                   6249: #    $path     = dirname($uri);
                   6250: #    return ($filename, $path);
                   6251: #
                   6252: #     The implementation below is probably faster however.
                   6253: #
1.710     albertel 6254: sub split_uri_for_cond {
                   6255:     my $uri=&deversion(&declutter(shift));
                   6256:     my @uriparts=split(/\//,$uri);
                   6257:     my $filename=pop(@uriparts);
                   6258:     my $pathname=join('/',@uriparts);
                   6259:     return ($pathname,$filename);
                   6260: }
1.232     www      6261: # --------------------------------------------------- Is a resource on the map?
                   6262: 
                   6263: sub is_on_map {
1.710     albertel 6264:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 6265:     #Trying to find the conditional for the file
1.620     albertel 6266:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 6267: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      6268:     if ($match) {
1.289     bowersj2 6269: 	return (1,$1);
                   6270:     } else {
1.434     www      6271: 	return (0,0);
1.289     bowersj2 6272:     }
1.12      www      6273: }
                   6274: 
1.427     www      6275: # --------------------------------------------------------- Get symb from alias
                   6276: 
                   6277: sub get_symb_from_alias {
                   6278:     my $symb=shift;
                   6279:     my ($map,$resid,$url)=&decode_symb($symb);
                   6280: # Already is a symb
                   6281:     if ($url) { return $symb; }
                   6282: # Must be an alias
                   6283:     my $aliassymb='';
                   6284:     my %bighash;
1.620     albertel 6285:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      6286:                             &GDBM_READER(),0640)) {
                   6287:         my $rid=$bighash{'mapalias_'.$symb};
                   6288: 	if ($rid) {
                   6289: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 6290: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   6291: 				    $resid,$bighash{'src_'.$rid});
1.427     www      6292: 	}
                   6293:         untie %bighash;
                   6294:     }
                   6295:     return $aliassymb;
                   6296: }
                   6297: 
1.12      www      6298: # ----------------------------------------------------------------- Define Role
                   6299: 
                   6300: sub definerole {
                   6301:   if (allowed('mcr','/')) {
                   6302:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 6303:     foreach my $role (split(':',$sysrole)) {
                   6304: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6305:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   6306:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   6307: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6308:                return "refused:s:$crole&$cqual"; 
                   6309:             }
                   6310:         }
1.191     harris41 6311:     }
1.800     albertel 6312:     foreach my $role (split(':',$domrole)) {
                   6313: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6314:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   6315:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   6316: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      6317:                return "refused:d:$crole&$cqual"; 
                   6318:             }
                   6319:         }
1.191     harris41 6320:     }
1.800     albertel 6321:     foreach my $role (split(':',$courole)) {
                   6322: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6323:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   6324:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   6325: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6326:                return "refused:c:$crole&$cqual"; 
                   6327:             }
                   6328:         }
1.191     harris41 6329:     }
1.620     albertel 6330:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   6331:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6332: 	        "rolesdef_$rolename=".
                   6333:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 6334:     return reply($command,$env{'user.home'});
1.12      www      6335:   } else {
                   6336:     return 'refused';
                   6337:   }
1.105     harris41 6338: }
                   6339: 
                   6340: # ---------------- Make a metadata query against the network of library servers
                   6341: 
                   6342: sub metadata_query {
1.244     matthew  6343:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 6344:     my %rhash;
1.845     albertel 6345:     my %libserv = &all_library();
1.244     matthew  6346:     my @server_list = (defined($server_array) ? @$server_array
                   6347:                                               : keys(%libserv) );
                   6348:     for my $server (@server_list) {
1.118     harris41 6349: 	unless ($custom or $customshow) {
                   6350: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   6351: 	    $rhash{$server}=$reply;
                   6352: 	}
                   6353: 	else {
                   6354: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   6355: 			     &escape($custom).':'.&escape($customshow),
                   6356: 			     $server);
                   6357: 	    $rhash{$server}=$reply;
                   6358: 	}
1.112     harris41 6359:     }
1.118     harris41 6360:     return \%rhash;
1.240     www      6361: }
                   6362: 
                   6363: # ----------------------------------------- Send log queries and wait for reply
                   6364: 
                   6365: sub log_query {
                   6366:     my ($uname,$udom,$query,%filters)=@_;
                   6367:     my $uhome=&homeserver($uname,$udom);
                   6368:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 6369:     my $uhost=&hostname($uhome);
1.800     albertel 6370:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      6371:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   6372:                        $uhome);
1.479     albertel 6373:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      6374:     return get_query_reply($queryid);
                   6375: }
                   6376: 
1.818     raeburn  6377: # -------------------------- Update MySQL table for portfolio file
                   6378: 
                   6379: sub update_portfolio_table {
1.821     raeburn  6380:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  6381:     if ($group ne '') {
                   6382:         $file_name =~s /^\Q$group\E//;
                   6383:     }
1.818     raeburn  6384:     my $homeserver = &homeserver($uname,$udom);
                   6385:     my $queryid=
1.821     raeburn  6386:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   6387:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  6388:     my $reply = &get_query_reply($queryid);
                   6389:     return $reply;
                   6390: }
                   6391: 
1.899     raeburn  6392: # -------------------------- Update MySQL allusers table
                   6393: 
                   6394: sub update_allusers_table {
                   6395:     my ($uname,$udom,$names) = @_;
                   6396:     my $homeserver = &homeserver($uname,$udom);
                   6397:     my $queryid=
                   6398:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   6399:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   6400:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   6401:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   6402:                'generation='.&escape($names->{'generation'}).'%%'.
                   6403:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   6404:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  6405:     return;
1.899     raeburn  6406: }
                   6407: 
1.508     raeburn  6408: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  6409: 
                   6410: sub fetch_enrollment_query {
1.511     raeburn  6411:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  6412:     my $homeserver;
1.547     raeburn  6413:     my $maxtries = 1;
1.508     raeburn  6414:     if ($context eq 'automated') {
                   6415:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  6416:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  6417:     } else {
                   6418:         $homeserver = &homeserver($cnum,$dom);
                   6419:     }
1.838     albertel 6420:     my $host=&hostname($homeserver);
1.506     raeburn  6421:     my $cmd = '';
1.1000    raeburn  6422:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 6423:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  6424:     }
                   6425:     $cmd =~ s/%%$//;
                   6426:     $cmd = &escape($cmd);
                   6427:     my $query = 'fetchenrollment';
1.620     albertel 6428:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  6429:     unless ($queryid=~/^\Q$host\E\_/) { 
                   6430:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   6431:         return 'error: '.$queryid;
                   6432:     }
1.506     raeburn  6433:     my $reply = &get_query_reply($queryid);
1.547     raeburn  6434:     my $tries = 1;
                   6435:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6436:         $reply = &get_query_reply($queryid);
                   6437:         $tries ++;
                   6438:     }
1.526     raeburn  6439:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 6440:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  6441:     } else {
1.901     albertel 6442:         my @responses = split(/:/,$reply);
1.515     raeburn  6443:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 6444:             foreach my $line (@responses) {
                   6445:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  6446:                 $$replyref{$key} = $value;
                   6447:             }
                   6448:         } else {
1.1117    foxr     6449:             my $pathname = LONCAPA::tempdir();
1.800     albertel 6450:             foreach my $line (@responses) {
                   6451:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  6452:                 $$replyref{$key} = $value;
                   6453:                 if ($value > 0) {
1.800     albertel 6454:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   6455:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  6456:                         my $destname = $pathname.'/'.$filename;
                   6457:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  6458:                         if ($xml_classlist =~ /^error/) {
                   6459:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   6460:                         } else {
1.506     raeburn  6461:                             if ( open(FILE,">$destname") ) {
                   6462:                                 print FILE &unescape($xml_classlist);
                   6463:                                 close(FILE);
1.526     raeburn  6464:                             } else {
                   6465:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  6466:                             }
                   6467:                         }
                   6468:                     }
                   6469:                 }
                   6470:             }
                   6471:         }
                   6472:         return 'ok';
                   6473:     }
                   6474:     return 'error';
                   6475: }
                   6476: 
1.242     www      6477: sub get_query_reply {
                   6478:     my $queryid=shift;
1.1117    foxr     6479:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      6480:     my $reply='';
                   6481:     for (1..100) {
                   6482: 	sleep 2;
                   6483:         if (-e $replyfile.'.end') {
1.448     albertel 6484: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 6485: 		$reply = join('',<$fh>);
                   6486: 		close($fh);
1.240     www      6487: 	   } else { return 'error: reply_file_error'; }
1.242     www      6488:            return &unescape($reply);
                   6489: 	}
1.240     www      6490:     }
1.242     www      6491:     return 'timeout:'.$queryid;
1.240     www      6492: }
                   6493: 
                   6494: sub courselog_query {
1.241     www      6495: #
                   6496: # possible filters:
                   6497: # url: url or symb
                   6498: # username
                   6499: # domain
                   6500: # action: view, submit, grade
                   6501: # start: timestamp
                   6502: # end: timestamp
                   6503: #
1.240     www      6504:     my (%filters)=@_;
1.620     albertel 6505:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6506:     if ($filters{'url'}) {
                   6507: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6508:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6509:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6510:     }
1.620     albertel 6511:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6512:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6513:     return &log_query($cname,$cdom,'courselog',%filters);
                   6514: }
                   6515: 
                   6516: sub userlog_query {
1.858     raeburn  6517: #
                   6518: # possible filters:
                   6519: # action: log check role
                   6520: # start: timestamp
                   6521: # end: timestamp
                   6522: #
1.240     www      6523:     my ($uname,$udom,%filters)=@_;
                   6524:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6525: }
                   6526: 
1.506     raeburn  6527: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6528: 
                   6529: sub auto_run {
1.508     raeburn  6530:     my ($cnum,$cdom) = @_;
1.876     raeburn  6531:     my $response = 0;
                   6532:     my $settings;
                   6533:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6534:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6535:         $settings = $domconfig{'autoenroll'};
                   6536:         if ($settings->{'run'} eq '1') {
                   6537:             $response = 1;
                   6538:         }
                   6539:     } else {
1.934     raeburn  6540:         my $homeserver;
                   6541:         if (&is_course($cdom,$cnum)) {
                   6542:             $homeserver = &homeserver($cnum,$cdom);
                   6543:         } else {
                   6544:             $homeserver = &domain($cdom,'primary');
                   6545:         }
                   6546:         if ($homeserver ne 'no_host') {
                   6547:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6548:         }
1.876     raeburn  6549:     }
1.506     raeburn  6550:     return $response;
                   6551: }
1.776     albertel 6552: 
1.506     raeburn  6553: sub auto_get_sections {
1.508     raeburn  6554:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6555:     my $homeserver;
                   6556:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6557:         $homeserver = &homeserver($cnum,$cdom);
                   6558:     }
                   6559:     if (!defined($homeserver)) { 
                   6560:         if ($cdom =~ /^$match_domain$/) {
                   6561:             $homeserver = &domain($cdom,'primary');
                   6562:         }
                   6563:     }
                   6564:     my @secs;
                   6565:     if (defined($homeserver)) {
                   6566:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6567:         unless ($response eq 'refused') {
                   6568:             @secs = split(/:/,$response);
                   6569:         }
1.506     raeburn  6570:     }
                   6571:     return @secs;
                   6572: }
1.776     albertel 6573: 
1.506     raeburn  6574: sub auto_new_course {
1.1099    raeburn  6575:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  6576:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  6577:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  6578:     return $response;
                   6579: }
1.776     albertel 6580: 
1.506     raeburn  6581: sub auto_validate_courseID {
1.508     raeburn  6582:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6583:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6584:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6585:     return $response;
                   6586: }
1.776     albertel 6587: 
1.1007    raeburn  6588: sub auto_validate_instcode {
1.1020    raeburn  6589:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6590:     my ($homeserver,$response);
                   6591:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6592:         $homeserver = &homeserver($cnum,$cdom);
                   6593:     }
                   6594:     if (!defined($homeserver)) {
                   6595:         if ($cdom =~ /^$match_domain$/) {
                   6596:             $homeserver = &domain($cdom,'primary');
                   6597:         }
                   6598:     }
1.1065    raeburn  6599:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6600:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6601:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6602:     return ($outcome,$description);
1.1007    raeburn  6603: }
                   6604: 
1.506     raeburn  6605: sub auto_create_password {
1.873     raeburn  6606:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6607:     my ($homeserver,$response);
1.506     raeburn  6608:     my $create_passwd = 0;
                   6609:     my $authchk = '';
1.873     raeburn  6610:     if ($udom =~ /^$match_domain$/) {
                   6611:         $homeserver = &domain($udom,'primary');
                   6612:     }
                   6613:     if ($homeserver eq '') {
                   6614:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6615:             $homeserver = &homeserver($cnum,$cdom);
                   6616:         }
                   6617:     }
                   6618:     if ($homeserver eq '') {
                   6619:         $authchk = 'nodomain';
1.506     raeburn  6620:     } else {
1.873     raeburn  6621:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6622:         if ($response eq 'refused') {
                   6623:             $authchk = 'refused';
                   6624:         } else {
1.901     albertel 6625:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6626:         }
1.506     raeburn  6627:     }
                   6628:     return ($authparam,$create_passwd,$authchk);
                   6629: }
                   6630: 
1.706     raeburn  6631: sub auto_photo_permission {
                   6632:     my ($cnum,$cdom,$students) = @_;
                   6633:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6634:     my ($outcome,$perm_reqd,$conditions) = 
                   6635: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6636:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6637: 	return (undef,undef);
                   6638:     }
1.706     raeburn  6639:     return ($outcome,$perm_reqd,$conditions);
                   6640: }
                   6641: 
                   6642: sub auto_checkphotos {
                   6643:     my ($uname,$udom,$pid) = @_;
                   6644:     my $homeserver = &homeserver($uname,$udom);
                   6645:     my ($result,$resulttype);
                   6646:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6647: 				   &escape($uname).':'.&escape($pid),
                   6648: 				   $homeserver));
1.709     albertel 6649:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6650: 	return (undef,undef);
                   6651:     }
1.706     raeburn  6652:     if ($outcome) {
                   6653:         ($result,$resulttype) = split(/:/,$outcome);
                   6654:     } 
                   6655:     return ($result,$resulttype);
                   6656: }
                   6657: 
                   6658: sub auto_photochoice {
                   6659:     my ($cnum,$cdom) = @_;
                   6660:     my $homeserver = &homeserver($cnum,$cdom);
                   6661:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6662: 						       &escape($cdom),
                   6663: 						       $homeserver)));
1.709     albertel 6664:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6665: 	return (undef,undef);
                   6666:     }
1.706     raeburn  6667:     return ($update,$comment);
                   6668: }
                   6669: 
                   6670: sub auto_photoupdate {
                   6671:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6672:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6673:     my $host=&hostname($homeserver);
1.706     raeburn  6674:     my $cmd = '';
                   6675:     my $maxtries = 1;
1.800     albertel 6676:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6677:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6678:     }
                   6679:     $cmd =~ s/%%$//;
                   6680:     $cmd = &escape($cmd);
                   6681:     my $query = 'institutionalphotos';
                   6682:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   6683:     unless ($queryid=~/^\Q$host\E\_/) {
                   6684:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   6685:         return 'error: '.$queryid;
                   6686:     }
                   6687:     my $reply = &get_query_reply($queryid);
                   6688:     my $tries = 1;
                   6689:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6690:         $reply = &get_query_reply($queryid);
                   6691:         $tries ++;
                   6692:     }
                   6693:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   6694:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   6695:     } else {
                   6696:         my @responses = split(/:/,$reply);
                   6697:         my $outcome = shift(@responses); 
                   6698:         foreach my $item (@responses) {
                   6699:             my ($key,$value) = split(/=/,$item);
                   6700:             $$photo{$key} = $value;
                   6701:         }
                   6702:         return $outcome;
                   6703:     }
                   6704:     return 'error';
                   6705: }
                   6706: 
1.521     raeburn  6707: sub auto_instcode_format {
1.793     albertel 6708:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   6709: 	$cat_order) = @_;
1.521     raeburn  6710:     my $courses = '';
1.772     raeburn  6711:     my @homeservers;
1.521     raeburn  6712:     if ($caller eq 'global') {
1.841     albertel 6713: 	my %servers = &get_servers($codedom,'library');
                   6714: 	foreach my $tryserver (keys(%servers)) {
                   6715: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6716: 		push(@homeservers,$tryserver);
                   6717: 	    }
1.584     raeburn  6718:         }
1.1022    raeburn  6719:     } elsif ($caller eq 'requests') {
                   6720:         if ($codedom =~ /^$match_domain$/) {
                   6721:             my $chome = &domain($codedom,'primary');
                   6722:             unless ($chome eq 'no_host') {
                   6723:                 push(@homeservers,$chome);
                   6724:             }
                   6725:         }
1.521     raeburn  6726:     } else {
1.772     raeburn  6727:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  6728:     }
1.793     albertel 6729:     foreach my $code (keys(%{$instcodes})) {
                   6730:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  6731:     }
                   6732:     chop($courses);
1.772     raeburn  6733:     my $ok_response = 0;
                   6734:     my $response;
                   6735:     while (@homeservers > 0 && $ok_response == 0) {
                   6736:         my $server = shift(@homeservers); 
                   6737:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   6738:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   6739:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 6740: 		split(/:/,$response);
1.772     raeburn  6741:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   6742:             push(@{$codetitles},&str2array($codetitles_str));
                   6743:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   6744:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   6745:             $ok_response = 1;
                   6746:         }
                   6747:     }
                   6748:     if ($ok_response) {
1.521     raeburn  6749:         return 'ok';
1.772     raeburn  6750:     } else {
                   6751:         return $response;
1.521     raeburn  6752:     }
                   6753: }
                   6754: 
1.792     raeburn  6755: sub auto_instcode_defaults {
                   6756:     my ($domain,$returnhash,$code_order) = @_;
                   6757:     my @homeservers;
1.841     albertel 6758: 
                   6759:     my %servers = &get_servers($domain,'library');
                   6760:     foreach my $tryserver (keys(%servers)) {
                   6761: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6762: 	    push(@homeservers,$tryserver);
                   6763: 	}
1.792     raeburn  6764:     }
1.841     albertel 6765: 
1.792     raeburn  6766:     my $response;
1.841     albertel 6767:     foreach my $server (@homeservers) {
1.792     raeburn  6768:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 6769:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   6770: 	
                   6771: 	foreach my $pair (split(/\&/,$response)) {
                   6772: 	    my ($name,$value)=split(/\=/,$pair);
                   6773: 	    if ($name eq 'code_order') {
                   6774: 		@{$code_order} = split(/\&/,&unescape($value));
                   6775: 	    } else {
                   6776: 		$returnhash->{&unescape($name)}=&unescape($value);
                   6777: 	    }
                   6778: 	}
                   6779: 	return 'ok';
1.792     raeburn  6780:     }
1.841     albertel 6781: 
                   6782:     return $response;
1.1003    raeburn  6783: }
                   6784: 
                   6785: sub auto_possible_instcodes {
1.1007    raeburn  6786:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   6787:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   6788:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   6789:         return;
                   6790:     }
1.1003    raeburn  6791:     my (@homeservers,$uhome);
                   6792:     if (defined(&domain($domain,'primary'))) {
                   6793:         $uhome=&domain($domain,'primary');
                   6794:         push(@homeservers,&domain($domain,'primary'));
                   6795:     } else {
                   6796:         my %servers = &get_servers($domain,'library');
                   6797:         foreach my $tryserver (keys(%servers)) {
                   6798:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6799:                 push(@homeservers,$tryserver);
                   6800:             }
                   6801:         }
                   6802:     }
                   6803:     my $response;
                   6804:     foreach my $server (@homeservers) {
                   6805:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   6806:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  6807:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   6808:             split(':',$response);
                   6809:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   6810:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  6811:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  6812:             my ($name,$value)=split('=',$item);
                   6813:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6814:         }
                   6815:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  6816:             my ($name,$value)=split('=',$item);
                   6817:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6818:         }
                   6819:         return 'ok';
                   6820:     }
                   6821:     return $response;
                   6822: }
1.792     raeburn  6823: 
1.1010    raeburn  6824: sub auto_courserequest_checks {
                   6825:     my ($dom) = @_;
1.1020    raeburn  6826:     my ($homeserver,%validations);
                   6827:     if ($dom =~ /^$match_domain$/) {
                   6828:         $homeserver = &domain($dom,'primary');
                   6829:     }
                   6830:     unless ($homeserver eq 'no_host') {
                   6831:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   6832:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   6833:             my @items = split(/&/,$response);
                   6834:             foreach my $item (@items) {
                   6835:                 my ($key,$value) = split('=',$item);
                   6836:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   6837:             }
                   6838:         }
                   6839:     }
1.1010    raeburn  6840:     return %validations; 
                   6841: }
                   6842: 
1.1020    raeburn  6843: sub auto_courserequest_validation {
                   6844:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   6845:     my ($homeserver,$response);
                   6846:     if ($dom =~ /^$match_domain$/) {
                   6847:         $homeserver = &domain($dom,'primary');
                   6848:     }
                   6849:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  6850:           
1.1020    raeburn  6851:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  6852:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  6853:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   6854:                                     $homeserver));
                   6855:     }
                   6856:     return $response;
                   6857: }
                   6858: 
1.777     albertel 6859: sub auto_validate_class_sec {
1.918     raeburn  6860:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  6861:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  6862:     my $ownerlist;
                   6863:     if (ref($owners) eq 'ARRAY') {
                   6864:         $ownerlist = join(',',@{$owners});
                   6865:     } else {
                   6866:         $ownerlist = $owners;
                   6867:     }
1.773     raeburn  6868:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  6869:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  6870:     return $response;
                   6871: }
                   6872: 
1.679     raeburn  6873: # ------------------------------------------------------- Course Group routines
                   6874: 
                   6875: sub get_coursegroups {
1.809     raeburn  6876:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6877:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6878: }
                   6879: 
1.679     raeburn  6880: sub modify_coursegroup {
                   6881:     my ($cdom,$cnum,$groupsettings) = @_;
                   6882:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6883: }
                   6884: 
1.809     raeburn  6885: sub toggle_coursegroup_status {
                   6886:     my ($cdom,$cnum,$group,$action) = @_;
                   6887:     my ($from_namespace,$to_namespace);
                   6888:     if ($action eq 'delete') {
                   6889:         $from_namespace = 'coursegroups';
                   6890:         $to_namespace = 'deleted_groups';
                   6891:     } else {
                   6892:         $from_namespace = 'deleted_groups';
                   6893:         $to_namespace = 'coursegroups';
                   6894:     }
                   6895:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6896:     if (my $tmp = &error(%curr_group)) {
                   6897:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6898:         return ('read error',$tmp);
                   6899:     } else {
                   6900:         my %savedsettings = %curr_group; 
1.809     raeburn  6901:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6902:         my $deloutcome;
                   6903:         if ($result eq 'ok') {
1.809     raeburn  6904:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6905:         } else {
                   6906:             return ('write error',$result);
                   6907:         }
                   6908:         if ($deloutcome eq 'ok') {
                   6909:             return 'ok';
                   6910:         } else {
                   6911:             return ('delete error',$deloutcome);
                   6912:         }
                   6913:     }
                   6914: }
                   6915: 
1.679     raeburn  6916: sub modify_group_roles {
1.957     raeburn  6917:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6918:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6919:     my $role = 'gr/'.&escape($userprivs);
                   6920:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6921:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6922:     if ($result eq 'ok') {
                   6923:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6924:     }
1.679     raeburn  6925:     return $result;
                   6926: }
                   6927: 
                   6928: sub modify_coursegroup_membership {
                   6929:     my ($cdom,$cnum,$membership) = @_;
                   6930:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6931:     return $result;
                   6932: }
                   6933: 
1.682     raeburn  6934: sub get_active_groups {
                   6935:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6936:     my $now = time;
                   6937:     my %groups = ();
                   6938:     foreach my $key (keys(%env)) {
1.811     albertel 6939:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6940:             my ($start,$end) = split(/\./,$env{$key});
                   6941:             if (($end!=0) && ($end<$now)) { next; }
                   6942:             if (($start!=0) && ($start>$now)) { next; }
                   6943:             if ($1 eq $cdom && $2 eq $cnum) {
                   6944:                 $groups{$3} = $env{$key} ;
                   6945:             }
                   6946:         }
                   6947:     }
                   6948:     return %groups;
                   6949: }
                   6950: 
1.683     raeburn  6951: sub get_group_membership {
                   6952:     my ($cdom,$cnum,$group) = @_;
                   6953:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6954: }
                   6955: 
                   6956: sub get_users_groups {
                   6957:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6958:     my @usersgroups;
1.683     raeburn  6959:     my $cachetime=1800;
                   6960: 
                   6961:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6962:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6963:     if (defined($cached)) {
1.734     albertel 6964:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6965:     } else {  
                   6966:         $grouplist = '';
1.816     raeburn  6967:         my $courseurl = &courseid_to_courseurl($courseid);
1.1086    raeburn  6968:         my $extra = &freeze_escape({'skipcheck' => 1});
                   6969:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817     raeburn  6970:         my $access_end = $env{'course.'.$courseid.
                   6971:                               '.default_enrollment_end_date'};
                   6972:         my $now = time;
                   6973:         foreach my $key (keys(%roleshash)) {
                   6974:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6975:                 my $group = $1;
                   6976:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6977:                     my $start = $2;
                   6978:                     my $end = $1;
                   6979:                     if ($start == -1) { next; } # deleted from group
                   6980:                     if (($start!=0) && ($start>$now)) { next; }
                   6981:                     if (($end!=0) && ($end<$now)) {
                   6982:                         if ($access_end && $access_end < $now) {
                   6983:                             if ($access_end - $end < 86400) {
                   6984:                                 push(@usersgroups,$group);
1.733     raeburn  6985:                             }
                   6986:                         }
1.817     raeburn  6987:                         next;
1.733     raeburn  6988:                     }
1.817     raeburn  6989:                     push(@usersgroups,$group);
1.683     raeburn  6990:                 }
                   6991:             }
                   6992:         }
1.817     raeburn  6993:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6994:         $grouplist = join(':',@usersgroups);
                   6995:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6996:     }
1.733     raeburn  6997:     return @usersgroups;
1.683     raeburn  6998: }
                   6999: 
                   7000: sub devalidate_getgroups_cache {
                   7001:     my ($udom,$uname,$cdom,$cnum)=@_;
                   7002:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 7003: 
1.683     raeburn  7004:     my $hashid="$udom:$uname:$courseid";
                   7005:     &devalidate_cache_new('getgroups',$hashid);
                   7006: }
                   7007: 
1.12      www      7008: # ------------------------------------------------------------------ Plain Text
                   7009: 
                   7010: sub plaintext {
1.988     raeburn  7011:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  7012:     if ($short =~ m{^cr/}) {
1.758     albertel 7013: 	return (split('/',$short))[-1];
                   7014:     }
1.742     raeburn  7015:     if (!defined($cid)) {
                   7016:         $cid = $env{'request.course.id'};
                   7017:     }
                   7018:     my %rolenames = (
1.1008    raeburn  7019:                       Course    => 'std',
                   7020:                       Community => 'alt1',
1.742     raeburn  7021:                     );
1.1037    raeburn  7022:     if ($cid ne '') {
                   7023:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   7024:             unless ($forcedefault) {
                   7025:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   7026:                 &Apache::lonlocal::mt_escape(\$roletext);
                   7027:                 return &Apache::lonlocal::mt($roletext);
                   7028:             }
                   7029:         }
                   7030:     }
                   7031:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   7032:         (defined($rolenames{$type})) && 
                   7033:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  7034:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  7035:     } elsif ($cid ne '') {
                   7036:         my $crstype = $env{'course.'.$cid.'.type'};
                   7037:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   7038:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   7039:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   7040:         }
1.742     raeburn  7041:     }
1.1037    raeburn  7042:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      7043: }
                   7044: 
                   7045: # ----------------------------------------------------------------- Assign Role
                   7046: 
                   7047: sub assignrole {
1.957     raeburn  7048:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   7049:         $context)=@_;
1.21      www      7050:     my $mrole;
                   7051:     if ($role =~ /^cr\//) {
1.393     www      7052:         my $cwosec=$url;
1.811     albertel 7053:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      7054: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  7055:            my $refused = 1;
                   7056:            if ($context eq 'requestcourses') {
                   7057:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7058:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   7059:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   7060:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7061:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7062:                            if ($crsenv{'internal.courseowner'} eq
                   7063:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   7064:                                $refused = '';
                   7065:                            }
                   7066:                        }
                   7067:                    }
                   7068:                }
                   7069:            }
                   7070:            if ($refused) {
                   7071:                &logthis('Refused custom assignrole: '.
                   7072:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   7073:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   7074:                return 'refused';
                   7075:            }
1.104     www      7076:         }
1.21      www      7077:         $mrole='cr';
1.678     raeburn  7078:     } elsif ($role =~ /^gr\//) {
                   7079:         my $cwogrp=$url;
1.811     albertel 7080:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  7081:         unless (&allowed('mdg',$cwogrp)) {
                   7082:             &logthis('Refused group assignrole: '.
                   7083:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   7084:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   7085:             return 'refused';
                   7086:         }
                   7087:         $mrole='gr';
1.21      www      7088:     } else {
1.82      www      7089:         my $cwosec=$url;
1.811     albertel 7090:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  7091:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   7092:             my $refused;
                   7093:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   7094:                 if (!(&allowed('c'.$role,$url))) {
                   7095:                     $refused = 1;
                   7096:                 }
                   7097:             } else {
                   7098:                 $refused = 1;
                   7099:             }
1.947     raeburn  7100:             if ($refused) {
1.1045    raeburn  7101:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7102:                 if (!$selfenroll && $context eq 'course') {
                   7103:                     my %crsenv;
                   7104:                     if ($role eq 'cc' || $role eq 'co') {
                   7105:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7106:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   7107:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   7108:                                 if ($crsenv{'internal.courseowner'} eq 
                   7109:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7110:                                     $refused = '';
                   7111:                                 }
                   7112:                             }
                   7113:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   7114:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   7115:                                 if ($crsenv{'internal.courseowner'} eq 
                   7116:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7117:                                     $refused = '';
                   7118:                                 }
                   7119:                             }
                   7120:                         }
                   7121:                     }
                   7122:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  7123:                     $refused = '';
1.1017    raeburn  7124:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  7125:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  7126:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  7127:                         my $wrongcc;
                   7128:                         if ($cnum =~ /^$match_community$/) {
                   7129:                             $wrongcc = 1 if ($role eq 'cc');
                   7130:                         } else {
                   7131:                             $wrongcc = 1 if ($role eq 'co');
                   7132:                         }
                   7133:                         unless ($wrongcc) {
                   7134:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7135:                             if ($crsenv{'internal.courseowner'} eq 
                   7136:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   7137:                                 $refused = '';
                   7138:                             }
1.1017    raeburn  7139:                         }
                   7140:                     }
                   7141:                 }
                   7142:                 if ($refused) {
1.947     raeburn  7143:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   7144:                              ' '.$role.' '.$end.' '.$start.' by '.
                   7145: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   7146:                     return 'refused';
                   7147:                 }
1.932     raeburn  7148:             }
1.1131    raeburn  7149:         } elsif ($role eq 'au') {
                   7150:             if ($url ne '/'.$udom.'/') {
                   7151:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   7152:                          ' to assign author role for '.$uname.':'.$udom.
                   7153:                          ' in domain: '.$url.' refused (wrong domain).');
                   7154:                 return 'refused';
                   7155:             }
1.104     www      7156:         }
1.21      www      7157:         $mrole=$role;
                   7158:     }
1.620     albertel 7159:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7160:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      7161:     if ($end) { $command.='_'.$end; }
1.21      www      7162:     if ($start) {
                   7163: 	if ($end) { 
1.81      www      7164:            $command.='_'.$start; 
1.21      www      7165:         } else {
1.81      www      7166:            $command.='_0_'.$start;
1.21      www      7167:         }
                   7168:     }
1.739     raeburn  7169:     my $origstart = $start;
                   7170:     my $origend = $end;
1.957     raeburn  7171:     my $delflag;
1.357     www      7172: # actually delete
                   7173:     if ($deleteflag) {
1.373     www      7174: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      7175: # modify command to delete the role
1.620     albertel 7176:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      7177:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 7178: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      7179: # set start and finish to negative values for userrolelog
                   7180:            $start=-1;
                   7181:            $end=-1;
1.957     raeburn  7182:            $delflag = 1;
1.357     www      7183:         }
                   7184:     }
                   7185: # send command
1.349     www      7186:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      7187: # log new user role if status is ok
1.349     www      7188:     if ($answer eq 'ok') {
1.663     raeburn  7189: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  7190: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  7191:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  7192:         unless ($role =~ /^gr/) {
                   7193:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  7194:                                              $origstart,$selfenroll,$context);
1.739     raeburn  7195:         }
1.1053    raeburn  7196:         if ($role eq 'cc') {
                   7197:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   7198:         }
1.349     www      7199:     }
                   7200:     return $answer;
1.169     harris41 7201: }
                   7202: 
1.1053    raeburn  7203: sub autoupdate_coowners {
                   7204:     my ($url,$end,$start,$uname,$udom) = @_;
                   7205:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   7206:     if (($cdom ne '') && ($cnum ne '')) {
                   7207:         my $now = time;
                   7208:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   7209:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   7210:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   7211:             my $instcode = $coursehash{'internal.coursecode'};
                   7212:             if ($instcode ne '') {
1.1056    raeburn  7213:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   7214:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  7215:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  7216:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   7217:                         if ($result eq 'valid') {
                   7218:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  7219:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7220:                                     push(@newcoowners,$coowner);
                   7221:                                 }
                   7222:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   7223:                                     push(@newcoowners,$uname.':'.$udom);
                   7224:                                 }
                   7225:                                 @newcoowners = sort(@newcoowners);
                   7226:                             } else {
                   7227:                                 push(@newcoowners,$uname.':'.$udom);
                   7228:                             }
                   7229:                         } else {
                   7230:                             if ($coursehash{'internal.co-owners'}) {
                   7231:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7232:                                     unless ($coowner eq $uname.':'.$udom) {
                   7233:                                         push(@newcoowners,$coowner);
                   7234:                                     }
                   7235:                                 }
                   7236:                                 unless (@newcoowners > 0) {
                   7237:                                     $delcoowners = 1;
                   7238:                                     $coowners = '';
                   7239:                                 }
                   7240:                             }
                   7241:                         }
                   7242:                         if (@newcoowners || $delcoowners) {
                   7243:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   7244:                                             $delcoowners,@newcoowners);
                   7245:                         }
                   7246:                     }
                   7247:                 }
                   7248:             }
                   7249:         }
                   7250:     }
                   7251: }
                   7252: 
                   7253: sub store_coowners {
                   7254:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   7255:     my $cid = $cdom.'_'.$cnum;
                   7256:     my ($coowners,$delresult,$putresult);
                   7257:     if (@newcoowners) {
                   7258:         $coowners = join(',',@newcoowners);
                   7259:         my %coownershash = (
                   7260:                             'internal.co-owners' => $coowners,
                   7261:                            );
                   7262:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   7263:         if ($putresult eq 'ok') {
                   7264:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   7265:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   7266:             }
                   7267:         }
                   7268:     }
                   7269:     if ($delcoowners) {
                   7270:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   7271:         if ($delresult eq 'ok') {
                   7272:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   7273:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   7274:             }
                   7275:         }
                   7276:     }
                   7277:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   7278:         my %crsinfo =
                   7279:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   7280:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   7281:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   7282:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   7283:         }
                   7284:     }
                   7285: }
                   7286: 
1.169     harris41 7287: # -------------------------------------------------- Modify user authentication
1.197     www      7288: # Overrides without validation
                   7289: 
1.169     harris41 7290: sub modifyuserauth {
                   7291:     my ($udom,$uname,$umode,$upass)=@_;
                   7292:     my $uhome=&homeserver($uname,$udom);
1.197     www      7293:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   7294:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 7295:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7296:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 7297:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   7298: 		     &escape($upass),$uhome);
1.620     albertel 7299:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      7300:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   7301:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   7302:     &log($udom,,$uname,$uhome,
1.620     albertel 7303:         'Authentication changed by '.$env{'user.domain'}.', '.
                   7304:                                      $env{'user.name'}.', '.$umode.
1.197     www      7305:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 7306:     unless ($reply eq 'ok') {
1.197     www      7307:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 7308: 	return 'error: '.$reply;
                   7309:     }   
1.170     harris41 7310:     return 'ok';
1.80      www      7311: }
                   7312: 
1.81      www      7313: # --------------------------------------------------------------- Modify a user
1.80      www      7314: 
1.81      www      7315: sub modifyuser {
1.206     matthew  7316:     my ($udom,    $uname, $uid,
                   7317:         $umode,   $upass, $first,
                   7318:         $middle,  $last,  $gene,
1.1058    raeburn  7319:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 7320:     $udom= &LONCAPA::clean_domain($udom);
                   7321:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  7322:     my $showcandelete = 'none';
                   7323:     if (ref($candelete) eq 'ARRAY') {
                   7324:         if (@{$candelete} > 0) {
                   7325:             $showcandelete = join(', ',@{$candelete});
                   7326:         }
                   7327:     }
1.81      www      7328:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      7329:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  7330: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  7331:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   7332:                                      ' desiredhome not specified'). 
1.620     albertel 7333:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7334:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 7335:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  7336:     my $newuser;
                   7337:     if ($uhome eq 'no_host') {
                   7338:         $newuser = 1;
                   7339:     }
1.80      www      7340: # ----------------------------------------------------------------- Create User
1.406     albertel 7341:     if (($uhome eq 'no_host') && 
                   7342: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      7343:         my $unhome='';
1.844     albertel 7344:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  7345:             $unhome = $desiredhome;
1.620     albertel 7346: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   7347: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  7348:         } else { # load balancing routine for determining $unhome
1.81      www      7349:             my $loadm=10000000;
1.841     albertel 7350: 	    my %servers = &get_servers($udom,'library');
                   7351: 	    foreach my $tryserver (keys(%servers)) {
                   7352: 		my $answer=reply('load',$tryserver);
                   7353: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   7354: 		    $loadm=$answer;
                   7355: 		    $unhome=$tryserver;
                   7356: 		}
1.80      www      7357: 	    }
                   7358:         }
                   7359:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  7360: 	    return 'error: unable to find a home server for '.$uname.
                   7361:                    ' in domain '.$udom;
1.80      www      7362:         }
                   7363:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   7364:                          &escape($upass),$unhome);
                   7365: 	unless ($reply eq 'ok') {
                   7366:             return 'error: '.$reply;
                   7367:         }   
1.230     stredwic 7368:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      7369:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  7370: 	    return 'error: unable verify users home machine.';
1.80      www      7371:         }
1.209     matthew  7372:     }   # End of creation of new user
1.80      www      7373: # ---------------------------------------------------------------------- Add ID
                   7374:     if ($uid) {
                   7375:        $uid=~tr/A-Z/a-z/;
                   7376:        my %uidhash=&idrget($udom,$uname);
1.196     www      7377:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   7378:          && (!$forceid)) {
1.80      www      7379: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  7380: 	      return 'error: user id "'.$uid.'" does not match '.
                   7381:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      7382:           }
                   7383:        } else {
                   7384: 	  &idput($udom,($uname => $uid));
                   7385:        }
                   7386:     }
                   7387: # -------------------------------------------------------------- Add names, etc
1.313     matthew  7388:     my @tmp=&get('environment',
1.899     raeburn  7389: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  7390:                     'permanentemail','inststatus'],
1.134     albertel 7391: 		   $udom,$uname);
1.1075    raeburn  7392:     my (%names,%oldnames);
1.313     matthew  7393:     if ($tmp[0] =~ m/^error:.*/) { 
                   7394:         %names=(); 
                   7395:     } else {
                   7396:         %names = @tmp;
1.1075    raeburn  7397:         %oldnames = %names;
1.313     matthew  7398:     }
1.388     www      7399: #
1.1058    raeburn  7400: # If name, email and/or uid are blank (e.g., because an uploaded file
                   7401: # of users did not contain them), do not overwrite existing values
                   7402: # unless field is in $candelete array ref.  
                   7403: #
                   7404: 
                   7405:     my @fields = ('firstname','middlename','lastname','generation',
                   7406:                   'permanentemail','id');
                   7407:     my %newvalues;
                   7408:     if (ref($candelete) eq 'ARRAY') {
                   7409:         foreach my $field (@fields) {
                   7410:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   7411:                 if ($field eq 'firstname') {
                   7412:                     $names{$field} = $first;
                   7413:                 } elsif ($field eq 'middlename') {
                   7414:                     $names{$field} = $middle;
                   7415:                 } elsif ($field eq 'lastname') {
                   7416:                     $names{$field} = $last;
                   7417:                 } elsif ($field eq 'generation') { 
                   7418:                     $names{$field} = $gene;
                   7419:                 } elsif ($field eq 'permanentemail') {
                   7420:                     $names{$field} = $email;
                   7421:                 } elsif ($field eq 'id') {
                   7422:                     $names{$field}  = $uid;
                   7423:                 }
                   7424:             }
                   7425:         }
                   7426:     }
1.388     www      7427:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  7428:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      7429:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  7430:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      7431:     if ($email) {
                   7432:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  7433:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      7434:     }
1.899     raeburn  7435:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  7436:     if (defined($inststatus)) {
                   7437:         $names{'inststatus'} = '';
                   7438:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   7439:         if (ref($usertypes) eq 'HASH') {
                   7440:             my @okstatuses; 
                   7441:             foreach my $item (split(/:/,$inststatus)) {
                   7442:                 if (defined($usertypes->{$item})) {
                   7443:                     push(@okstatuses,$item);  
                   7444:                 }
                   7445:             }
                   7446:             if (@okstatuses) {
                   7447:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   7448:             }
                   7449:         }
                   7450:     }
1.1075    raeburn  7451:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  7452:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  7453:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  7454:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   7455:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   7456:     } else {
                   7457:         $logmsg .= ' during self creation';
                   7458:     }
1.1075    raeburn  7459:     my $changed;
                   7460:     if ($newuser) {
                   7461:         $changed = 1;
                   7462:     } else {
                   7463:         foreach my $field (@fields) {
                   7464:             if ($names{$field} ne $oldnames{$field}) {
                   7465:                 $changed = 1;
                   7466:                 last;
                   7467:             }
                   7468:         }
                   7469:     }
                   7470:     unless ($changed) {
                   7471:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   7472:         &logthis($logmsg);
                   7473:         return 'ok';
                   7474:     }
                   7475:     my $reply = &put('environment', \%names, $udom,$uname);
                   7476:     if ($reply ne 'ok') { 
                   7477:         return 'error: '.$reply;
                   7478:     }
1.1087    raeburn  7479:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   7480:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   7481:     }
1.1075    raeburn  7482:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   7483:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   7484:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  7485:     &logthis($logmsg);
1.134     albertel 7486:     return 'ok';
1.80      www      7487: }
                   7488: 
1.81      www      7489: # -------------------------------------------------------------- Modify student
1.80      www      7490: 
1.81      www      7491: sub modifystudent {
                   7492:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  7493:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  7494:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 7495:     if (!$cid) {
1.620     albertel 7496: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7497: 	    return 'not_in_class';
                   7498: 	}
1.80      www      7499:     }
                   7500: # --------------------------------------------------------------- Make the user
1.81      www      7501:     my $reply=&modifyuser
1.209     matthew  7502: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  7503:          $desiredhome,$email,$inststatus);
1.80      www      7504:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  7505:     # This will cause &modify_student_enrollment to get the uid from the
                   7506:     # students environment
                   7507:     $uid = undef if (!$forceid);
1.455     albertel 7508:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  7509: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  7510:     return $reply;
                   7511: }
                   7512: 
                   7513: sub modify_student_enrollment {
1.957     raeburn  7514:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 7515:     my ($cdom,$cnum,$chome);
                   7516:     if (!$cid) {
1.620     albertel 7517: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7518: 	    return 'not_in_class';
                   7519: 	}
1.620     albertel 7520: 	$cdom=$env{'course.'.$cid.'.domain'};
                   7521: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 7522:     } else {
                   7523: 	($cdom,$cnum)=split(/_/,$cid);
                   7524:     }
1.620     albertel 7525:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 7526:     if (!$chome) {
1.457     raeburn  7527: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  7528:     }
1.455     albertel 7529:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  7530:     # Make sure the user exists
1.81      www      7531:     my $uhome=&homeserver($uname,$udom);
                   7532:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7533: 	return 'error: no such user';
                   7534:     }
1.297     matthew  7535:     # Get student data if we were not given enough information
                   7536:     if (!defined($first)  || $first  eq '' || 
                   7537:         !defined($last)   || $last   eq '' || 
                   7538:         !defined($uid)    || $uid    eq '' || 
                   7539:         !defined($middle) || $middle eq '' || 
                   7540:         !defined($gene)   || $gene   eq '') {
1.294     matthew  7541:         # They did not supply us with enough data to enroll the student, so
                   7542:         # we need to pick up more information.
1.297     matthew  7543:         my %tmp = &get('environment',
1.294     matthew  7544:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  7545:                        ,$udom,$uname);
                   7546: 
1.800     albertel 7547:         #foreach my $key (keys(%tmp)) {
                   7548:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 7549:         #}
1.294     matthew  7550:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   7551:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   7552:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  7553:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  7554:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   7555:     }
1.556     albertel 7556:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  7557:     my $user = "$uname:$udom";
                   7558:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 7559:     my $reply=cput('classlist',
1.1148    raeburn  7560: 		   {$user => 
1.515     raeburn  7561: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7562: 		   $cdom,$cnum);
1.1148    raeburn  7563:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7564:         &devalidate_getsection_cache($udom,$uname,$cid);
                   7565:     } else { 
1.81      www      7566: 	return 'error: '.$reply;
                   7567:     }
1.297     matthew  7568:     # Add student role to user
1.83      www      7569:     my $uurl='/'.$cid;
1.81      www      7570:     $uurl=~s/\_/\//g;
                   7571:     if ($usec) {
                   7572: 	$uurl.='/'.$usec;
                   7573:     }
1.1148    raeburn  7574:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   7575:                              $selfenroll,$context);
                   7576:     if ($result ne 'ok') {
                   7577:         if ($old_entry{$user} ne '') {
                   7578:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   7579:         } else {
                   7580:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   7581:         }
                   7582:     }
                   7583:     return $result; 
1.21      www      7584: }
                   7585: 
1.556     albertel 7586: sub format_name {
                   7587:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7588:     my $name;
                   7589:     if ($first ne 'lastname') {
                   7590: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7591:     } else {
                   7592: 	if ($lastname=~/\S/) {
                   7593: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7594: 	    $name=~s/\s+,/,/;
                   7595: 	} else {
                   7596: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7597: 	}
                   7598:     }
                   7599:     $name=~s/^\s+//;
                   7600:     $name=~s/\s+$//;
                   7601:     $name=~s/\s+/ /g;
                   7602:     return $name;
                   7603: }
                   7604: 
1.84      www      7605: # ------------------------------------------------- Write to course preferences
                   7606: 
                   7607: sub writecoursepref {
                   7608:     my ($courseid,%prefs)=@_;
                   7609:     $courseid=~s/^\///;
                   7610:     $courseid=~s/\_/\//g;
                   7611:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7612:     my $chome=homeserver($cnum,$cdomain);
                   7613:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7614: 	return 'error: no such course';
                   7615:     }
                   7616:     my $cstring='';
1.800     albertel 7617:     foreach my $pref (keys(%prefs)) {
                   7618: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7619:     }
1.84      www      7620:     $cstring=~s/\&$//;
                   7621:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7622: }
                   7623: 
                   7624: # ---------------------------------------------------------- Make/modify course
                   7625: 
                   7626: sub createcourse {
1.741     raeburn  7627:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7628:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7629:     $url=&declutter($url);
                   7630:     my $cid='';
1.1028    raeburn  7631:     if ($context eq 'requestcourses') {
                   7632:         my $can_create = 0;
                   7633:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7634:         if ($udom eq $ownerdom) {
                   7635:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7636:                                   $context)) {
                   7637:                 $can_create = 1;
                   7638:             }
                   7639:         } else {
                   7640:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7641:                                            $category);
                   7642:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7643:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7644:                 if (@curr > 0) {
                   7645:                     my @options = qw(approval validate autolimit);
                   7646:                     my $optregex = join('|',@options);
                   7647:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7648:                         $can_create = 1;
                   7649:                     }
                   7650:                 }
                   7651:             }
                   7652:         }
                   7653:         if ($can_create) {
                   7654:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7655:                 unless (&allowed('ccc',$udom)) {
                   7656:                     return 'refused'; 
                   7657:                 }
1.1017    raeburn  7658:             }
                   7659:         } else {
                   7660:             return 'refused';
                   7661:         }
1.1028    raeburn  7662:     } elsif (!&allowed('ccc',$udom)) {
                   7663:         return 'refused';
1.84      www      7664:     }
1.1011    raeburn  7665: # --------------------------------------------------------------- Get Unique ID
                   7666:     my $uname;
                   7667:     if ($cnum =~ /^$match_courseid$/) {
                   7668:         my $chome=&homeserver($cnum,$udom,'true');
                   7669:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7670:             $uname = $cnum;
                   7671:         } else {
1.1038    raeburn  7672:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7673:         }
                   7674:     } else {
1.1038    raeburn  7675:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7676:     }
                   7677:     return $uname if ($uname =~ /^error/);
                   7678: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7679:     if (!defined($course_server)) {
                   7680:         if (defined(&domain($udom,'primary'))) {
                   7681:             $course_server = &domain($udom,'primary');
                   7682:         } else {
                   7683:             $course_server = $env{'user.home'}; 
                   7684:         }
                   7685:     }
                   7686:     my %host_servers =
                   7687:         &Apache::lonnet::get_servers($udom,'library');
                   7688:     unless ($host_servers{$course_server}) {
                   7689:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  7690:     }
1.84      www      7691: # ------------------------------------------------------------- Make the course
                   7692:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  7693:                       $course_server);
1.84      www      7694:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  7695:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      7696:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7697: 	return 'error: no such course';
                   7698:     }
1.271     www      7699: # ----------------------------------------------------------------- Course made
1.516     raeburn  7700: # log existence
1.1029    raeburn  7701:     my $now = time;
1.918     raeburn  7702:     my $newcourse = {
                   7703:                     $udom.'_'.$uname => {
1.921     raeburn  7704:                                      description => $description,
                   7705:                                      inst_code   => $inst_code,
                   7706:                                      owner       => $course_owner,
                   7707:                                      type        => $crstype,
1.1029    raeburn  7708:                                      creator     => $env{'user.name'}.':'.
                   7709:                                                     $env{'user.domain'},
                   7710:                                      created     => $now,
                   7711:                                      context     => $context,
1.918     raeburn  7712:                                                 },
                   7713:                     };
1.921     raeburn  7714:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      7715: # set toplevel url
1.271     www      7716:     my $topurl=$url;
                   7717:     unless ($nonstandard) {
                   7718: # ------------------------------------------ For standard courses, make top url
                   7719:         my $mapurl=&clutter($url);
1.278     www      7720:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 7721:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      7722: <map>
                   7723: <resource id="1" type="start"></resource>
                   7724: <resource id="2" src="$mapurl"></resource>
                   7725: <resource id="3" type="finish"></resource>
                   7726: <link index="1" from="1" to="2"></link>
                   7727: <link index="2" from="2" to="3"></link>
                   7728: </map>
                   7729: ENDINITMAP
                   7730:         $topurl=&declutter(
1.638     albertel 7731:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      7732:                           );
                   7733:     }
                   7734: # ----------------------------------------------------------- Write preferences
1.84      www      7735:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  7736:                      ('description'              => $description,
                   7737:                       'url'                      => $topurl,
                   7738:                       'internal.creator'         => $env{'user.name'}.':'.
                   7739:                                                     $env{'user.domain'},
                   7740:                       'internal.created'         => $now,
                   7741:                       'internal.creationcontext' => $context)
                   7742:                     );
1.84      www      7743:     return '/'.$udom.'/'.$uname;
                   7744: }
                   7745: 
1.1011    raeburn  7746: # ------------------------------------------------------------------- Create ID
                   7747: sub generate_coursenum {
1.1038    raeburn  7748:     my ($udom,$crstype) = @_;
1.1011    raeburn  7749:     my $domdesc = &domain($udom);
                   7750:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  7751:     my $first;
                   7752:     if ($crstype eq 'Community') {
                   7753:         $first = '0';
                   7754:     } else {
                   7755:         $first = int(1+rand(9)); 
                   7756:     } 
                   7757:     my $uname=$first.
1.1011    raeburn  7758:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7759:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7760:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7761: # ----------------------------------------------- Make sure that does not exist
                   7762:     my $uhome=&homeserver($uname,$udom,'true');
                   7763:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  7764:         if ($crstype eq 'Community') {
                   7765:             $first = '0';
                   7766:         } else {
                   7767:             $first = int(1+rand(9));
                   7768:         }
                   7769:         $uname=$first.
1.1011    raeburn  7770:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7771:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7772:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7773:         $uhome=&homeserver($uname,$udom,'true');
                   7774:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   7775:             return 'error: unable to generate unique course-ID';
                   7776:         }
                   7777:     }
                   7778:     return $uname;
                   7779: }
                   7780: 
1.813     albertel 7781: sub is_course {
                   7782:     my ($cdom,$cnum) = @_;
                   7783:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  7784: 				undef,'.');
1.813     albertel 7785:     if (exists($courses{$cdom.'_'.$cnum})) {
                   7786:         return 1;
                   7787:     }
                   7788:     return 0;
                   7789: }
                   7790: 
1.1015    raeburn  7791: sub store_userdata {
                   7792:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  7793:     my $result;
1.1016    raeburn  7794:     if ($datakey ne '') {
1.1013    raeburn  7795:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  7796:             if ($udom eq '' || $uname eq '') {
                   7797:                 $udom = $env{'user.domain'};
                   7798:                 $uname = $env{'user.name'};
                   7799:             }
                   7800:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  7801:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   7802:                 $result = 'error: no_host';
                   7803:             } else {
                   7804:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   7805:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   7806: 
                   7807:                 my $namevalue='';
                   7808:                 foreach my $key (keys(%{$storehash})) {
                   7809:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7810:                 }
                   7811:                 $namevalue=~s/\&$//;
1.1105    raeburn  7812:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   7813:                                   $namevalue,$uhome);
1.1013    raeburn  7814:             }
                   7815:         } else {
                   7816:             $result = 'error: data to store was not a hash reference'; 
                   7817:         }
                   7818:     } else {
                   7819:         $result= 'error: invalid requestkey'; 
                   7820:     }
                   7821:     return $result;
                   7822: }
                   7823: 
1.21      www      7824: # ---------------------------------------------------------- Assign Custom Role
                   7825: 
                   7826: sub assigncustomrole {
1.957     raeburn  7827:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7828:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  7829:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      7830: }
                   7831: 
                   7832: # ----------------------------------------------------------------- Revoke Role
                   7833: 
                   7834: sub revokerole {
1.957     raeburn  7835:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7836:     my $now=time;
1.965     raeburn  7837:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      7838: }
                   7839: 
                   7840: # ---------------------------------------------------------- Revoke Custom Role
                   7841: 
                   7842: sub revokecustomrole {
1.957     raeburn  7843:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7844:     my $now=time;
1.357     www      7845:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  7846:            $deleteflag,$selfenroll,$context);
1.17      www      7847: }
                   7848: 
1.533     banghart 7849: # ------------------------------------------------------------ Disk usage
1.535     albertel 7850: sub diskusage {
1.955     raeburn  7851:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   7852:     $directorypath =~ s/\/$//;
                   7853:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   7854:                        .&escape($getpropath).':'.&escape($uname).':'
                   7855:                        .&escape($udom),homeserver($uname,$udom));
                   7856:     if ($listing eq 'unknown_cmd') {
                   7857:         if ($getpropath) {
                   7858:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   7859:         }
                   7860:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   7861:     }
1.514     albertel 7862:     return $listing;
1.512     banghart 7863: }
                   7864: 
1.566     banghart 7865: sub is_locked {
1.1096    raeburn  7866:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 7867:     my @check;
                   7868:     my $is_locked;
1.1093    raeburn  7869:     push (@check,$file_name);
1.613     albertel 7870:     my %locked = &get('file_permissions',\@check,
1.620     albertel 7871: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 7872:     my ($tmp)=keys(%locked);
                   7873:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  7874:     
1.566     banghart 7875:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  7876:         $is_locked = 'false';
                   7877:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  7878:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  7879:                $is_locked = 'true';
1.1096    raeburn  7880:                if (ref($which) eq 'ARRAY') {
                   7881:                    push(@{$which},$entry);
                   7882:                } else {
                   7883:                    last;
                   7884:                }
1.745     raeburn  7885:            }
                   7886:        }
1.566     banghart 7887:     } else {
                   7888:         $is_locked = 'false';
                   7889:     }
1.1093    raeburn  7890:     return $is_locked;
1.566     banghart 7891: }
                   7892: 
1.759     albertel 7893: sub declutter_portfile {
                   7894:     my ($file) = @_;
1.833     albertel 7895:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 7896:     return $file;
                   7897: }
                   7898: 
1.559     banghart 7899: # ------------------------------------------------------------- Mark as Read Only
                   7900: 
                   7901: sub mark_as_readonly {
                   7902:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 7903:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7904:     my ($tmp)=keys(%current_permissions);
                   7905:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 7906:     foreach my $file (@{$files}) {
1.759     albertel 7907: 	$file = &declutter_portfile($file);
1.561     banghart 7908:         push(@{$current_permissions{$file}},$what);
1.559     banghart 7909:     }
1.613     albertel 7910:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7911:     return;
                   7912: }
                   7913: 
1.572     banghart 7914: # ------------------------------------------------------------Save Selected Files
                   7915: 
                   7916: sub save_selected_files {
                   7917:     my ($user, $path, @files) = @_;
                   7918:     my $filename = $user."savedfiles";
1.573     banghart 7919:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 7920:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 7921:     foreach my $file (@files) {
1.620     albertel 7922:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 7923:     }
                   7924:     foreach my $file (@other_files) {
1.574     banghart 7925:         print (OUT $file."\n");
1.572     banghart 7926:     }
1.574     banghart 7927:     close (OUT);
1.572     banghart 7928:     return 'ok';
                   7929: }
                   7930: 
1.574     banghart 7931: sub clear_selected_files {
                   7932:     my ($user) = @_;
                   7933:     my $filename = $user."savedfiles";
1.1117    foxr     7934:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 7935:     print (OUT undef);
                   7936:     close (OUT);
                   7937:     return ("ok");    
                   7938: }
                   7939: 
1.572     banghart 7940: sub files_in_path {
                   7941:     my ($user, $path) = @_;
                   7942:     my $filename = $user."savedfiles";
                   7943:     my %return_files;
1.1117    foxr     7944:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 7945:     while (my $line_in = <IN>) {
1.574     banghart 7946:         chomp ($line_in);
                   7947:         my @paths_and_file = split (m!/!, $line_in);
                   7948:         my $file_part = pop (@paths_and_file);
                   7949:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 7950:         $path_part.='/';
                   7951:         my $path_and_file = $path_part.$file_part;
                   7952:         if ($path_part eq $path) {
                   7953:             $return_files{$file_part}= 'selected';
                   7954:         }
                   7955:     }
1.574     banghart 7956:     close (IN);
                   7957:     return (\%return_files);
1.572     banghart 7958: }
                   7959: 
                   7960: # called in portfolio select mode, to show files selected NOT in current directory
                   7961: sub files_not_in_path {
                   7962:     my ($user, $path) = @_;
                   7963:     my $filename = $user."savedfiles";
                   7964:     my @return_files;
                   7965:     my $path_part;
1.1117    foxr     7966:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 7967:     while (my $line = <IN>) {
1.572     banghart 7968:         #ok, I know it's clunky, but I want it to work
1.800     albertel 7969:         my @paths_and_file = split(m|/|, $line);
                   7970:         my $file_part = pop(@paths_and_file);
                   7971:         chomp($file_part);
                   7972:         my $path_part = join('/', @paths_and_file);
1.572     banghart 7973:         $path_part .= '/';
                   7974:         my $path_and_file = $path_part.$file_part;
                   7975:         if ($path_part ne $path) {
1.800     albertel 7976:             push(@return_files, ($path_and_file));
1.572     banghart 7977:         }
                   7978:     }
1.800     albertel 7979:     close(OUT);
1.574     banghart 7980:     return (@return_files);
1.572     banghart 7981: }
                   7982: 
1.745     raeburn  7983: #----------------------------------------------Get portfolio file permissions
1.629     banghart 7984: 
1.745     raeburn  7985: sub get_portfile_permissions {
                   7986:     my ($domain,$user) = @_;
1.613     albertel 7987:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7988:     my ($tmp)=keys(%current_permissions);
                   7989:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7990:     return \%current_permissions;
                   7991: }
                   7992: 
                   7993: #---------------------------------------------Get portfolio file access controls
                   7994: 
1.749     raeburn  7995: sub get_access_controls {
1.745     raeburn  7996:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 7997:     my %access;
                   7998:     my $real_file = $file;
                   7999:     $file =~ s/\.meta$//;
1.745     raeburn  8000:     if (defined($file)) {
1.749     raeburn  8001:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   8002:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 8003:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  8004:             }
                   8005:         }
1.745     raeburn  8006:     } else {
1.749     raeburn  8007:         foreach my $key (keys(%{$current_permissions})) {
                   8008:             if ($key =~ /\0accesscontrol$/) {
                   8009:                 if (defined($group)) {
                   8010:                     if ($key !~ m-^\Q$group\E/-) {
                   8011:                         next;
                   8012:                     }
                   8013:                 }
                   8014:                 my ($fullpath) = split(/\0/,$key);
                   8015:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   8016:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   8017:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   8018:                     }
                   8019:                 }
                   8020:             }
                   8021:         }
                   8022:     }
                   8023:     return %access;
                   8024: }
                   8025: 
                   8026: sub modify_access_controls {
                   8027:     my ($file_name,$changes,$domain,$user)=@_;
                   8028:     my ($outcome,$deloutcome);
                   8029:     my %store_permissions;
                   8030:     my %new_values;
                   8031:     my %new_control;
                   8032:     my %translation;
                   8033:     my @deletions = ();
                   8034:     my $now = time;
                   8035:     if (exists($$changes{'activate'})) {
                   8036:         if (ref($$changes{'activate'}) eq 'HASH') {
                   8037:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   8038:             my $numnew = scalar(@newitems);
                   8039:             for (my $i=0; $i<$numnew; $i++) {
                   8040:                 my $newkey = $newitems[$i];
                   8041:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  8042:                 if ($newkey =~ /^\d+:/) { 
                   8043:                     $newkey =~ s/^(\d+)/$newid/;
                   8044:                     $translation{$1} = $newid;
                   8045:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   8046:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   8047:                     $translation{$1} = $newid;
                   8048:                 }
1.749     raeburn  8049:                 $new_values{$file_name."\0".$newkey} = 
                   8050:                                           $$changes{'activate'}{$newitems[$i]};
                   8051:                 $new_control{$newkey} = $now;
                   8052:             }
                   8053:         }
                   8054:     }
                   8055:     my %todelete;
                   8056:     my %changed_items;
                   8057:     foreach my $action ('delete','update') {
                   8058:         if (exists($$changes{$action})) {
                   8059:             if (ref($$changes{$action}) eq 'HASH') {
                   8060:                 foreach my $key (keys(%{$$changes{$action}})) {
                   8061:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   8062:                     if ($action eq 'delete') { 
                   8063:                         $todelete{$itemnum} = 1;
                   8064:                     } else {
                   8065:                         $changed_items{$itemnum} = $key;
                   8066:                     }
                   8067:                 }
1.745     raeburn  8068:             }
                   8069:         }
1.749     raeburn  8070:     }
                   8071:     # get lock on access controls for file.
                   8072:     my $lockhash = {
                   8073:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   8074:                                                        ':'.$env{'user.domain'},
                   8075:                    }; 
                   8076:     my $tries = 0;
                   8077:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8078:    
                   8079:     while (($gotlock ne 'ok') && $tries <3) {
                   8080:         $tries ++;
                   8081:         sleep 1;
                   8082:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8083:     }
                   8084:     if ($gotlock eq 'ok') {
                   8085:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   8086:         my ($tmp)=keys(%curr_permissions);
                   8087:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   8088:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   8089:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   8090:             if (ref($curr_controls) eq 'HASH') {
                   8091:                 foreach my $control_item (keys(%{$curr_controls})) {
                   8092:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   8093:                     if (defined($todelete{$itemnum})) {
                   8094:                         push(@deletions,$file_name."\0".$control_item);
                   8095:                     } else {
                   8096:                         if (defined($changed_items{$itemnum})) {
                   8097:                             $new_control{$changed_items{$itemnum}} = $now;
                   8098:                             push(@deletions,$file_name."\0".$control_item);
                   8099:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   8100:                         } else {
                   8101:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   8102:                         }
                   8103:                     }
1.745     raeburn  8104:                 }
                   8105:             }
                   8106:         }
1.970     raeburn  8107:         my ($group);
                   8108:         if (&is_course($domain,$user)) {
                   8109:             ($group,my $file) = split(/\//,$file_name,2);
                   8110:         }
1.749     raeburn  8111:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   8112:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   8113:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   8114:         #  remove lock
                   8115:         my @del_lock = ($file_name."\0".'locked_access_records');
                   8116:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  8117:         my $sqlresult =
1.970     raeburn  8118:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  8119:                                     $group);
1.749     raeburn  8120:     } else {
                   8121:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  8122:     }
1.749     raeburn  8123:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  8124: }
                   8125: 
1.827     raeburn  8126: sub make_public_indefinitely {
                   8127:     my ($requrl) = @_;
                   8128:     my $now = time;
                   8129:     my $action = 'activate';
                   8130:     my $aclnum = 0;
                   8131:     if (&is_portfolio_url($requrl)) {
                   8132:         my (undef,$udom,$unum,$file_name,$group) =
                   8133:             &parse_portfolio_url($requrl);
                   8134:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   8135:         my %access_controls = &get_access_controls($current_perms,
                   8136:                                                    $group,$file_name);
                   8137:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   8138:             my ($num,$scope,$end,$start) = 
                   8139:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   8140:             if ($scope eq 'public') {
                   8141:                 if ($start <= $now && $end == 0) {
                   8142:                     $action = 'none';
                   8143:                 } else {
                   8144:                     $action = 'update';
                   8145:                     $aclnum = $num;
                   8146:                 }
                   8147:                 last;
                   8148:             }
                   8149:         }
                   8150:         if ($action eq 'none') {
                   8151:              return 'ok';
                   8152:         } else {
                   8153:             my %changes;
                   8154:             my $newend = 0;
                   8155:             my $newstart = $now;
                   8156:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   8157:             $changes{$action}{$newkey} = {
                   8158:                 type => 'public',
                   8159:                 time => {
                   8160:                     start => $newstart,
                   8161:                     end   => $newend,
                   8162:                 },
                   8163:             };
                   8164:             my ($outcome,$deloutcome,$new_values,$translation) =
                   8165:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   8166:             return $outcome;
                   8167:         }
                   8168:     } else {
                   8169:         return 'invalid';
                   8170:     }
                   8171: }
                   8172: 
1.745     raeburn  8173: #------------------------------------------------------Get Marked as Read Only
                   8174: 
                   8175: sub get_marked_as_readonly {
                   8176:     my ($domain,$user,$what,$group) = @_;
                   8177:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 8178:     my @readonly_files;
1.629     banghart 8179:     my $cmp1=$what;
                   8180:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  8181:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8182:         if (defined($group)) {
                   8183:             if ($file_name !~ m-^\Q$group\E/-) {
                   8184:                 next;
                   8185:             }
                   8186:         }
1.561     banghart 8187:         if (ref($value) eq "ARRAY"){
                   8188:             foreach my $stored_what (@{$value}) {
1.629     banghart 8189:                 my $cmp2=$stored_what;
1.759     albertel 8190:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  8191:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  8192:                 }
1.629     banghart 8193:                 if ($cmp1 eq $cmp2) {
1.561     banghart 8194:                     push(@readonly_files, $file_name);
1.745     raeburn  8195:                     last;
1.563     banghart 8196:                 } elsif (!defined($what)) {
                   8197:                     push(@readonly_files, $file_name);
1.745     raeburn  8198:                     last;
1.561     banghart 8199:                 }
                   8200:             }
1.745     raeburn  8201:         }
1.561     banghart 8202:     }
                   8203:     return @readonly_files;
                   8204: }
1.577     banghart 8205: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 8206: 
1.577     banghart 8207: sub get_marked_as_readonly_hash {
1.745     raeburn  8208:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 8209:     my %readonly_files;
1.745     raeburn  8210:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8211:         if (defined($group)) {
                   8212:             if ($file_name !~ m-^\Q$group\E/-) {
                   8213:                 next;
                   8214:             }
                   8215:         }
1.577     banghart 8216:         if (ref($value) eq "ARRAY"){
                   8217:             foreach my $stored_what (@{$value}) {
1.745     raeburn  8218:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 8219:                     foreach my $lock_descriptor(@{$stored_what}) {
                   8220:                         if ($lock_descriptor eq 'graded') {
                   8221:                             $readonly_files{$file_name} = 'graded';
                   8222:                         } elsif ($lock_descriptor eq 'handback') {
                   8223:                             $readonly_files{$file_name} = 'handback';
                   8224:                         } else {
                   8225:                             if (!exists($readonly_files{$file_name})) {
                   8226:                                 $readonly_files{$file_name} = 'locked';
                   8227:                             }
                   8228:                         }
1.745     raeburn  8229:                     }
1.750     banghart 8230:                 } 
1.577     banghart 8231:             }
                   8232:         } 
                   8233:     }
                   8234:     return %readonly_files;
                   8235: }
1.559     banghart 8236: # ------------------------------------------------------------ Unmark as Read Only
                   8237: 
                   8238: sub unmark_as_readonly {
1.629     banghart 8239:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   8240:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  8241:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 8242:     $file_name = &declutter_portfile($file_name);
1.634     albertel 8243:     my $symb_crs = $what;
                   8244:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  8245:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 8246:     my ($tmp)=keys(%current_permissions);
                   8247:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8248:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 8249:     foreach my $file (@readonly_files) {
1.759     albertel 8250: 	my $clean_file = &declutter_portfile($file);
                   8251: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 8252: 	my $current_locks = $current_permissions{$file};
1.563     banghart 8253:         my @new_locks;
                   8254:         my @del_keys;
                   8255:         if (ref($current_locks) eq "ARRAY"){
                   8256:             foreach my $locker (@{$current_locks}) {
1.632     albertel 8257:                 my $compare=$locker;
1.749     raeburn  8258:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  8259:                     $compare=join('',@{$locker});
1.746     raeburn  8260:                     if ($compare ne $symb_crs) {
                   8261:                         push(@new_locks, $locker);
                   8262:                     }
1.563     banghart 8263:                 }
                   8264:             }
1.650     albertel 8265:             if (scalar(@new_locks) > 0) {
1.563     banghart 8266:                 $current_permissions{$file} = \@new_locks;
                   8267:             } else {
                   8268:                 push(@del_keys, $file);
1.613     albertel 8269:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 8270:                 delete($current_permissions{$file});
1.563     banghart 8271:             }
                   8272:         }
1.561     banghart 8273:     }
1.613     albertel 8274:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8275:     return;
                   8276: }
1.512     banghart 8277: 
1.17      www      8278: # ------------------------------------------------------------ Directory lister
                   8279: 
                   8280: sub dirlist {
1.955     raeburn  8281:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      8282:     $uri=~s/^\///;
                   8283:     $uri=~s/\/$//;
1.253     stredwic 8284:     my ($udom, $uname);
1.955     raeburn  8285:     if ($getuserdir) {
1.253     stredwic 8286:         $udom = $userdomain;
                   8287:         $uname = $username;
1.955     raeburn  8288:     } else {
                   8289:         (undef,$udom,$uname)=split(/\//,$uri);
                   8290:         if(defined($userdomain)) {
                   8291:             $udom = $userdomain;
                   8292:         }
                   8293:         if(defined($username)) {
                   8294:             $uname = $username;
                   8295:         }
1.253     stredwic 8296:     }
1.955     raeburn  8297:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 8298: 
1.955     raeburn  8299:     $dirRoot = $perlvar{'lonDocRoot'};
                   8300:     if (defined($getpropath)) {
                   8301:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 8302:         $dirRoot =~ s/\/$//;
1.955     raeburn  8303:     } elsif (defined($getuserdir)) {
                   8304:         my $subdir=$uname.'__';
                   8305:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   8306:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   8307:                    ."/$udom/$subdir/$uname";
                   8308:     } elsif (defined($alternateRoot)) {
                   8309:         $dirRoot = $alternateRoot;
1.751     banghart 8310:     }
1.253     stredwic 8311: 
                   8312:     if($udom) {
                   8313:         if($uname) {
1.1135    raeburn  8314:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  8315:             if ($uhome eq 'no_host') {
                   8316:                 return ([],'no_host');
                   8317:             }
1.955     raeburn  8318:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  8319:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  8320:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  8321:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  8322:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  8323:             } else {
                   8324:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8325:             }
1.605     matthew  8326:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  8327:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  8328:                 @listing_results = split(/:/,$listing);
                   8329:             } else {
                   8330:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8331:             }
1.1135    raeburn  8332:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  8333:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   8334:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   8335:                 return ([],$listing);
                   8336:             } else {
                   8337:                 return (\@listing_results);
1.1135    raeburn  8338:             }
1.955     raeburn  8339:         } elsif(!$alternateRoot) {
1.1136    raeburn  8340:             my (%allusers,%listerror);
1.841     albertel 8341: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  8342:  	    foreach my $tryserver (keys(%servers)) {
                   8343:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   8344:                                   &escape($udom),$tryserver);
                   8345:                 if ($listing eq 'unknown_cmd') {
                   8346: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8347: 				      $udom, $tryserver);
                   8348:                 } else {
                   8349:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8350:                 }
1.841     albertel 8351: 		if ($listing eq 'unknown_cmd') {
                   8352: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8353: 				      $udom, $tryserver);
                   8354: 		    @listing_results = split(/:/,$listing);
                   8355: 		} else {
                   8356: 		    @listing_results =
                   8357: 			map { &unescape($_); } split(/:/,$listing);
                   8358: 		}
1.1136    raeburn  8359:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   8360:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   8361:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   8362:                     $listerror{$tryserver} = $listing;
                   8363:                 } else {
1.841     albertel 8364: 		    foreach my $line (@listing_results) {
                   8365: 			my ($entry) = split(/&/,$line,2);
                   8366: 			$allusers{$entry} = 1;
                   8367: 		    }
                   8368: 		}
1.253     stredwic 8369:             }
1.1136    raeburn  8370:             my @alluserslist=();
1.800     albertel 8371:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  8372:                 push(@alluserslist,$user.'&user');
1.253     stredwic 8373:             }
1.1136    raeburn  8374:             return (\@alluserslist);
1.253     stredwic 8375:         } else {
1.1136    raeburn  8376:             return ([],'missing username');
1.253     stredwic 8377:         }
1.955     raeburn  8378:     } elsif(!defined($getpropath)) {
1.1136    raeburn  8379:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   8380:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   8381:         return (\@all_domains);
1.955     raeburn  8382:     } else {
1.1136    raeburn  8383:         return ([],'missing domain');
1.275     stredwic 8384:     }
                   8385: }
                   8386: 
                   8387: # --------------------------------------------- GetFileTimestamp
                   8388: # This function utilizes dirlist and returns the date stamp for
                   8389: # when it was last modified.  It will also return an error of -1
                   8390: # if an error occurs
                   8391: 
                   8392: sub GetFileTimestamp {
1.955     raeburn  8393:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 8394:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   8395:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  8396:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   8397:                                     undef,$getuserdir);
                   8398:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   8399:         return -1;
                   8400:     }
                   8401:     if (ref($fileref) eq 'ARRAY') {
                   8402:         my @stats = split('&',$fileref->[0]);
1.375     matthew  8403:         # @stats contains first the filename, then the stat output
                   8404:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 8405:     } else {
                   8406:         return -1;
1.253     stredwic 8407:     }
1.26      www      8408: }
                   8409: 
1.712     albertel 8410: sub stat_file {
                   8411:     my ($uri) = @_;
1.787     albertel 8412:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 8413: 
1.955     raeburn  8414:     my ($udom,$uname,$file);
1.712     albertel 8415:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   8416: 	($udom,$uname,$file) =
1.811     albertel 8417: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 8418: 	$file = 'userfiles/'.$file;
                   8419:     }
                   8420:     if ($uri =~ m-^/res/-) {
                   8421: 	($udom,$uname) = 
1.807     albertel 8422: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 8423: 	$file = $uri;
                   8424:     }
                   8425: 
                   8426:     if (!$udom || !$uname || !$file) {
                   8427: 	# unable to handle the uri
                   8428: 	return ();
                   8429:     }
1.956     raeburn  8430:     my $getpropath;
                   8431:     if ($file =~ /^userfiles\//) {
                   8432:         $getpropath = 1;
                   8433:     }
1.1136    raeburn  8434:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   8435:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   8436:         return ();
                   8437:     } else {
                   8438:         if (ref($listref) eq 'ARRAY') {
                   8439:             my @stats = split('&',$listref->[0]);
                   8440: 	    shift(@stats); #filename is first
                   8441: 	    return @stats;
                   8442:         }
1.712     albertel 8443:     }
                   8444:     return ();
                   8445: }
                   8446: 
1.26      www      8447: # -------------------------------------------------------- Value of a Condition
                   8448: 
1.713     albertel 8449: # gets the value of a specific preevaluated condition
                   8450: #    stored in the string  $env{user.state.<cid>}
                   8451: # or looks up a condition reference in the bighash and if if hasn't
                   8452: # already been evaluated recurses into docondval to get the value of
                   8453: # the condition, then memoizing it to 
                   8454: #   $env{user.state.<cid>.<condition>}
1.40      www      8455: sub directcondval {
                   8456:     my $number=shift;
1.620     albertel 8457:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 8458: 	&Apache::lonuserstate::evalstate();
                   8459:     }
1.713     albertel 8460:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   8461: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   8462:     } elsif ($number =~ /^_/) {
                   8463: 	my $sub_condition;
                   8464: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8465: 		&GDBM_READER(),0640)) {
                   8466: 	    $sub_condition=$bighash{'conditions'.$number};
                   8467: 	    untie(%bighash);
                   8468: 	}
                   8469: 	my $value = &docondval($sub_condition);
1.949     raeburn  8470: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 8471: 	return $value;
                   8472:     }
1.620     albertel 8473:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   8474:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      8475:     } else {
                   8476:        return 2;
                   8477:     }
                   8478: }
                   8479: 
1.713     albertel 8480: # get the collection of conditions for this resource
1.26      www      8481: sub condval {
                   8482:     my $condidx=shift;
1.54      www      8483:     my $allpathcond='';
1.713     albertel 8484:     foreach my $cond (split(/\|/,$condidx)) {
                   8485: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   8486: 	    $allpathcond.=
                   8487: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   8488: 	}
1.191     harris41 8489:     }
1.54      www      8490:     $allpathcond=~s/\|$//;
1.713     albertel 8491:     return &docondval($allpathcond);
                   8492: }
                   8493: 
                   8494: #evaluates an expression of conditions
                   8495: sub docondval {
                   8496:     my ($allpathcond) = @_;
                   8497:     my $result=0;
                   8498:     if ($env{'request.course.id'}
                   8499: 	&& defined($allpathcond)) {
                   8500: 	my $operand='|';
                   8501: 	my @stack;
                   8502: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   8503: 	    if ($chunk eq '(') {
                   8504: 		push @stack,($operand,$result);
                   8505: 	    } elsif ($chunk eq ')') {
                   8506: 		my $before=pop @stack;
                   8507: 		if (pop @stack eq '&') {
                   8508: 		    $result=$result>$before?$before:$result;
                   8509: 		} else {
                   8510: 		    $result=$result>$before?$result:$before;
                   8511: 		}
                   8512: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   8513: 		$operand=$chunk;
                   8514: 	    } else {
                   8515: 		my $new=directcondval($chunk);
                   8516: 		if ($operand eq '&') {
                   8517: 		    $result=$result>$new?$new:$result;
                   8518: 		} else {
                   8519: 		    $result=$result>$new?$result:$new;
                   8520: 		}
                   8521: 	    }
                   8522: 	}
1.26      www      8523:     }
                   8524:     return $result;
1.421     albertel 8525: }
                   8526: 
                   8527: # ---------------------------------------------------- Devalidate courseresdata
                   8528: 
                   8529: sub devalidatecourseresdata {
                   8530:     my ($coursenum,$coursedomain)=@_;
                   8531:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8532:     &devalidate_cache_new('courseres',$hashid);
1.28      www      8533: }
                   8534: 
1.763     www      8535: 
1.200     www      8536: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     8537: #
                   8538: #  Parameters:
                   8539: #      $coursenum    - Number of the course.
                   8540: #      $coursedomain - Domain at which the course was created.
                   8541: #  Returns:
                   8542: #     A hash of the course parameters along (I think) with timestamps
                   8543: #     and version info.
1.877     foxr     8544: 
1.624     albertel 8545: sub get_courseresdata {
                   8546:     my ($coursenum,$coursedomain)=@_;
1.200     www      8547:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8548:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8549:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8550:     my %dumpreply;
1.417     albertel 8551:     unless (defined($cached)) {
1.624     albertel 8552: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8553: 	$result=\%dumpreply;
1.251     albertel 8554: 	my ($tmp) = keys(%dumpreply);
                   8555: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8556: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8557: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8558: 	    return $tmp;
1.416     albertel 8559: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8560: 	    $result=undef;
1.599     albertel 8561: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8562: 	}
                   8563:     }
1.624     albertel 8564:     return $result;
                   8565: }
                   8566: 
1.633     albertel 8567: sub devalidateuserresdata {
                   8568:     my ($uname,$udom)=@_;
                   8569:     my $hashid="$udom:$uname";
                   8570:     &devalidate_cache_new('userres',$hashid);
                   8571: }
                   8572: 
1.624     albertel 8573: sub get_userresdata {
                   8574:     my ($uname,$udom)=@_;
                   8575:     #most student don\'t have any data set, check if there is some data
                   8576:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   8577: 
                   8578:     my $hashid="$udom:$uname";
                   8579:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   8580:     if (!defined($cached)) {
                   8581: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   8582: 	$result=\%resourcedata;
                   8583: 	&do_cache_new('userres',$hashid,$result,600);
                   8584:     }
                   8585:     my ($tmp)=keys(%$result);
                   8586:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8587: 	return $result;
                   8588:     }
                   8589:     #error 2 occurs when the .db doesn't exist
                   8590:     if ($tmp!~/error: 2 /) {
1.672     albertel 8591: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8592: 		 " Trying to get resource data for ".
                   8593: 		 $uname." at ".$udom.": ".
                   8594: 		 $tmp."</font>");
                   8595:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8596: 	#&EXT_cache_set($udom,$uname);
                   8597: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8598: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8599:     }
                   8600:     return $tmp;
                   8601: }
1.879     foxr     8602: #----------------------------------------------- resdata - return resource data
                   8603: #  Purpose:
                   8604: #    Return resource data for either users or for a course.
                   8605: #  Parameters:
                   8606: #     $name      - Course/user name.
                   8607: #     $domain    - Name of the domain the user/course is registered on.
                   8608: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8609: #     @which     - Array of names of resources desired.
                   8610: #  Returns:
                   8611: #     The value of the first reasource in @which that is found in the
                   8612: #     resource hash.
                   8613: #  Exceptional Conditions:
                   8614: #     If the $type passed in is not valid (not the string 'course' or 
                   8615: #     'user', an undefined  reference is returned.
                   8616: #     If none of the resources are found, an undef is returned
1.624     albertel 8617: sub resdata {
                   8618:     my ($name,$domain,$type,@which)=@_;
                   8619:     my $result;
                   8620:     if ($type eq 'course') {
                   8621: 	$result=&get_courseresdata($name,$domain);
                   8622:     } elsif ($type eq 'user') {
                   8623: 	$result=&get_userresdata($name,$domain);
                   8624:     }
                   8625:     if (!ref($result)) { return $result; }    
1.251     albertel 8626:     foreach my $item (@which) {
1.927     albertel 8627: 	if (defined($result->{$item->[0]})) {
                   8628: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8629: 	}
1.250     albertel 8630:     }
1.291     albertel 8631:     return undef;
1.200     www      8632: }
                   8633: 
1.379     matthew  8634: #
                   8635: # EXT resource caching routines
                   8636: #
                   8637: 
                   8638: sub clear_EXT_cache_status {
1.383     albertel 8639:     &delenv('cache.EXT.');
1.379     matthew  8640: }
                   8641: 
                   8642: sub EXT_cache_status {
                   8643:     my ($target_domain,$target_user) = @_;
1.383     albertel 8644:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8645:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8646:         # We know already the user has no data
                   8647:         return 1;
                   8648:     } else {
                   8649:         return 0;
                   8650:     }
                   8651: }
                   8652: 
                   8653: sub EXT_cache_set {
                   8654:     my ($target_domain,$target_user) = @_;
1.383     albertel 8655:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8656:     #&appenv({$cachename => time});
1.379     matthew  8657: }
                   8658: 
1.28      www      8659: # --------------------------------------------------------- Value of a Variable
1.58      www      8660: sub EXT {
1.715     albertel 8661: 
1.395     albertel 8662:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8663:     unless ($varname) { return ''; }
1.218     albertel 8664:     #get real user name/domain, courseid and symb
                   8665:     my $courseid;
1.359     albertel 8666:     my $publicuser;
1.427     www      8667:     if ($symbparm) {
                   8668: 	$symbparm=&get_symb_from_alias($symbparm);
                   8669:     }
1.218     albertel 8670:     if (!($uname && $udom)) {
1.790     albertel 8671:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8672:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8673:     } else {
1.620     albertel 8674: 	$courseid=$env{'request.course.id'};
1.218     albertel 8675:     }
1.48      www      8676:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8677:     my $rest;
1.320     albertel 8678:     if (defined($therest[0])) {
1.48      www      8679:        $rest=join('.',@therest);
                   8680:     } else {
                   8681:        $rest='';
                   8682:     }
1.320     albertel 8683: 
1.57      www      8684:     my $qualifierrest=$qualifier;
                   8685:     if ($rest) { $qualifierrest.='.'.$rest; }
                   8686:     my $spacequalifierrest=$space;
                   8687:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      8688:     if ($realm eq 'user') {
1.48      www      8689: # --------------------------------------------------------------- user.resource
                   8690: 	if ($space eq 'resource') {
1.651     albertel 8691: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   8692: 		  || defined($Apache::lonhomework::parsing_a_task))
                   8693: 		 &&
1.744     albertel 8694: 		 ($symbparm eq &symbread()) ) {	
                   8695: 		# if we are in the middle of processing the resource the
                   8696: 		# get the value we are planning on committing
                   8697:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   8698:                     return $Apache::lonhomework::results{$qualifierrest};
                   8699:                 } else {
                   8700:                     return $Apache::lonhomework::history{$qualifierrest};
                   8701:                 }
1.335     albertel 8702: 	    } else {
1.359     albertel 8703: 		my %restored;
1.620     albertel 8704: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 8705: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   8706: 		} else {
                   8707: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   8708: 		}
1.335     albertel 8709: 		return $restored{$qualifierrest};
                   8710: 	    }
1.48      www      8711: # ----------------------------------------------------------------- user.access
                   8712:         } elsif ($space eq 'access') {
1.218     albertel 8713: 	    # FIXME - not supporting calls for a specific user
1.48      www      8714:             return &allowed($qualifier,$rest);
                   8715: # ------------------------------------------ user.preferences, user.environment
                   8716:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 8717: 	    if (($uname eq $env{'user.name'}) &&
                   8718: 		($udom eq $env{'user.domain'})) {
                   8719: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 8720: 	    } else {
1.359     albertel 8721: 		my %returnhash;
                   8722: 		if (!$publicuser) {
                   8723: 		    %returnhash=&userenvironment($udom,$uname,
                   8724: 						 $qualifierrest);
                   8725: 		}
1.218     albertel 8726: 		return $returnhash{$qualifierrest};
                   8727: 	    }
1.48      www      8728: # ----------------------------------------------------------------- user.course
                   8729:         } elsif ($space eq 'course') {
1.218     albertel 8730: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8731:             return $env{join('.',('request.course',$qualifier))};
1.48      www      8732: # ------------------------------------------------------------------- user.role
                   8733:         } elsif ($space eq 'role') {
1.218     albertel 8734: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8735:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      8736:             if ($qualifier eq 'value') {
                   8737: 		return $role;
                   8738:             } elsif ($qualifier eq 'extent') {
                   8739:                 return $where;
                   8740:             }
                   8741: # ----------------------------------------------------------------- user.domain
                   8742:         } elsif ($space eq 'domain') {
1.218     albertel 8743:             return $udom;
1.48      www      8744: # ------------------------------------------------------------------- user.name
                   8745:         } elsif ($space eq 'name') {
1.218     albertel 8746:             return $uname;
1.48      www      8747: # ---------------------------------------------------- Any other user namespace
1.29      www      8748:         } else {
1.359     albertel 8749: 	    my %reply;
                   8750: 	    if (!$publicuser) {
                   8751: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   8752: 	    }
                   8753: 	    return $reply{$qualifierrest};
1.48      www      8754:         }
1.236     www      8755:     } elsif ($realm eq 'query') {
                   8756: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 8757:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   8758: 						[$spacequalifierrest]);
1.620     albertel 8759: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      8760:    } elsif ($realm eq 'request') {
1.48      www      8761: # ------------------------------------------------------------- request.browser
                   8762:         if ($space eq 'browser') {
1.1145    bisitz   8763:             return $env{'browser.'.$qualifier};
1.57      www      8764: # ------------------------------------------------------------ request.filename
                   8765:         } else {
1.620     albertel 8766:             return $env{'request.'.$spacequalifierrest};
1.29      www      8767:         }
1.28      www      8768:     } elsif ($realm eq 'course') {
1.48      www      8769: # ---------------------------------------------------------- course.description
1.620     albertel 8770:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      8771:     } elsif ($realm eq 'resource') {
1.165     www      8772: 
1.620     albertel 8773: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 8774: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   8775: 	}
1.693     albertel 8776: 
                   8777: 	if ($space eq 'title') {
                   8778: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   8779: 	    return &gettitle($symbparm);
                   8780: 	}
                   8781: 	
                   8782: 	if ($space eq 'map') {
                   8783: 	    my ($map) = &decode_symb($symbparm);
                   8784: 	    return &symbread($map);
                   8785: 	}
1.905     albertel 8786: 	if ($space eq 'filename') {
                   8787: 	    if ($symbparm) {
                   8788: 		return &clutter((&decode_symb($symbparm))[2]);
                   8789: 	    }
                   8790: 	    return &hreflocation('',$env{'request.filename'});
                   8791: 	}
1.693     albertel 8792: 
                   8793: 	my ($section, $group, @groups);
1.593     albertel 8794: 	my ($courselevelm,$courselevel);
1.539     albertel 8795: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8796: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      8797: 
1.218     albertel 8798: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      8799: 
1.60      www      8800: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 8801: 	    my $symbp=$symbparm;
1.735     albertel 8802: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 8803: 
                   8804: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   8805: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   8806: 
1.620     albertel 8807: 	    if (($env{'user.name'} eq $uname) &&
                   8808: 		($env{'user.domain'} eq $udom)) {
                   8809: 		$section=$env{'request.course.sec'};
1.733     raeburn  8810:                 @groups = split(/:/,$env{'request.course.groups'});  
                   8811:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 8812: 	    } else {
1.539     albertel 8813: 		if (! defined($usection)) {
1.551     albertel 8814: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 8815: 		} else {
                   8816: 		    $section = $usection;
                   8817: 		}
1.733     raeburn  8818:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 8819: 	    }
                   8820: 
                   8821: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   8822: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   8823: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   8824: 
1.593     albertel 8825: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 8826: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 8827: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      8828: 
1.60      www      8829: # ----------------------------------------------------------- first, check user
1.624     albertel 8830: 
                   8831: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 8832: 				       ([$courselevelr,'resource'],
                   8833: 					[$courselevelm,'map'     ],
                   8834: 					[$courselevel, 'course'  ]));
1.931     albertel 8835: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      8836: 
1.594     albertel 8837: # ------------------------------------------------ second, check some of course
1.684     raeburn  8838:             my $coursereply;
1.691     raeburn  8839:             if (@groups > 0) {
                   8840:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   8841:                                        $mapparm,$spacequalifierrest);
1.927     albertel 8842:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  8843:             }
1.96      www      8844: 
1.684     raeburn  8845: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 8846: 				  $env{'course.'.$courseid.'.domain'},
                   8847: 				  'course',
                   8848: 				  ([$seclevelr,   'resource'],
                   8849: 				   [$seclevelm,   'map'     ],
                   8850: 				   [$seclevel,    'course'  ],
                   8851: 				   [$courselevelr,'resource']));
                   8852: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      8853: 
1.60      www      8854: # ------------------------------------------------------ third, check map parms
1.218     albertel 8855: 	    my %parmhash=();
                   8856: 	    my $thisparm='';
                   8857: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 8858: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 8859: 		    &GDBM_READER(),0640)) {
1.218     albertel 8860: 		$thisparm=$parmhash{$symbparm};
                   8861: 		untie(%parmhash);
                   8862: 	    }
1.927     albertel 8863: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 8864: 	}
1.594     albertel 8865: # ------------------------------------------ fourth, look in resource metadata
1.71      www      8866: 
1.218     albertel 8867: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 8868: 	my $filename;
                   8869: 	if (!$symbparm) { $symbparm=&symbread(); }
                   8870: 	if ($symbparm) {
1.409     www      8871: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 8872: 	} else {
1.620     albertel 8873: 	    $filename=$env{'request.filename'};
1.282     albertel 8874: 	}
                   8875: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 8876: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 8877: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 8878: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      8879: 
1.927     albertel 8880: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 8881: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8882: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 8883: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   8884: 				     $env{'course.'.$courseid.'.domain'},
                   8885: 				     'course',
1.927     albertel 8886: 				     ([$courselevelm,'map'   ],
                   8887: 				      [$courselevel, 'course']));
                   8888: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 8889: 	}
1.145     www      8890: # ------------------------------------------------------------------ Cascade up
1.218     albertel 8891: 	unless ($space eq '0') {
1.336     albertel 8892: 	    my @parts=split(/_/,$space);
                   8893: 	    my $id=pop(@parts);
                   8894: 	    my $part=join('_',@parts);
                   8895: 	    if ($part eq '') { $part='0'; }
1.927     albertel 8896: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 8897: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  8898: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 8899: 	}
1.395     albertel 8900: 	if ($recurse) { return undef; }
                   8901: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 8902: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      8903: # ---------------------------------------------------- Any other user namespace
                   8904:     } elsif ($realm eq 'environment') {
                   8905: # ----------------------------------------------------------------- environment
1.620     albertel 8906: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   8907: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 8908: 	} else {
1.770     albertel 8909: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   8910: 		return '';
                   8911: 	    }
1.219     albertel 8912: 	    my %returnhash=&userenvironment($udom,$uname,
                   8913: 					    $spacequalifierrest);
                   8914: 	    return $returnhash{$spacequalifierrest};
                   8915: 	}
1.28      www      8916:     } elsif ($realm eq 'system') {
1.48      www      8917: # ----------------------------------------------------------------- system.time
                   8918: 	if ($space eq 'time') {
                   8919: 	    return time;
                   8920:         }
1.696     albertel 8921:     } elsif ($realm eq 'server') {
                   8922: # ----------------------------------------------------------------- system.time
                   8923: 	if ($space eq 'name') {
                   8924: 	    return $ENV{'SERVER_NAME'};
                   8925:         }
1.28      www      8926:     }
1.48      www      8927:     return '';
1.61      www      8928: }
                   8929: 
1.927     albertel 8930: sub get_reply {
                   8931:     my ($reply_value) = @_;
1.940     raeburn  8932:     if (ref($reply_value) eq 'ARRAY') {
                   8933:         if (wantarray) {
                   8934: 	    return @$reply_value;
                   8935:         }
                   8936:         return $reply_value->[0];
                   8937:     } else {
                   8938:         return $reply_value;
1.927     albertel 8939:     }
                   8940: }
                   8941: 
1.691     raeburn  8942: sub check_group_parms {
                   8943:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   8944:     my @groupitems = ();
                   8945:     my $resultitem;
1.927     albertel 8946:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  8947:     foreach my $group (@{$groups}) {
                   8948:         foreach my $level (@levels) {
1.927     albertel 8949:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   8950:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  8951:         }
                   8952:     }
                   8953:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   8954:                             $env{'course.'.$courseid.'.domain'},
                   8955:                                      'course',@groupitems);
                   8956:     return $coursereply;
                   8957: }
                   8958: 
                   8959: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  8960:     my ($courseid,@groups) = @_;
                   8961:     @groups = sort(@groups);
1.691     raeburn  8962:     return @groups;
                   8963: }
                   8964: 
1.395     albertel 8965: sub packages_tab_default {
                   8966:     my ($uri,$varname)=@_;
                   8967:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 8968: 
                   8969:     my (@extension,@specifics,$do_default);
                   8970:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 8971: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 8972: 	if ($pack_type eq 'default') {
                   8973: 	    $do_default=1;
                   8974: 	} elsif ($pack_type eq 'extension') {
                   8975: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 8976: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 8977: 	    # only look at packages defaults for packages that this id is
1.738     albertel 8978: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   8979: 	}
                   8980:     }
                   8981:     # first look for a package that matches the requested part id
                   8982:     foreach my $package (@specifics) {
                   8983: 	my (undef,$pack_type,$pack_part)=@{$package};
                   8984: 	next if ($pack_part ne $part);
                   8985: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8986: 	    return $packagetab{"$pack_type&$name&default"};
                   8987: 	}
                   8988:     }
                   8989:     # look for any possible matching non extension_ package
                   8990:     foreach my $package (@specifics) {
                   8991: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 8992: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8993: 	    return $packagetab{"$pack_type&$name&default"};
                   8994: 	}
1.585     albertel 8995: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 8996: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   8997: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 8998: 	}
                   8999:     }
1.738     albertel 9000:     # look for any posible extension_ match
                   9001:     foreach my $package (@extension) {
                   9002: 	my ($package,$pack_type)=@{$package};
                   9003: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9004: 	    return $packagetab{"$pack_type&$name&default"};
                   9005: 	}
                   9006: 	if (defined($packagetab{$package."&$name&default"})) {
                   9007: 	    return $packagetab{$package."&$name&default"};
                   9008: 	}
                   9009:     }
                   9010:     # look for a global default setting
                   9011:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   9012: 	return $packagetab{"default&$name&default"};
                   9013:     }
1.395     albertel 9014:     return undef;
                   9015: }
                   9016: 
1.334     albertel 9017: sub add_prefix_and_part {
                   9018:     my ($prefix,$part)=@_;
                   9019:     my $keyroot;
                   9020:     if (defined($prefix) && $prefix !~ /^__/) {
                   9021: 	# prefix that has a part already
                   9022: 	$keyroot=$prefix;
                   9023:     } elsif (defined($prefix)) {
                   9024: 	# prefix that is missing a part
                   9025: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   9026:     } else {
                   9027: 	# no prefix at all
                   9028: 	if (defined($part)) { $keyroot='_'.$part; }
                   9029:     }
                   9030:     return $keyroot;
                   9031: }
                   9032: 
1.71      www      9033: # ---------------------------------------------------------------- Get metadata
                   9034: 
1.599     albertel 9035: my %metaentry;
1.1070    www      9036: my %importedpartids;
1.71      www      9037: sub metadata {
1.176     www      9038:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      9039:     $uri=&declutter($uri);
1.288     albertel 9040:     # if it is a non metadata possible uri return quickly
1.529     albertel 9041:     if (($uri eq '') || 
                   9042: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 9043: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108    raeburn  9044:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 9045: 	return undef;
                   9046:     }
1.1140    www      9047:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 9048: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 9049: 	return undef;
1.288     albertel 9050:     }
1.73      www      9051:     my $filename=$uri;
                   9052:     $uri=~s/\.meta$//;
1.172     www      9053: #
                   9054: # Is the metadata already cached?
1.177     www      9055: # Look at timestamp of caching
1.172     www      9056: # Everything is cached by the main uri, libraries are never directly cached
                   9057: #
1.428     albertel 9058:     if (!defined($liburi)) {
1.599     albertel 9059: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 9060: 	if (defined($cached)) { return $result->{':'.$what}; }
                   9061:     }
                   9062:     {
1.1069    www      9063: # Imported parts would go here
1.1070    www      9064:         my %importedids=();
                   9065:         my @origfileimportpartids=();
1.1069    www      9066:         my $importedparts=0;
1.172     www      9067: #
                   9068: # Is this a recursive call for a library?
                   9069: #
1.599     albertel 9070: #	if (! exists($metacache{$uri})) {
                   9071: #	    $metacache{$uri}={};
                   9072: #	}
1.924     albertel 9073: 	my $cachetime = 60*60;
1.171     www      9074:         if ($liburi) {
                   9075: 	    $liburi=&declutter($liburi);
                   9076:             $filename=$liburi;
1.401     bowersj2 9077:         } else {
1.599     albertel 9078: 	    &devalidate_cache_new('meta',$uri);
                   9079: 	    undef(%metaentry);
1.401     bowersj2 9080: 	}
1.140     www      9081:         my %metathesekeys=();
1.73      www      9082:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 9083: 	my $metastring;
1.1140    www      9084: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 9085: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 9086: 	    $metastring = 
1.929     albertel 9087: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 9088: 					  ('grade_target' => 'meta'));
                   9089: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  9090: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   9091:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 9092: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 9093: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 9094: 	    $metastring=&getfile($file);
1.489     albertel 9095: 	}
1.208     albertel 9096:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      9097:         my $token;
1.140     www      9098:         undef %metathesekeys;
1.71      www      9099:         while ($token=$parser->get_token) {
1.339     albertel 9100: 	    if ($token->[0] eq 'S') {
                   9101: 		if (defined($token->[2]->{'package'})) {
1.172     www      9102: #
                   9103: # This is a package - get package info
                   9104: #
1.339     albertel 9105: 		    my $package=$token->[2]->{'package'};
                   9106: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9107: 		    if (defined($token->[2]->{'id'})) { 
                   9108: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   9109: 		    }
1.599     albertel 9110: 		    if ($metaentry{':packages'}) {
                   9111: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 9112: 		    } else {
1.599     albertel 9113: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 9114: 		    }
1.736     albertel 9115: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 9116: 			my $part=$keyroot;
                   9117: 			$part=~s/^\_//;
1.736     albertel 9118: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   9119: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   9120: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 9121: 			    # ignore package.tab specified default values
                   9122:                             # here &package_tab_default() will fetch those
                   9123: 			    if ($subp eq 'default') { next; }
1.736     albertel 9124: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 9125: 			    my $unikey;
                   9126: 			    if ($pack =~ /_0$/) {
                   9127: 				$unikey='parameter_0_'.$name;
                   9128: 				$part=0;
                   9129: 			    } else {
                   9130: 				$unikey='parameter'.$keyroot.'_'.$name;
                   9131: 			    }
1.339     albertel 9132: 			    if ($subp eq 'display') {
                   9133: 				$value.=' [Part: '.$part.']';
                   9134: 			    }
1.599     albertel 9135: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 9136: 			    $metathesekeys{$unikey}=1;
1.599     albertel 9137: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9138: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 9139: 			    }
1.599     albertel 9140: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   9141: 				$metaentry{':'.$unikey}=
                   9142: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 9143: 			    }
1.339     albertel 9144: 			}
                   9145: 		    }
                   9146: 		} else {
1.172     www      9147: #
                   9148: # This is not a package - some other kind of start tag
1.339     albertel 9149: #
                   9150: 		    my $entry=$token->[1];
1.1068    www      9151: 		    my $unikey='';
1.175     www      9152: 
1.339     albertel 9153: 		    if ($entry eq 'import') {
1.175     www      9154: #
                   9155: # Importing a library here
1.339     albertel 9156: #
1.1067    www      9157:                         my $location=$parser->get_text('/import');
                   9158:                         my $dir=$filename;
                   9159:                         $dir=~s|[^/]*$||;
                   9160:                         $location=&filelocation($dir,$location);
1.1069    www      9161:                        
1.1068    www      9162:                         my $importmode=$token->[2]->{'importmode'};
                   9163:                         if ($importmode eq 'problem') {
1.1069    www      9164: # Import as problem/response
1.1068    www      9165:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9166:                         } elsif ($importmode eq 'part') {
                   9167: # Import as part(s)
1.1069    www      9168:                            $importedparts=1;
                   9169: # We need to get the original file and the imported file to get the part order correct
                   9170: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   9171: # Load and inspect original file
1.1070    www      9172:                            if ($#origfileimportpartids<0) {
                   9173:                               undef(%importedpartids);
                   9174:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   9175:                               my $origfile=&getfile($origfilelocation);
                   9176:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9177:                            }
                   9178: 
1.1069    www      9179: # Load and inspect imported file
                   9180:                            my $impfile=&getfile($location);
                   9181:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9182:                            if ($#impfilepartids>=0) {
                   9183: # This problem had parts
1.1070    www      9184:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      9185:                            } else {
                   9186: # Importing by turning a single problem into a problem part
                   9187: # It gets the import-tags ID as part-ID
                   9188:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      9189:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      9190:                            }
1.1068    www      9191:                         } else {
                   9192: # Normal import
                   9193:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9194:                            if (defined($token->[2]->{'id'})) {
                   9195:                               $unikey.='_'.$token->[2]->{'id'};
                   9196:                            }
1.1067    www      9197:                         }
                   9198: 
1.339     albertel 9199: 			if ($depthcount<20) {
1.736     albertel 9200: 			    my $metadata = 
                   9201: 				&metadata($uri,'keys', $location,$unikey,
                   9202: 					  $depthcount+1);
                   9203: 			    foreach my $meta (split(',',$metadata)) {
                   9204: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   9205: 				$metathesekeys{$meta}=1;
1.339     albertel 9206: 			    }
1.1068    www      9207: 			
                   9208:                         }
1.1067    www      9209: 		    } else {
                   9210: #
                   9211: # Not importing, some other kind of non-package, non-library start tag
                   9212: # 
                   9213:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9214:                         if (defined($token->[2]->{'id'})) {
                   9215:                             $unikey.='_'.$token->[2]->{'id'};
                   9216:                         }
1.339     albertel 9217: 			if (defined($token->[2]->{'name'})) { 
                   9218: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   9219: 			}
                   9220: 			$metathesekeys{$unikey}=1;
1.736     albertel 9221: 			foreach my $param (@{$token->[3]}) {
                   9222: 			    $metaentry{':'.$unikey.'.'.$param} =
                   9223: 				$token->[2]->{$param};
1.339     albertel 9224: 			}
                   9225: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 9226: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 9227: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   9228: 		 # only ws inside the tag, and not in default, so use default
                   9229: 		 # as value
1.599     albertel 9230: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 9231: 			} elsif ( $internaltext =~ /\S/ ) {
                   9232: 		  # something interesting inside the tag
                   9233: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 9234: 			} else {
1.908     albertel 9235: 		  # no interesting values, don't set a default
1.339     albertel 9236: 			}
1.172     www      9237: # end of not-a-package not-a-library import
1.339     albertel 9238: 		    }
1.172     www      9239: # end of not-a-package start tag
1.339     albertel 9240: 		}
1.172     www      9241: # the next is the end of "start tag"
1.339     albertel 9242: 	    }
                   9243: 	}
1.483     albertel 9244: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 9245: 	$extension = lc($extension);
                   9246: 	if ($extension eq 'htm') { $extension='html'; }
                   9247: 
1.737     albertel 9248: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 9249: 	    #no specific packages #how's our extension
                   9250: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 9251: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 9252: 					 \%metathesekeys);
                   9253: 	}
1.883     albertel 9254: 
                   9255: 	if (!exists($metaentry{':packages'})
                   9256: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 9257: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 9258: 		#no specific packages well let's get default then
                   9259: 		if ($key!~/^default&/) { next; }
1.488     albertel 9260: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 9261: 					     \%metathesekeys);
                   9262: 	    }
                   9263: 	}
1.338     www      9264: # are there custom rights to evaluate
1.599     albertel 9265: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 9266: 
1.338     www      9267:     #
                   9268:     # Importing a rights file here
1.339     albertel 9269:     #
                   9270: 	    unless ($depthcount) {
1.599     albertel 9271: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 9272: 		my $dir=$filename;
                   9273: 		$dir=~s|[^/]*$||;
                   9274: 		$location=&filelocation($dir,$location);
1.736     albertel 9275: 		my $rights_metadata =
                   9276: 		    &metadata($uri,'keys',$location,'_rights',
                   9277: 			      $depthcount+1);
                   9278: 		foreach my $rights (split(',',$rights_metadata)) {
                   9279: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   9280: 		    $metathesekeys{$rights}=1;
1.339     albertel 9281: 		}
                   9282: 	    }
                   9283: 	}
1.737     albertel 9284: 	# uniqifiy package listing
                   9285: 	my %seen;
                   9286: 	my @uniq_packages =
                   9287: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   9288: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   9289: 
1.1070    www      9290:         if ($importedparts) {
                   9291: # We had imported parts and need to rebuild partorder
                   9292:            $metaentry{':partorder'}='';
                   9293:            $metathesekeys{'partorder'}=1;
                   9294:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   9295:                if ($origfileimportpartids[$index] eq 'part') {
                   9296: # original part, part of the problem
                   9297:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   9298:                } else {
                   9299: # we have imported parts at this position
                   9300:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   9301:                }
                   9302:            }
                   9303:            $metaentry{':partorder'}=~s/^\,//;
                   9304:         }
                   9305: 
1.737     albertel 9306: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 9307: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   9308: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 9309: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      9310: # this is the end of "was not already recently cached
1.71      www      9311:     }
1.599     albertel 9312:     return $metaentry{':'.$what};
1.261     albertel 9313: }
                   9314: 
1.488     albertel 9315: sub metadata_create_package_def {
1.483     albertel 9316:     my ($uri,$key,$package,$metathesekeys)=@_;
                   9317:     my ($pack,$name,$subp)=split(/\&/,$key);
                   9318:     if ($subp eq 'default') { next; }
                   9319:     
1.599     albertel 9320:     if (defined($metaentry{':packages'})) {
                   9321: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 9322:     } else {
1.599     albertel 9323: 	$metaentry{':packages'}=$package;
1.483     albertel 9324:     }
                   9325:     my $value=$packagetab{$key};
                   9326:     my $unikey;
                   9327:     $unikey='parameter_0_'.$name;
1.599     albertel 9328:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 9329:     $$metathesekeys{$unikey}=1;
1.599     albertel 9330:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9331: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 9332:     }
1.599     albertel 9333:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   9334: 	$metaentry{':'.$unikey}=
                   9335: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 9336:     }
                   9337: }
                   9338: 
1.261     albertel 9339: sub metadata_generate_part0 {
                   9340:     my ($metadata,$metacache,$uri) = @_;
                   9341:     my %allnames;
1.737     albertel 9342:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 9343: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 9344: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   9345: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 9346: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 9347: 	    $allnames{$name}=$part;
                   9348: 	  }
                   9349: 	}
                   9350:     }
                   9351:     foreach my $name (keys(%allnames)) {
                   9352:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 9353:       my $key=":parameter_0_$name";
1.261     albertel 9354:       $$metacache{"$key.part"}='0';
                   9355:       $$metacache{"$key.name"}=$name;
1.428     albertel 9356:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 9357: 					   $allnames{$name}.'_'.$name.
                   9358: 					   '.type'};
1.428     albertel 9359:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 9360: 			     '.display'};
1.644     www      9361:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 9362:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 9363:       $$metacache{"$key.display"}=$olddis;
                   9364:     }
1.71      www      9365: }
                   9366: 
1.764     albertel 9367: # ------------------------------------------------------ Devalidate title cache
                   9368: 
                   9369: sub devalidate_title_cache {
                   9370:     my ($url)=@_;
                   9371:     if (!$env{'request.course.id'}) { return; }
                   9372:     my $symb=&symbread($url);
                   9373:     if (!$symb) { return; }
                   9374:     my $key=$env{'request.course.id'}."\0".$symb;
                   9375:     &devalidate_cache_new('title',$key);
                   9376: }
                   9377: 
1.1014    droeschl 9378: # ------------------------------------------------- Get the title of a course
                   9379: 
                   9380: sub current_course_title {
                   9381:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   9382: }
1.301     www      9383: # ------------------------------------------------- Get the title of a resource
                   9384: 
                   9385: sub gettitle {
                   9386:     my $urlsymb=shift;
                   9387:     my $symb=&symbread($urlsymb);
1.534     albertel 9388:     if ($symb) {
1.620     albertel 9389: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 9390: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 9391: 	if (defined($cached)) { 
                   9392: 	    return $result;
                   9393: 	}
1.534     albertel 9394: 	my ($map,$resid,$url)=&decode_symb($symb);
                   9395: 	my $title='';
1.907     albertel 9396: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   9397: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   9398: 	} else {
                   9399: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9400: 		    &GDBM_READER(),0640)) {
                   9401: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   9402: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   9403: 		untie(%bighash);
                   9404: 	    }
1.534     albertel 9405: 	}
                   9406: 	$title=~s/\&colon\;/\:/gs;
                   9407: 	if ($title) {
1.1159  ! www      9408: # Remember both $symb and $title for dynamic metadata
        !          9409:             $accesshash{$symb.'___crstitle'}=$title;
        !          9410: # Cache this title and then return it
1.599     albertel 9411: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 9412: 	}
                   9413: 	$urlsymb=$url;
                   9414:     }
                   9415:     my $title=&metadata($urlsymb,'title');
                   9416:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   9417:     return $title;
1.301     www      9418: }
1.613     albertel 9419: 
1.614     albertel 9420: sub get_slot {
                   9421:     my ($which,$cnum,$cdom)=@_;
                   9422:     if (!$cnum || !$cdom) {
1.790     albertel 9423: 	(undef,my $courseid)=&whichuser();
1.620     albertel 9424: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   9425: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 9426:     }
1.703     albertel 9427:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   9428:     my %slotinfo;
                   9429:     if (exists($remembered{$key})) {
                   9430: 	$slotinfo{$which} = $remembered{$key};
                   9431:     } else {
                   9432: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   9433: 	&Apache::lonhomework::showhash(%slotinfo);
                   9434: 	my ($tmp)=keys(%slotinfo);
                   9435: 	if ($tmp=~/^error:/) { return (); }
                   9436: 	$remembered{$key} = $slotinfo{$which};
                   9437:     }
1.616     albertel 9438:     if (ref($slotinfo{$which}) eq 'HASH') {
                   9439: 	return %{$slotinfo{$which}};
                   9440:     }
                   9441:     return $slotinfo{$which};
1.614     albertel 9442: }
1.1150    raeburn  9443: 
                   9444: sub get_reservable_slots {
                   9445:     my ($cnum,$cdom,$uname,$udom) = @_;
                   9446:     my $now = time;
                   9447:     my $reservable_info;
                   9448:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   9449:     if (exists($remembered{$key})) {
                   9450:         $reservable_info = $remembered{$key};
                   9451:     } else {
                   9452:         my %resv;
                   9453:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   9454:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   9455:         $reservable_info = \%resv;
                   9456:         $remembered{$key} = $reservable_info;
                   9457:     }
                   9458:     return $reservable_info;
                   9459: }
                   9460: 
                   9461: sub get_course_slots {
                   9462:     my ($cnum,$cdom) = @_;
                   9463:     my $hashid=$cnum.':'.$cdom;
                   9464:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   9465:     if (defined($cached)) {
                   9466:         if (ref($result) eq 'HASH') {
                   9467:             return %{$result};
                   9468:         }
                   9469:     } else {
                   9470:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   9471:         my ($tmp) = keys(%slots);
                   9472:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9473:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
                   9474:             return %slots;
                   9475:         }
                   9476:     }
                   9477:     return;
                   9478: }
                   9479: 
                   9480: sub devalidate_slots_cache {
                   9481:     my ($cnum,$cdom)=@_;
                   9482:     my $hashid=$cnum.':'.$cdom;
                   9483:     &devalidate_cache_new('allslots',$hashid);
                   9484: }
                   9485: 
1.31      www      9486: # ------------------------------------------------- Update symbolic store links
                   9487: 
                   9488: sub symblist {
                   9489:     my ($mapname,%newhash)=@_;
1.438     www      9490:     $mapname=&deversion(&declutter($mapname));
1.31      www      9491:     my %hash;
1.620     albertel 9492:     if (($env{'request.course.fn'}) && (%newhash)) {
                   9493:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9494:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  9495: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 9496: 		next if ($url eq 'last_known'
                   9497: 			 && $env{'form.no_update_last_known'});
                   9498: 		$hash{declutter($url)}=&encode_symb($mapname,
                   9499: 						    $newhash{$url}->[1],
                   9500: 						    $newhash{$url}->[0]);
1.191     harris41 9501:             }
1.31      www      9502:             if (untie(%hash)) {
                   9503: 		return 'ok';
                   9504:             }
                   9505:         }
                   9506:     }
                   9507:     return 'error';
1.212     www      9508: }
                   9509: 
                   9510: # --------------------------------------------------------------- Verify a symb
                   9511: 
                   9512: sub symbverify {
1.510     www      9513:     my ($symb,$thisurl)=@_;
                   9514:     my $thisfn=$thisurl;
1.439     www      9515:     $thisfn=&declutter($thisfn);
1.215     www      9516: # direct jump to resource in page or to a sequence - will construct own symbs
                   9517:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   9518: # check URL part
1.409     www      9519:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      9520: 
1.431     www      9521:     unless ($url eq $thisfn) { return 0; }
1.213     www      9522: 
1.216     www      9523:     $symb=&symbclean($symb);
1.510     www      9524:     $thisurl=&deversion($thisurl);
1.439     www      9525:     $thisfn=&deversion($thisfn);
1.213     www      9526: 
                   9527:     my %bighash;
                   9528:     my $okay=0;
1.431     www      9529: 
1.620     albertel 9530:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9531:                             &GDBM_READER(),0640)) {
1.1032    raeburn  9532:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   9533:             $thisurl =~ s/\?.+$//;
                   9534:         }
1.510     www      9535:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102    raeburn  9536:         unless ($ids) {
                   9537:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   9538:             $ids=$bighash{$idkey};
1.216     www      9539:         }
                   9540:         if ($ids) {
                   9541: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 9542: 	    foreach my $id (split(/\,/,$ids)) {
                   9543: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  9544:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   9545:                    $symb =~ s/\?.+$//;
                   9546:                }
1.216     www      9547:                if (
                   9548:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   9549:    eq $symb) { 
1.620     albertel 9550: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  9551: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   9552:                        ($thisurl eq '/adm/navmaps')) {
1.582     albertel 9553: 		       $okay=1; 
                   9554: 		   }
                   9555: 	       }
1.216     www      9556: 	   }
                   9557:         }
1.213     www      9558: 	untie(%bighash);
                   9559:     }
                   9560:     return $okay;
1.31      www      9561: }
                   9562: 
1.210     www      9563: # --------------------------------------------------------------- Clean-up symb
                   9564: 
                   9565: sub symbclean {
                   9566:     my $symb=shift;
1.568     albertel 9567:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      9568: # remove version from map
                   9569:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      9570: 
1.210     www      9571: # remove version from URL
                   9572:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      9573: 
1.507     www      9574: # remove wrapper
                   9575: 
1.510     www      9576:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 9577:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      9578:     return $symb;
1.409     www      9579: }
                   9580: 
                   9581: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 9582: 
                   9583: sub encode_symb {
                   9584:     my ($map,$resid,$url)=@_;
                   9585:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   9586: }
1.409     www      9587: 
                   9588: sub decode_symb {
1.568     albertel 9589:     my $symb=shift;
                   9590:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   9591:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      9592:     return (&fixversion($map),$resid,&fixversion($url));
                   9593: }
                   9594: 
                   9595: sub fixversion {
                   9596:     my $fn=shift;
1.609     banghart 9597:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      9598:     my %bighash;
                   9599:     my $uri=&clutter($fn);
1.620     albertel 9600:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      9601: # is this cached?
1.599     albertel 9602:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      9603:     if (defined($cached)) { return $result; }
                   9604: # unfortunately not cached, or expired
1.620     albertel 9605:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      9606: 	    &GDBM_READER(),0640)) {
                   9607:  	if ($bighash{'version_'.$uri}) {
                   9608:  	    my $version=$bighash{'version_'.$uri};
1.444     www      9609:  	    unless (($version eq 'mostrecent') || 
                   9610: 		    ($version==&getversion($uri))) {
1.440     www      9611:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   9612:  	    }
                   9613:  	}
                   9614:  	untie %bighash;
1.413     www      9615:     }
1.599     albertel 9616:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      9617: }
                   9618: 
                   9619: sub deversion {
                   9620:     my $url=shift;
                   9621:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   9622:     return $url;
1.210     www      9623: }
                   9624: 
1.31      www      9625: # ------------------------------------------------------ Return symb list entry
                   9626: 
                   9627: sub symbread {
1.249     www      9628:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 9629:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 9630:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      9631: # no filename provided? try from environment
1.44      www      9632:     unless ($thisfn) {
1.620     albertel 9633:         if ($env{'request.symb'}) {
                   9634: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 9635: 	}
1.620     albertel 9636: 	$thisfn=$env{'request.filename'};
1.44      www      9637:     }
1.569     albertel 9638:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      9639: # is that filename actually a symb? Verify, clean, and return
                   9640:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 9641: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 9642: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 9643: 	}
1.242     www      9644:     }
1.44      www      9645:     $thisfn=declutter($thisfn);
1.31      www      9646:     my %hash;
1.37      www      9647:     my %bighash;
                   9648:     my $syval='';
1.620     albertel 9649:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  9650:         my $targetfn = $thisfn;
1.609     banghart 9651:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  9652:             $targetfn = 'adm/wrapper/'.$thisfn;
                   9653:         }
1.687     albertel 9654: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   9655: 	    $targetfn=$1;
                   9656: 	}
1.620     albertel 9657:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9658:                       &GDBM_READER(),0640)) {
1.481     raeburn  9659: 	    $syval=$hash{$targetfn};
1.37      www      9660:             untie(%hash);
                   9661:         }
                   9662: # ---------------------------------------------------------- There was an entry
                   9663:         if ($syval) {
1.601     albertel 9664: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 9665: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  9666: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9667: 		    #return $env{$cache_str}='';
1.601     albertel 9668: 		#}    
                   9669: 		#$syval.=$1;
                   9670: 	    #}
1.37      www      9671:         } else {
                   9672: # ------------------------------------------------------- Was not in symb table
1.620     albertel 9673:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9674:                             &GDBM_READER(),0640)) {
1.37      www      9675: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      9676:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      9677:               unless ($ids) { 
                   9678:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      9679:               }
                   9680:               unless ($ids) {
                   9681: # alias?
                   9682: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      9683:               }
1.37      www      9684:               if ($ids) {
                   9685: # ------------------------------------------------------------------- Has ID(s)
                   9686:                  my @possibilities=split(/\,/,$ids);
1.39      www      9687:                  if ($#possibilities==0) {
                   9688: # ----------------------------------------------- There is only one possibility
1.37      www      9689: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 9690: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9691: 						    $resid,$thisfn);
1.249     www      9692:                  } elsif (!$donotrecurse) {
1.39      www      9693: # ------------------------------------------ There is more than one possibility
                   9694:                      my $realpossible=0;
1.800     albertel 9695:                      foreach my $id (@possibilities) {
                   9696: 			 my $file=$bighash{'src_'.$id};
1.39      www      9697:                          if (&allowed('bre',$file)) {
1.800     albertel 9698:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      9699:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   9700: 				$realpossible++;
1.626     albertel 9701:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9702: 						    $resid,$thisfn);
1.39      www      9703:                             }
                   9704: 			 }
1.191     harris41 9705:                      }
1.39      www      9706: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      9707:                  } else {
                   9708:                      $syval='';
1.37      www      9709:                  }
                   9710: 	      }
                   9711:               untie(%bighash)
1.481     raeburn  9712:            }
1.31      www      9713:         }
1.62      www      9714:         if ($syval) {
1.620     albertel 9715: 	    return $env{$cache_str}=$syval;
1.62      www      9716:         }
1.31      www      9717:     }
1.949     raeburn  9718:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9719:     return $env{$cache_str}='';
1.31      www      9720: }
                   9721: 
                   9722: # ---------------------------------------------------------- Return random seed
                   9723: 
1.32      www      9724: sub numval {
                   9725:     my $txt=shift;
                   9726:     $txt=~tr/A-J/0-9/;
                   9727:     $txt=~tr/a-j/0-9/;
                   9728:     $txt=~tr/K-T/0-9/;
                   9729:     $txt=~tr/k-t/0-9/;
                   9730:     $txt=~tr/U-Z/0-5/;
                   9731:     $txt=~tr/u-z/0-5/;
                   9732:     $txt=~s/\D//g;
1.564     albertel 9733:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      9734:     return int($txt);
1.368     albertel 9735: }
                   9736: 
1.484     albertel 9737: sub numval2 {
                   9738:     my $txt=shift;
                   9739:     $txt=~tr/A-J/0-9/;
                   9740:     $txt=~tr/a-j/0-9/;
                   9741:     $txt=~tr/K-T/0-9/;
                   9742:     $txt=~tr/k-t/0-9/;
                   9743:     $txt=~tr/U-Z/0-5/;
                   9744:     $txt=~tr/u-z/0-5/;
                   9745:     $txt=~s/\D//g;
                   9746:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9747:     my $total;
                   9748:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 9749:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 9750:     return int($total);
                   9751: }
                   9752: 
1.575     albertel 9753: sub numval3 {
                   9754:     use integer;
                   9755:     my $txt=shift;
                   9756:     $txt=~tr/A-J/0-9/;
                   9757:     $txt=~tr/a-j/0-9/;
                   9758:     $txt=~tr/K-T/0-9/;
                   9759:     $txt=~tr/k-t/0-9/;
                   9760:     $txt=~tr/U-Z/0-5/;
                   9761:     $txt=~tr/u-z/0-5/;
                   9762:     $txt=~s/\D//g;
                   9763:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9764:     my $total;
                   9765:     foreach my $val (@txts) { $total+=$val; }
                   9766:     if ($_64bit) { $total=(($total<<32)>>32); }
                   9767:     return $total;
                   9768: }
                   9769: 
1.675     albertel 9770: sub digest {
                   9771:     my ($data)=@_;
                   9772:     my $digest=&Digest::MD5::md5($data);
                   9773:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   9774:     my ($e,$f);
                   9775:     {
                   9776:         use integer;
                   9777:         $e=($a+$b);
                   9778:         $f=($c+$d);
                   9779:         if ($_64bit) {
                   9780:             $e=(($e<<32)>>32);
                   9781:             $f=(($f<<32)>>32);
                   9782:         }
                   9783:     }
                   9784:     if (wantarray) {
                   9785: 	return ($e,$f);
                   9786:     } else {
                   9787: 	my $g;
                   9788: 	{
                   9789: 	    use integer;
                   9790: 	    $g=($e+$f);
                   9791: 	    if ($_64bit) {
                   9792: 		$g=(($g<<32)>>32);
                   9793: 	    }
                   9794: 	}
                   9795: 	return $g;
                   9796:     }
                   9797: }
                   9798: 
1.368     albertel 9799: sub latest_rnd_algorithm_id {
1.675     albertel 9800:     return '64bit5';
1.366     albertel 9801: }
1.32      www      9802: 
1.503     albertel 9803: sub get_rand_alg {
                   9804:     my ($courseid)=@_;
1.790     albertel 9805:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 9806:     if ($courseid) {
1.620     albertel 9807: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 9808:     }
                   9809:     return &latest_rnd_algorithm_id();
                   9810: }
                   9811: 
1.562     albertel 9812: sub validCODE {
                   9813:     my ($CODE)=@_;
                   9814:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   9815:     return 0;
                   9816: }
                   9817: 
1.491     albertel 9818: sub getCODE {
1.620     albertel 9819:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 9820:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   9821: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   9822: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 9823: 	return $Apache::lonhomework::history{'resource.CODE'};
                   9824:     }
                   9825:     return undef;
                   9826: }
1.1133    foxr     9827: #
                   9828: #  Determines the random seed for a specific context:
                   9829: #
                   9830: # parameters:
                   9831: #   symb      - in course context the symb for the seed.
                   9832: #   course_id - The course id of the form domain_coursenum.
                   9833: #   domain    - Domain for the user.
                   9834: #   course    - Course for the user.
                   9835: #   cenv      - environment of the course.
                   9836: #
                   9837: # NOTE:
                   9838: #   All parameters are picked out of the environment if missing
                   9839: #   or not defined.
                   9840: #   If a symb cannot be determined the current time is used instead.
                   9841: #
                   9842: #  For a given well defined symb, courside, domain, username,
                   9843: #  and course environment, the seed is reproducible.
                   9844: #
1.31      www      9845: sub rndseed {
1.1133    foxr     9846:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 9847:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 9848:     if (!defined($symb)) {
1.366     albertel 9849: 	unless ($symb=$wsymb) { return time; }
                   9850:     }
1.1146    foxr     9851:     if (!defined $courseid) { 
                   9852: 	$courseid=$wcourseid; 
                   9853:     }
                   9854:     if (!defined $domain) { $domain=$wdomain; }
                   9855:     if (!defined $username) { $username=$wusername }
1.1133    foxr     9856: 
                   9857:     my $which;
                   9858:     if (defined($cenv->{'rndseed'})) {
                   9859: 	$which = $cenv->{'rndseed'};
                   9860:     } else {
                   9861: 	$which =&get_rand_alg($courseid);
                   9862:     }
1.491     albertel 9863:     if (defined(&getCODE())) {
1.1133    foxr     9864: 
1.675     albertel 9865: 	if ($which eq '64bit5') {
                   9866: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   9867: 	} elsif ($which eq '64bit4') {
1.575     albertel 9868: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   9869: 	} else {
                   9870: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   9871: 	}
1.675     albertel 9872:     } elsif ($which eq '64bit5') {
                   9873: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 9874:     } elsif ($which eq '64bit4') {
                   9875: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 9876:     } elsif ($which eq '64bit3') {
                   9877: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 9878:     } elsif ($which eq '64bit2') {
                   9879: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 9880:     } elsif ($which eq '64bit') {
                   9881: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   9882:     }
                   9883:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   9884: }
                   9885: 
                   9886: sub rndseed_32bit {
                   9887:     my ($symb,$courseid,$domain,$username)=@_;
                   9888:     {
                   9889: 	use integer;
                   9890: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   9891: 	my $symbseed=numval($symb) << 22;
                   9892: 	my $namechck=unpack("%32C*",$username) << 17;
                   9893: 	my $nameseed=numval($username) << 12;
                   9894: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   9895: 	my $courseseed=unpack("%32C*",$courseid);
                   9896: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 9897: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9898: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9899: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 9900: 	return $num;
                   9901:     }
                   9902: }
                   9903: 
                   9904: sub rndseed_64bit {
                   9905:     my ($symb,$courseid,$domain,$username)=@_;
                   9906:     {
                   9907: 	use integer;
                   9908: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   9909: 	my $symbseed=numval($symb) << 10;
                   9910: 	my $namechck=unpack("%32S*",$username);
                   9911: 	
                   9912: 	my $nameseed=numval($username) << 21;
                   9913: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   9914: 	my $courseseed=unpack("%32S*",$courseid);
                   9915: 	
                   9916: 	my $num1=$symbchck+$symbseed+$namechck;
                   9917: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9918: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9919: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9920: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 9921: 	return "$num1,$num2";
1.155     albertel 9922:     }
1.366     albertel 9923: }
                   9924: 
1.443     albertel 9925: sub rndseed_64bit2 {
                   9926:     my ($symb,$courseid,$domain,$username)=@_;
                   9927:     {
                   9928: 	use integer;
                   9929: 	# strings need to be an even # of cahracters long, it it is odd the
                   9930:         # last characters gets thrown away
                   9931: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9932: 	my $symbseed=numval($symb) << 10;
                   9933: 	my $namechck=unpack("%32S*",$username.' ');
                   9934: 	
                   9935: 	my $nameseed=numval($username) << 21;
1.501     albertel 9936: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9937: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9938: 	
                   9939: 	my $num1=$symbchck+$symbseed+$namechck;
                   9940: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9941: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9942: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 9943: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 9944: 	return "$num1,$num2";
                   9945:     }
                   9946: }
                   9947: 
                   9948: sub rndseed_64bit3 {
                   9949:     my ($symb,$courseid,$domain,$username)=@_;
                   9950:     {
                   9951: 	use integer;
                   9952: 	# strings need to be an even # of cahracters long, it it is odd the
                   9953:         # last characters gets thrown away
                   9954: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9955: 	my $symbseed=numval2($symb) << 10;
                   9956: 	my $namechck=unpack("%32S*",$username.' ');
                   9957: 	
                   9958: 	my $nameseed=numval2($username) << 21;
1.443     albertel 9959: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9960: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9961: 	
                   9962: 	my $num1=$symbchck+$symbseed+$namechck;
                   9963: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9964: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9965: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 9966: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      9967: 	
1.503     albertel 9968: 	return "$num1:$num2";
1.443     albertel 9969:     }
                   9970: }
                   9971: 
1.575     albertel 9972: sub rndseed_64bit4 {
                   9973:     my ($symb,$courseid,$domain,$username)=@_;
                   9974:     {
                   9975: 	use integer;
                   9976: 	# strings need to be an even # of cahracters long, it it is odd the
                   9977:         # last characters gets thrown away
                   9978: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9979: 	my $symbseed=numval3($symb) << 10;
                   9980: 	my $namechck=unpack("%32S*",$username.' ');
                   9981: 	
                   9982: 	my $nameseed=numval3($username) << 21;
                   9983: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9984: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9985: 	
                   9986: 	my $num1=$symbchck+$symbseed+$namechck;
                   9987: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9988: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9989: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 9990: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      9991: 	
1.575     albertel 9992: 	return "$num1:$num2";
                   9993:     }
                   9994: }
                   9995: 
1.675     albertel 9996: sub rndseed_64bit5 {
                   9997:     my ($symb,$courseid,$domain,$username)=@_;
                   9998:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   9999:     return "$num1:$num2";
                   10000: }
                   10001: 
1.366     albertel 10002: sub rndseed_CODE_64bit {
                   10003:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 10004:     {
1.366     albertel 10005: 	use integer;
1.443     albertel 10006: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 10007: 	my $symbseed=numval2($symb);
1.491     albertel 10008: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10009: 	my $CODEseed=numval(&getCODE());
1.443     albertel 10010: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 10011: 	my $num1=$symbseed+$CODEchck;
                   10012: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10013: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10014: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 10015: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10016: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 10017: 	return "$num1:$num2";
1.366     albertel 10018:     }
                   10019: }
                   10020: 
1.575     albertel 10021: sub rndseed_CODE_64bit4 {
                   10022:     my ($symb,$courseid,$domain,$username)=@_;
                   10023:     {
                   10024: 	use integer;
                   10025: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   10026: 	my $symbseed=numval3($symb);
                   10027: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10028: 	my $CODEseed=numval3(&getCODE());
                   10029: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10030: 	my $num1=$symbseed+$CODEchck;
                   10031: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10032: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10033: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 10034: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10035: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   10036: 	return "$num1:$num2";
                   10037:     }
                   10038: }
                   10039: 
1.675     albertel 10040: sub rndseed_CODE_64bit5 {
                   10041:     my ($symb,$courseid,$domain,$username)=@_;
                   10042:     my $code = &getCODE();
                   10043:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   10044:     return "$num1:$num2";
                   10045: }
                   10046: 
1.366     albertel 10047: sub setup_random_from_rndseed {
                   10048:     my ($rndseed)=@_;
1.503     albertel 10049:     if ($rndseed =~/([,:])/) {
                   10050: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 10051: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   10052:     } else {
                   10053: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 10054:     }
1.36      albertel 10055: }
                   10056: 
1.474     albertel 10057: sub latest_receipt_algorithm_id {
1.835     albertel 10058:     return 'receipt3';
1.474     albertel 10059: }
                   10060: 
1.480     www      10061: sub recunique {
                   10062:     my $fucourseid=shift;
                   10063:     my $unique;
1.835     albertel 10064:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   10065: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 10066: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      10067:     } else {
                   10068: 	$unique=$perlvar{'lonReceipt'};
                   10069:     }
                   10070:     return unpack("%32C*",$unique);
                   10071: }
                   10072: 
                   10073: sub recprefix {
                   10074:     my $fucourseid=shift;
                   10075:     my $prefix;
1.835     albertel 10076:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   10077: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 10078: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      10079:     } else {
                   10080: 	$prefix=$perlvar{'lonHostID'};
                   10081:     }
                   10082:     return unpack("%32C*",$prefix);
                   10083: }
                   10084: 
1.76      www      10085: sub ireceipt {
1.474     albertel 10086:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 10087: 
                   10088:     my $return =&recprefix($fucourseid).'-';
                   10089: 
                   10090:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   10091: 	$env{'request.state'} eq 'construct') {
                   10092: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   10093: 	return $return;
                   10094:     }
                   10095: 
1.76      www      10096:     my $cuname=unpack("%32C*",$funame);
                   10097:     my $cudom=unpack("%32C*",$fudom);
                   10098:     my $cucourseid=unpack("%32C*",$fucourseid);
                   10099:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      10100:     my $cunique=&recunique($fucourseid);
1.474     albertel 10101:     my $cpart=unpack("%32S*",$part);
1.835     albertel 10102:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   10103: 
1.790     albertel 10104: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 10105: 			       
                   10106: 	$return.= ($cunique%$cuname+
                   10107: 		   $cunique%$cudom+
                   10108: 		   $cusymb%$cuname+
                   10109: 		   $cusymb%$cudom+
                   10110: 		   $cucourseid%$cuname+
                   10111: 		   $cucourseid%$cudom+
                   10112: 		   $cpart%$cuname+
                   10113: 		   $cpart%$cudom);
                   10114:     } else {
                   10115: 	$return.= ($cunique%$cuname+
                   10116: 		   $cunique%$cudom+
                   10117: 		   $cusymb%$cuname+
                   10118: 		   $cusymb%$cudom+
                   10119: 		   $cucourseid%$cuname+
                   10120: 		   $cucourseid%$cudom);
                   10121:     }
                   10122:     return $return;
1.76      www      10123: }
                   10124: 
                   10125: sub receipt {
1.474     albertel 10126:     my ($part)=@_;
1.790     albertel 10127:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 10128:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      10129: }
1.260     ng       10130: 
1.790     albertel 10131: sub whichuser {
                   10132:     my ($passedsymb)=@_;
                   10133:     my ($symb,$courseid,$domain,$name,$publicuser);
                   10134:     if (defined($env{'form.grade_symb'})) {
                   10135: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   10136: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   10137: 	if (!$allowed &&
                   10138: 	    exists($env{'request.course.sec'}) &&
                   10139: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   10140: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   10141: 			      '/'.$env{'request.course.sec'});
                   10142: 	}
                   10143: 	if ($allowed) {
                   10144: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   10145: 	    $courseid=$tmp_courseid;
                   10146: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   10147: 	    ($name)=&get_env_multiple('form.grade_username');
                   10148: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   10149: 	}
                   10150:     }
                   10151:     if (!$passedsymb) {
                   10152: 	$symb=&symbread();
                   10153:     } else {
                   10154: 	$symb=$passedsymb;
                   10155:     }
                   10156:     $courseid=$env{'request.course.id'};
                   10157:     $domain=$env{'user.domain'};
                   10158:     $name=$env{'user.name'};
                   10159:     if ($name eq 'public' && $domain eq 'public') {
                   10160: 	if (!defined($env{'form.username'})) {
                   10161: 	    $env{'form.username'}.=time.rand(10000000);
                   10162: 	}
                   10163: 	$name.=$env{'form.username'};
                   10164:     }
                   10165:     return ($symb,$courseid,$domain,$name,$publicuser);
                   10166: 
                   10167: }
                   10168: 
1.36      albertel 10169: # ------------------------------------------------------------ Serves up a file
1.472     albertel 10170: # returns either the contents of the file or 
                   10171: # -1 if the file doesn't exist
1.481     raeburn  10172: #
                   10173: # if the target is a file that was uploaded via DOCS, 
                   10174: # a check will be made to see if a current copy exists on the local server,
                   10175: # if it does this will be served, otherwise a copy will be retrieved from
                   10176: # the home server for the course and stored in /home/httpd/html/userfiles on
                   10177: # the local server.   
1.472     albertel 10178: 
1.36      albertel 10179: sub getfile {
1.538     albertel 10180:     my ($file) = @_;
1.609     banghart 10181:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 10182:     &repcopy($file);
                   10183:     return &readfile($file);
                   10184: }
                   10185: 
                   10186: sub repcopy_userfile {
                   10187:     my ($file)=@_;
1.1142    raeburn  10188:     my $londocroot = $perlvar{'lonDocRoot'};
                   10189:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
                   10190:     if ($file =~ m{^\Q$londocroot/lonUsers/\E}) { return 'ok'; }
1.538     albertel 10191:     my ($cdom,$cnum,$filename) = 
1.811     albertel 10192: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 10193:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   10194:     if (-e "$file") {
1.828     www      10195: # we already have a local copy, check it out
1.538     albertel 10196: 	my @fileinfo = stat($file);
1.828     www      10197: 	my $rtncode;
                   10198: 	my $info;
1.538     albertel 10199: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 10200: 	if ($lwpresp ne 'ok') {
1.828     www      10201: # there is no such file anymore, even though we had a local copy
1.482     albertel 10202: 	    if ($rtncode eq '404') {
1.538     albertel 10203: 		unlink($file);
1.482     albertel 10204: 	    }
                   10205: 	    return -1;
                   10206: 	}
                   10207: 	if ($info < $fileinfo[9]) {
1.828     www      10208: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  10209: 	    return 'ok';
1.828     www      10210: 	} else {
                   10211: # the file is outdated, get rid of it
                   10212: 	    unlink($file);
1.482     albertel 10213: 	}
1.828     www      10214:     }
                   10215: # one way or the other, at this point, we don't have the file
                   10216: # construct the correct path for the file
                   10217:     my @parts = ($cdom,$cnum); 
                   10218:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   10219: 	push @parts, split(/\//,$1);
                   10220:     }
                   10221:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   10222:     foreach my $part (@parts) {
                   10223: 	$path .= '/'.$part;
                   10224: 	if (!-e $path) {
                   10225: 	    mkdir($path,0770);
1.482     albertel 10226: 	}
                   10227:     }
1.828     www      10228: # now the path exists for sure
                   10229: # get a user agent
                   10230:     my $ua=new LWP::UserAgent;
                   10231:     my $transferfile=$file.'.in.transfer';
                   10232: # FIXME: this should flock
                   10233:     if (-e $transferfile) { return 'ok'; }
                   10234:     my $request;
                   10235:     $uri=~s/^\///;
1.980     raeburn  10236:     my $homeserver = &homeserver($cnum,$cdom);
                   10237:     my $protocol = $protocol{$homeserver};
                   10238:     $protocol = 'http' if ($protocol ne 'https');
                   10239:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      10240:     my $response=$ua->request($request,$transferfile);
                   10241: # did it work?
                   10242:     if ($response->is_error()) {
                   10243: 	unlink($transferfile);
                   10244: 	&logthis("Userfile repcopy failed for $uri");
                   10245: 	return -1;
                   10246:     }
                   10247: # worked, rename the transfer file
                   10248:     rename($transferfile,$file);
1.607     raeburn  10249:     return 'ok';
1.481     raeburn  10250: }
                   10251: 
1.517     albertel 10252: sub tokenwrapper {
                   10253:     my $uri=shift;
1.980     raeburn  10254:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 10255:     $uri=~s|^/||;
1.620     albertel 10256:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 10257:     my $token=$1;
1.552     albertel 10258:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   10259:     if ($udom && $uname && $file) {
                   10260: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  10261:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  10262:         my $homeserver = &homeserver($uname,$udom);
                   10263:         my $protocol = $protocol{$homeserver};
                   10264:         $protocol = 'http' if ($protocol ne 'https');
                   10265:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 10266:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   10267:                                '&tokenissued='.$perlvar{'lonHostID'};
                   10268:     } else {
                   10269:         return '/adm/notfound.html';
                   10270:     }
                   10271: }
                   10272: 
1.828     www      10273: # call with reqtype HEAD: get last modification time
                   10274: # call with reqtype GET: get the file contents
                   10275: # Do not call this with reqtype GET for large files! It loads everything into memory
                   10276: #
1.481     raeburn  10277: sub getuploaded {
                   10278:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   10279:     $uri=~s/^\///;
1.980     raeburn  10280:     my $homeserver = &homeserver($cnum,$cdom);
                   10281:     my $protocol = $protocol{$homeserver};
                   10282:     $protocol = 'http' if ($protocol ne 'https');
                   10283:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  10284:     my $ua=new LWP::UserAgent;
                   10285:     my $request=new HTTP::Request($reqtype,$uri);
                   10286:     my $response=$ua->request($request);
                   10287:     $$rtncode = $response->code;
1.482     albertel 10288:     if (! $response->is_success()) {
                   10289: 	return 'failed';
                   10290:     }      
                   10291:     if ($reqtype eq 'HEAD') {
1.486     www      10292: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 10293:     } elsif ($reqtype eq 'GET') {
                   10294: 	$$info = $response->content;
1.472     albertel 10295:     }
1.482     albertel 10296:     return 'ok';
1.36      albertel 10297: }
                   10298: 
1.481     raeburn  10299: sub readfile {
                   10300:     my $file = shift;
                   10301:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   10302:     my $fh;
                   10303:     open($fh,"<$file");
                   10304:     my $a='';
1.800     albertel 10305:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  10306:     return $a;
                   10307: }
                   10308: 
1.36      albertel 10309: sub filelocation {
1.590     banghart 10310:     my ($dir,$file) = @_;
                   10311:     my $location;
                   10312:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 10313: 
                   10314:     if ($file =~ m-^/adm/-) {
                   10315: 	$file=~s-^/adm/wrapper/-/-;
                   10316: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   10317:     }
1.882     albertel 10318: 
1.1139    www      10319:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  10320:         $location = $file;
1.609     banghart 10321:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 10322:         my ($udom,$uname,$filename)=
1.811     albertel 10323:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 10324:         my $home=&homeserver($uname,$udom);
                   10325:         my $is_me=0;
                   10326:         my @ids=&current_machine_ids();
                   10327:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   10328:         if ($is_me) {
1.1117    foxr     10329:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 10330:         } else {
                   10331:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   10332:   	      $udom.'/'.$uname.'/'.$filename;
                   10333:         }
1.882     albertel 10334:     } elsif ($file =~ m-^/adm/-) {
                   10335: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 10336:     } else {
                   10337:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      10338:         $file=~s:^/(res|priv)/:/:;
                   10339:         my $space=$1;
1.590     banghart 10340:         if ( !( $file =~ m:^/:) ) {
                   10341:             $location = $dir. '/'.$file;
                   10342:         } else {
1.1142    raeburn  10343:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 10344:         }
1.59      albertel 10345:     }
1.590     banghart 10346:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 10347:     while ($location=~m{/\.\./}) {
                   10348: 	if ($location =~ m{/[^/]+/\.\./}) {
                   10349: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   10350: 	} else {
                   10351: 	    $location=~ s{/\.\./}{/}g;
                   10352: 	}
                   10353:     } #remove dir/..
1.590     banghart 10354:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   10355:     return $location;
1.46      www      10356: }
1.36      albertel 10357: 
1.46      www      10358: sub hreflocation {
                   10359:     my ($dir,$file)=@_;
1.980     raeburn  10360:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 10361: 	$file=filelocation($dir,$file);
1.700     albertel 10362:     } elsif ($file=~m-^/adm/-) {
                   10363: 	$file=~s-^/adm/wrapper/-/-;
                   10364: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 10365:     }
                   10366:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   10367: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   10368:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  10369: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   10370: 	        {/uploaded/$1/$2/}x;
1.46      www      10371:     }
1.913     albertel 10372:     if ($file=~ m{^/userfiles/}) {
                   10373: 	$file =~ s{^/userfiles/}{/uploaded/};
                   10374:     }
1.462     albertel 10375:     return $file;
1.465     albertel 10376: }
                   10377: 
1.1139    www      10378: 
                   10379: 
                   10380: 
                   10381: 
1.465     albertel 10382: sub current_machine_domains {
1.853     albertel 10383:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   10384: }
                   10385: 
                   10386: sub machine_domains {
                   10387:     my ($hostname) = @_;
1.465     albertel 10388:     my @domains;
1.838     albertel 10389:     my %hostname = &all_hostnames();
1.465     albertel 10390:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  10391: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 10392: 	if ($hostname eq $name) {
1.844     albertel 10393: 	    push(@domains,&host_domain($id));
1.465     albertel 10394: 	}
                   10395:     }
                   10396:     return @domains;
                   10397: }
                   10398: 
                   10399: sub current_machine_ids {
1.853     albertel 10400:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   10401: }
                   10402: 
                   10403: sub machine_ids {
                   10404:     my ($hostname) = @_;
                   10405:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 10406:     my @ids;
1.888     albertel 10407:     my %name_to_host = &all_names();
1.889     albertel 10408:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   10409: 	return @{ $name_to_host{$hostname} };
                   10410:     }
                   10411:     return;
1.31      www      10412: }
                   10413: 
1.824     raeburn  10414: sub additional_machine_domains {
                   10415:     my @domains;
                   10416:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   10417:     while( my $line = <$fh>) {
                   10418:         $line =~ s/\s//g;
                   10419:         push(@domains,$line);
                   10420:     }
                   10421:     return @domains;
                   10422: }
                   10423: 
                   10424: sub default_login_domain {
                   10425:     my $domain = $perlvar{'lonDefDomain'};
                   10426:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   10427:     foreach my $posdom (&current_machine_domains(),
                   10428:                         &additional_machine_domains()) {
                   10429:         if (lc($posdom) eq lc($testdomain)) {
                   10430:             $domain=$posdom;
                   10431:             last;
                   10432:         }
                   10433:     }
                   10434:     return $domain;
                   10435: }
                   10436: 
1.31      www      10437: # ------------------------------------------------------------- Declutters URLs
                   10438: 
                   10439: sub declutter {
                   10440:     my $thisfn=shift;
1.569     albertel 10441:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 10442:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      10443:     $thisfn=~s/^\///;
1.697     albertel 10444:     $thisfn=~s|^adm/wrapper/||;
                   10445:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      10446:     $thisfn=~s/^res\///;
1.1032    raeburn  10447:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   10448:         $thisfn=~s/\?.+$//;
                   10449:     }
1.268     www      10450:     return $thisfn;
                   10451: }
                   10452: 
                   10453: # ------------------------------------------------------------- Clutter up URLs
                   10454: 
                   10455: sub clutter {
                   10456:     my $thisfn='/'.&declutter(shift);
1.887     albertel 10457:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 10458: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      10459:        $thisfn='/res'.$thisfn; 
                   10460:     }
1.1031    raeburn  10461:     if ($thisfn !~m|^/adm|) {
                   10462: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 10463: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 10464: 	} else {
                   10465: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   10466: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 10467: 	    if ($embstyle eq 'ssi'
                   10468: 		|| ($embstyle eq 'hdn')
                   10469: 		|| ($embstyle eq 'rat')
                   10470: 		|| ($embstyle eq 'prv')
                   10471: 		|| ($embstyle eq 'ign')) {
                   10472: 		#do nothing with these
                   10473: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 10474: 		|| ($embstyle eq 'emb')
                   10475: 		|| ($embstyle eq 'wrp')) {
                   10476: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 10477: 	    } elsif ($embstyle eq 'unk'
                   10478: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 10479: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 10480: 	    } else {
1.718     www      10481: #		&logthis("Got a blank emb style");
1.695     albertel 10482: 	    }
1.694     albertel 10483: 	}
                   10484:     }
1.31      www      10485:     return $thisfn;
1.12      www      10486: }
                   10487: 
1.787     albertel 10488: sub clutter_with_no_wrapper {
                   10489:     my $uri = &clutter(shift);
                   10490:     if ($uri =~ m-^/adm/-) {
                   10491: 	$uri =~ s-^/adm/wrapper/-/-;
                   10492: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   10493:     }
                   10494:     return $uri;
                   10495: }
                   10496: 
1.557     albertel 10497: sub freeze_escape {
                   10498:     my ($value)=@_;
                   10499:     if (ref($value)) {
                   10500: 	$value=&nfreeze($value);
                   10501: 	return '__FROZEN__'.&escape($value);
                   10502:     }
                   10503:     return &escape($value);
                   10504: }
                   10505: 
1.11      www      10506: 
1.557     albertel 10507: sub thaw_unescape {
                   10508:     my ($value)=@_;
                   10509:     if ($value =~ /^__FROZEN__/) {
                   10510: 	substr($value,0,10,undef);
                   10511: 	$value=&unescape($value);
                   10512: 	return &thaw($value);
                   10513:     }
                   10514:     return &unescape($value);
                   10515: }
                   10516: 
1.436     albertel 10517: sub correct_line_ends {
                   10518:     my ($result)=@_;
                   10519:     $$result =~s/\r\n/\n/mg;
                   10520:     $$result =~s/\r/\n/mg;
1.415     albertel 10521: }
1.1       albertel 10522: # ================================================================ Main Program
                   10523: 
1.184     www      10524: sub goodbye {
1.204     albertel 10525:    &logthis("Starting Shut down");
1.443     albertel 10526: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 10527:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 10528: #converted
1.599     albertel 10529: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 10530:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   10531: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   10532: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 10533: #1.1 only
1.870     albertel 10534: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   10535: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   10536: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   10537: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   10538:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 10539:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   10540:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      10541:    &flushcourselogs();
                   10542:    &logthis("Shutting down");
                   10543: }
                   10544: 
1.852     albertel 10545: sub get_dns {
1.869     albertel 10546:     my ($url,$func,$ignore_cache) = @_;
                   10547:     if (!$ignore_cache) {
                   10548: 	my ($content,$cached)=
                   10549: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   10550: 	if ($cached) {
                   10551: 	    &$func($content);
                   10552: 	    return;
                   10553: 	}
                   10554:     }
                   10555: 
                   10556:     my %alldns;
1.852     albertel 10557:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10558:     foreach my $dns (<$config>) {
                   10559: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  10560:         my $line = $1;
                   10561:         my ($host,$protocol) = split(/:/,$line);
                   10562:         if ($protocol ne 'https') {
                   10563:             $protocol = 'http';
                   10564:         }
                   10565: 	$alldns{$host} = $protocol;
1.869     albertel 10566:     }
                   10567:     while (%alldns) {
                   10568: 	my ($dns) = keys(%alldns);
1.852     albertel 10569: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  10570:         $ua->timeout(30);
1.979     raeburn  10571: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 10572: 	my $response=$ua->request($request);
1.979     raeburn  10573:         delete($alldns{$dns});
1.852     albertel 10574: 	next if ($response->is_error());
                   10575: 	my @content = split("\n",$response->content);
1.869     albertel 10576: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 10577: 	&$func(\@content);
1.869     albertel 10578: 	return;
1.852     albertel 10579:     }
                   10580:     close($config);
1.871     albertel 10581:     my $which = (split('/',$url))[3];
                   10582:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   10583:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 10584:     my @content = <$config>;
                   10585:     &$func(\@content);
                   10586:     return;
1.852     albertel 10587: }
1.327     albertel 10588: # ------------------------------------------------------------ Read domain file
                   10589: {
1.852     albertel 10590:     my $loaded;
1.846     albertel 10591:     my %domain;
                   10592: 
1.852     albertel 10593:     sub parse_domain_tab {
                   10594: 	my ($lines) = @_;
                   10595: 	foreach my $line (@$lines) {
                   10596: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      10597: 
1.846     albertel 10598: 	    chomp($line);
1.852     albertel 10599: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 10600: 	    my %this_domain;
                   10601: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   10602: 			       'lang_def', 'city', 'longi', 'lati',
                   10603: 			       'primary') {
                   10604: 		$this_domain{$field} = shift(@elements);
                   10605: 	    }
                   10606: 	    $domain{$name} = \%this_domain;
1.852     albertel 10607: 	}
                   10608:     }
1.864     albertel 10609: 
                   10610:     sub reset_domain_info {
                   10611: 	undef($loaded);
                   10612: 	undef(%domain);
                   10613:     }
                   10614: 
1.852     albertel 10615:     sub load_domain_tab {
1.869     albertel 10616: 	my ($ignore_cache) = @_;
                   10617: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 10618: 	my $fh;
                   10619: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   10620: 	    my @lines = <$fh>;
                   10621: 	    &parse_domain_tab(\@lines);
1.448     albertel 10622: 	}
1.852     albertel 10623: 	close($fh);
                   10624: 	$loaded = 1;
1.327     albertel 10625:     }
1.846     albertel 10626: 
                   10627:     sub domain {
1.852     albertel 10628: 	&load_domain_tab() if (!$loaded);
                   10629: 
1.846     albertel 10630: 	my ($name,$what) = @_;
                   10631: 	return if ( !exists($domain{$name}) );
                   10632: 
                   10633: 	if (!$what) {
                   10634: 	    return $domain{$name}{'description'};
                   10635: 	}
                   10636: 	return $domain{$name}{$what};
                   10637:     }
1.974     raeburn  10638: 
                   10639:     sub domain_info {
                   10640:         &load_domain_tab() if (!$loaded);
                   10641:         return %domain;
                   10642:     }
                   10643: 
1.327     albertel 10644: }
                   10645: 
                   10646: 
1.1       albertel 10647: # ------------------------------------------------------------- Read hosts file
                   10648: {
1.838     albertel 10649:     my %hostname;
1.844     albertel 10650:     my %hostdom;
1.845     albertel 10651:     my %libserv;
1.852     albertel 10652:     my $loaded;
1.888     albertel 10653:     my %name_to_host;
1.1074    raeburn  10654:     my %internetdom;
1.1107    raeburn  10655:     my %LC_dns_serv;
1.852     albertel 10656: 
                   10657:     sub parse_hosts_tab {
                   10658: 	my ($file) = @_;
                   10659: 	foreach my $configline (@$file) {
                   10660: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  10661:             chomp($configline);
                   10662: 	    if ($configline =~ /^\^/) {
                   10663:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   10664:                     $LC_dns_serv{$1} = 1;
                   10665:                 }
                   10666:                 next;
                   10667:             }
1.1074    raeburn  10668: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 10669: 	    $name=~s/\s//g;
                   10670: 	    if ($id && $domain && $role && $name) {
                   10671: 		$hostname{$id}=$name;
1.888     albertel 10672: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 10673: 		$hostdom{$id}=$domain;
                   10674: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  10675:                 if (defined($protocol)) {
                   10676:                     if ($protocol eq 'https') {
                   10677:                         $protocol{$id} = $protocol;
                   10678:                     } else {
                   10679:                         $protocol{$id} = 'http'; 
                   10680:                     }
1.968     raeburn  10681:                 } else {
1.969     raeburn  10682:                     $protocol{$id} = 'http';
1.968     raeburn  10683:                 }
1.1074    raeburn  10684:                 if (defined($intdom)) {
                   10685:                     $internetdom{$id} = $intdom;
                   10686:                 }
1.852     albertel 10687: 	    }
                   10688: 	}
                   10689:     }
1.864     albertel 10690:     
                   10691:     sub reset_hosts_info {
1.897     albertel 10692: 	&purge_remembered();
1.864     albertel 10693: 	&reset_domain_info();
                   10694: 	&reset_hosts_ip_info();
1.892     albertel 10695: 	undef(%name_to_host);
1.864     albertel 10696: 	undef(%hostname);
                   10697: 	undef(%hostdom);
                   10698: 	undef(%libserv);
                   10699: 	undef($loaded);
                   10700:     }
1.1       albertel 10701: 
1.852     albertel 10702:     sub load_hosts_tab {
1.869     albertel 10703: 	my ($ignore_cache) = @_;
                   10704: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 10705: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10706: 	my @config = <$config>;
                   10707: 	&parse_hosts_tab(\@config);
                   10708: 	close($config);
                   10709: 	$loaded=1;
1.1       albertel 10710:     }
1.852     albertel 10711: 
1.838     albertel 10712:     sub hostname {
1.852     albertel 10713: 	&load_hosts_tab() if (!$loaded);
                   10714: 
1.838     albertel 10715: 	my ($lonid) = @_;
                   10716: 	return $hostname{$lonid};
                   10717:     }
1.845     albertel 10718: 
1.838     albertel 10719:     sub all_hostnames {
1.852     albertel 10720: 	&load_hosts_tab() if (!$loaded);
                   10721: 
1.838     albertel 10722: 	return %hostname;
                   10723:     }
1.845     albertel 10724: 
1.888     albertel 10725:     sub all_names {
                   10726: 	&load_hosts_tab() if (!$loaded);
                   10727: 
                   10728: 	return %name_to_host;
                   10729:     }
                   10730: 
1.974     raeburn  10731:     sub all_host_domain {
                   10732:         &load_hosts_tab() if (!$loaded);
                   10733:         return %hostdom;
                   10734:     }
                   10735: 
1.845     albertel 10736:     sub is_library {
1.852     albertel 10737: 	&load_hosts_tab() if (!$loaded);
                   10738: 
1.845     albertel 10739: 	return exists($libserv{$_[0]});
                   10740:     }
                   10741: 
                   10742:     sub all_library {
1.852     albertel 10743: 	&load_hosts_tab() if (!$loaded);
                   10744: 
1.845     albertel 10745: 	return %libserv;
                   10746:     }
                   10747: 
1.1062    droeschl 10748:     sub unique_library {
                   10749: 	#2x reverse removes all hostnames that appear more than once
                   10750:         my %unique = reverse &all_library();
                   10751:         return reverse %unique;
                   10752:     }
                   10753: 
1.841     albertel 10754:     sub get_servers {
1.852     albertel 10755: 	&load_hosts_tab() if (!$loaded);
                   10756: 
1.841     albertel 10757: 	my ($domain,$type) = @_;
                   10758: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   10759: 	                                          : %hostname;
                   10760: 	my %result;
1.842     albertel 10761: 	if (ref($domain) eq 'ARRAY') {
                   10762: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 10763: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 10764: 		    $result{$host} = $hostname;
                   10765: 		}
                   10766: 	    }
                   10767: 	} else {
                   10768: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   10769: 		if ($hostdom{$host} eq $domain) {
                   10770: 		    $result{$host} = $hostname;
                   10771: 		}
1.841     albertel 10772: 	    }
                   10773: 	}
                   10774: 	return %result;
                   10775:     }
1.845     albertel 10776: 
1.1062    droeschl 10777:     sub get_unique_servers {
                   10778:         my %unique = reverse &get_servers(@_);
                   10779: 	return reverse %unique;
                   10780:     }
                   10781: 
1.844     albertel 10782:     sub host_domain {
1.852     albertel 10783: 	&load_hosts_tab() if (!$loaded);
                   10784: 
1.844     albertel 10785: 	my ($lonid) = @_;
                   10786: 	return $hostdom{$lonid};
                   10787:     }
                   10788: 
1.841     albertel 10789:     sub all_domains {
1.852     albertel 10790: 	&load_hosts_tab() if (!$loaded);
                   10791: 
1.841     albertel 10792: 	my %seen;
                   10793: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   10794: 	return @uniq;
                   10795:     }
1.1074    raeburn  10796: 
                   10797:     sub internet_dom {
                   10798:         &load_hosts_tab() if (!$loaded);
                   10799: 
                   10800:         my ($lonid) = @_;
                   10801:         return $internetdom{$lonid};
                   10802:     }
1.1107    raeburn  10803: 
                   10804:     sub is_LC_dns {
                   10805:         &load_hosts_tab() if (!$loaded);
                   10806: 
                   10807:         my ($hostname) = @_;
                   10808:         return exists($LC_dns_serv{$hostname});
                   10809:     }
                   10810: 
1.1       albertel 10811: }
                   10812: 
1.847     albertel 10813: { 
                   10814:     my %iphost;
1.856     albertel 10815:     my %name_to_ip;
                   10816:     my %lonid_to_ip;
1.869     albertel 10817: 
1.847     albertel 10818:     sub get_hosts_from_ip {
                   10819: 	my ($ip) = @_;
                   10820: 	my %iphosts = &get_iphost();
                   10821: 	if (ref($iphosts{$ip})) {
                   10822: 	    return @{$iphosts{$ip}};
                   10823: 	}
                   10824: 	return;
1.839     albertel 10825:     }
1.864     albertel 10826:     
                   10827:     sub reset_hosts_ip_info {
                   10828: 	undef(%iphost);
                   10829: 	undef(%name_to_ip);
                   10830: 	undef(%lonid_to_ip);
                   10831:     }
1.856     albertel 10832: 
                   10833:     sub get_host_ip {
                   10834: 	my ($lonid) = @_;
                   10835: 	if (exists($lonid_to_ip{$lonid})) {
                   10836: 	    return $lonid_to_ip{$lonid};
                   10837: 	}
                   10838: 	my $name=&hostname($lonid);
                   10839:    	my $ip = gethostbyname($name);
                   10840: 	return if (!$ip || length($ip) ne 4);
                   10841: 	$ip=inet_ntoa($ip);
                   10842: 	$name_to_ip{$name}   = $ip;
                   10843: 	$lonid_to_ip{$lonid} = $ip;
                   10844: 	return $ip;
                   10845:     }
1.847     albertel 10846:     
                   10847:     sub get_iphost {
1.869     albertel 10848: 	my ($ignore_cache) = @_;
1.894     albertel 10849: 
1.869     albertel 10850: 	if (!$ignore_cache) {
                   10851: 	    if (%iphost) {
                   10852: 		return %iphost;
                   10853: 	    }
                   10854: 	    my ($ip_info,$cached)=
                   10855: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   10856: 	    if ($cached) {
                   10857: 		%iphost      = %{$ip_info->[0]};
                   10858: 		%name_to_ip  = %{$ip_info->[1]};
                   10859: 		%lonid_to_ip = %{$ip_info->[2]};
                   10860: 		return %iphost;
                   10861: 	    }
                   10862: 	}
1.894     albertel 10863: 
                   10864: 	# get yesterday's info for fallback
                   10865: 	my %old_name_to_ip;
                   10866: 	my ($ip_info,$cached)=
                   10867: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   10868: 	if ($cached) {
                   10869: 	    %old_name_to_ip = %{$ip_info->[1]};
                   10870: 	}
                   10871: 
1.888     albertel 10872: 	my %name_to_host = &all_names();
                   10873: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 10874: 	    my $ip;
                   10875: 	    if (!exists($name_to_ip{$name})) {
                   10876: 		$ip = gethostbyname($name);
                   10877: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 10878: 		    if (defined($old_name_to_ip{$name})) {
                   10879: 			$ip = $old_name_to_ip{$name};
                   10880: 			&logthis("Can't find $name defaulting to old $ip");
                   10881: 		    } else {
                   10882: 			&logthis("Name $name no IP found");
                   10883: 			next;
                   10884: 		    }
                   10885: 		} else {
                   10886: 		    $ip=inet_ntoa($ip);
1.847     albertel 10887: 		}
                   10888: 		$name_to_ip{$name} = $ip;
                   10889: 	    } else {
                   10890: 		$ip = $name_to_ip{$name};
1.653     albertel 10891: 	    }
1.888     albertel 10892: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   10893: 		$lonid_to_ip{$id} = $ip;
                   10894: 	    }
                   10895: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 10896: 	}
1.869     albertel 10897: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   10898: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 10899: 				      48*60*60);
1.869     albertel 10900: 
1.847     albertel 10901: 	return %iphost;
1.598     albertel 10902:     }
                   10903: 
1.992     raeburn  10904:     #
                   10905:     #  Given a DNS returns the loncapa host name for that DNS 
                   10906:     # 
                   10907:     sub host_from_dns {
                   10908:         my ($dns) = @_;
                   10909:         my @hosts;
                   10910:         my $ip;
                   10911: 
1.993     raeburn  10912:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  10913:             $ip = $name_to_ip{$dns};
                   10914:         }
                   10915:         if (!$ip) {
                   10916:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   10917:             if (length($ip) == 4) { 
                   10918: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   10919:             }
                   10920:         }
                   10921:         if ($ip) {
                   10922: 	    @hosts = get_hosts_from_ip($ip);
                   10923: 	    return $hosts[0];
                   10924:         }
                   10925:         return undef;
1.986     foxr     10926:     }
1.992     raeburn  10927: 
1.1074    raeburn  10928:     sub get_internet_names {
                   10929:         my ($lonid) = @_;
                   10930:         return if ($lonid eq '');
                   10931:         my ($idnref,$cached)=
                   10932:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   10933:         if ($cached) {
                   10934:             return $idnref;
                   10935:         }
                   10936:         my $ip = &get_host_ip($lonid);
                   10937:         my @hosts = &get_hosts_from_ip($ip);
                   10938:         my %iphost = &get_iphost();
                   10939:         my (@idns,%seen);
                   10940:         foreach my $id (@hosts) {
                   10941:             my $dom = &host_domain($id);
                   10942:             my $prim_id = &domain($dom,'primary');
                   10943:             my $prim_ip = &get_host_ip($prim_id);
                   10944:             next if ($seen{$prim_ip});
                   10945:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   10946:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   10947:                     my $intdom = &internet_dom($id);
                   10948:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   10949:                         push(@idns,$intdom);
                   10950:                     }
                   10951:                 }
                   10952:             }
                   10953:             $seen{$prim_ip} = 1;
                   10954:         }
                   10955:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   10956:     }
                   10957: 
1.986     foxr     10958: }
                   10959: 
1.1079    raeburn  10960: sub all_loncaparevs {
                   10961:     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);
                   10962: }
                   10963: 
1.862     albertel 10964: BEGIN {
                   10965: 
                   10966: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   10967:     unless ($readit) {
                   10968: {
                   10969:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   10970:     %perlvar = (%perlvar,%{$configvars});
                   10971: }
                   10972: 
                   10973: 
1.1       albertel 10974: # ------------------------------------------------------ Read spare server file
                   10975: {
1.448     albertel 10976:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 10977: 
                   10978:     while (my $configline=<$config>) {
                   10979:        chomp($configline);
1.284     matthew  10980:        if ($configline) {
1.784     albertel 10981: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 10982: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 10983: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 10984:        }
                   10985:     }
1.448     albertel 10986:     close($config);
1.1       albertel 10987: }
1.11      www      10988: # ------------------------------------------------------------ Read permissions
                   10989: {
1.448     albertel 10990:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      10991: 
                   10992:     while (my $configline=<$config>) {
1.448     albertel 10993: 	chomp($configline);
                   10994: 	if ($configline) {
                   10995: 	    my ($role,$perm)=split(/ /,$configline);
                   10996: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   10997: 	}
1.11      www      10998:     }
1.448     albertel 10999:     close($config);
1.11      www      11000: }
                   11001: 
                   11002: # -------------------------------------------- Read plain texts for permissions
                   11003: {
1.448     albertel 11004:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      11005: 
                   11006:     while (my $configline=<$config>) {
1.448     albertel 11007: 	chomp($configline);
                   11008: 	if ($configline) {
1.742     raeburn  11009: 	    my ($short,@plain)=split(/:/,$configline);
                   11010:             %{$prp{$short}} = ();
                   11011: 	    if (@plain > 0) {
                   11012:                 $prp{$short}{'std'} = $plain[0];
                   11013:                 for (my $i=1; $i<@plain; $i++) {
                   11014:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   11015:                 }
                   11016:             }
1.448     albertel 11017: 	}
1.135     www      11018:     }
1.448     albertel 11019:     close($config);
1.135     www      11020: }
                   11021: 
                   11022: # ---------------------------------------------------------- Read package table
                   11023: {
1.448     albertel 11024:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      11025: 
                   11026:     while (my $configline=<$config>) {
1.483     albertel 11027: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 11028: 	chomp($configline);
                   11029: 	my ($short,$plain)=split(/:/,$configline);
                   11030: 	my ($pack,$name)=split(/\&/,$short);
                   11031: 	if ($plain ne '') {
                   11032: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   11033: 	    $packagetab{$short}=$plain; 
                   11034: 	}
1.11      www      11035:     }
1.448     albertel 11036:     close($config);
1.329     matthew  11037: }
                   11038: 
1.1073    raeburn  11039: # ---------------------------------------------------------- Read loncaparev table
                   11040: {
                   11041:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   11042:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   11043:             while (my $configline=<$config>) {
                   11044:                 chomp($configline);
                   11045:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   11046:                 $loncaparevs{$hostid}=$loncaparev;
                   11047:             }
                   11048:             close($config);
                   11049:         }
                   11050:     }
                   11051: }
                   11052: 
1.1074    raeburn  11053: # ---------------------------------------------------------- Read serverhostID table
                   11054: {
                   11055:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   11056:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   11057:             while (my $configline=<$config>) {
                   11058:                 chomp($configline);
                   11059:                 my ($name,$id)=split(/:/,$configline);
                   11060:                 $serverhomeIDs{$name}=$id;
                   11061:             }
                   11062:             close($config);
                   11063:         }
                   11064:     }
                   11065: }
                   11066: 
1.1079    raeburn  11067: {
                   11068:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   11069:     if (-e $file) {
                   11070:         my $parser = HTML::LCParser->new($file);
                   11071:         while (my $token = $parser->get_token()) {
                   11072:             if ($token->[0] eq 'S') {
                   11073:                 my $item = $token->[1];
                   11074:                 my $name = $token->[2]{'name'};
                   11075:                 my $value = $token->[2]{'value'};
                   11076:                 if ($item ne '' && $name ne '' && $value ne '') {
                   11077:                     my $release = $parser->get_text();
                   11078:                     $release =~ s/(^\s*|\s*$ )//gx;
                   11079:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   11080:                 }
                   11081:             }
                   11082:         }
                   11083:     }
1.1073    raeburn  11084: }
                   11085: 
1.1138    raeburn  11086: # ---------------------------------------------------------- Read managers table
                   11087: {
                   11088:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   11089:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   11090:             while (my $configline=<$config>) {
                   11091:                 chomp($configline);
                   11092:                 next if ($configline =~ /^\#/);
                   11093:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   11094:                     $managerstab{$configline} = 1;
                   11095:                 }
                   11096:             }
                   11097:             close($config);
                   11098:         }
                   11099:     }
                   11100: }
                   11101: 
1.329     matthew  11102: # ------------- set up temporary directory
                   11103: {
1.1117    foxr     11104:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  11105: 
1.11      www      11106: }
                   11107: 
1.794     albertel 11108: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   11109: 				'compress_threshold'=> 20_000,
                   11110:  			        });
1.185     www      11111: 
1.281     www      11112: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      11113: $dumpcount=0;
1.958     www      11114: $locknum=0;
1.22      www      11115: 
1.163     harris41 11116: &logtouch();
1.672     albertel 11117: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      11118: $readit=1;
1.564     albertel 11119:     {
                   11120: 	use integer;
                   11121: 	my $test=(2**32)+1;
1.568     albertel 11122: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 11123: 	&logthis(" Detected 64bit platform ($_64bit)");
                   11124:     }
1.195     www      11125: }
1.1       albertel 11126: }
1.179     www      11127: 
1.1       albertel 11128: 1;
1.191     harris41 11129: __END__
                   11130: 
1.243     albertel 11131: =pod
                   11132: 
1.191     harris41 11133: =head1 NAME
                   11134: 
1.243     albertel 11135: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 11136: 
                   11137: =head1 SYNOPSIS
                   11138: 
1.243     albertel 11139: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 11140: 
                   11141:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   11142: 
1.243     albertel 11143: Common parameters:
                   11144: 
                   11145: =over 4
                   11146: 
                   11147: =item *
                   11148: 
                   11149: $uname : an internal username (if $cname expecting a course Id specifically)
                   11150: 
                   11151: =item *
                   11152: 
                   11153: $udom : a domain (if $cdom expecting a course's domain specifically)
                   11154: 
                   11155: =item *
                   11156: 
                   11157: $symb : a resource instance identifier
                   11158: 
                   11159: =item *
                   11160: 
                   11161: $namespace : the name of a .db file that contains the data needed or
                   11162: being set.
                   11163: 
                   11164: =back
                   11165: 
1.394     bowersj2 11166: =head1 OVERVIEW
1.191     harris41 11167: 
1.394     bowersj2 11168: lonnet provides subroutines which interact with the
                   11169: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   11170: about classes, users, and resources.
1.243     albertel 11171: 
                   11172: For many of these objects you can also use this to store data about
                   11173: them or modify them in various ways.
1.191     harris41 11174: 
1.394     bowersj2 11175: =head2 Symbs
1.191     harris41 11176: 
1.394     bowersj2 11177: To identify a specific instance of a resource, LON-CAPA uses symbols
                   11178: or "symbs"X<symb>. These identifiers are built from the URL of the
                   11179: map, the resource number of the resource in the map, and the URL of
                   11180: the resource itself. The latter is somewhat redundant, but might help
                   11181: if maps change.
                   11182: 
                   11183: An example is
                   11184: 
                   11185:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   11186: 
                   11187: The respective map entry is
                   11188: 
                   11189:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   11190:   title="Problem 2">
                   11191:  </resource>
                   11192: 
                   11193: Symbs are used by the random number generator, as well as to store and
                   11194: restore data specific to a certain instance of for example a problem.
                   11195: 
                   11196: =head2 Storing And Retrieving Data
                   11197: 
                   11198: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   11199: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   11200: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   11201: is is the non-critical message twin of cstore. These functions are for
                   11202: handlers to store a perl hash to a user's permanent data space in an
                   11203: easy manner, and to retrieve it again on another call. It is expected
                   11204: that a handler would use this once at the beginning to retrieve data,
                   11205: and then again once at the end to send only the new data back.
                   11206: 
                   11207: The data is stored in the user's data directory on the user's
                   11208: homeserver under the ID of the course.
                   11209: 
                   11210: The hash that is returned by restore will have all of the previous
                   11211: value for all of the elements of the hash.
                   11212: 
                   11213: Example:
                   11214: 
                   11215:  #creating a hash
                   11216:  my %hash;
                   11217:  $hash{'foo'}='bar';
                   11218: 
                   11219:  #storing it
                   11220:  &Apache::lonnet::cstore(\%hash);
                   11221: 
                   11222:  #changing a value
                   11223:  $hash{'foo'}='notbar';
                   11224: 
                   11225:  #adding a new value
                   11226:  $hash{'bar'}='foo';
                   11227:  &Apache::lonnet::cstore(\%hash);
                   11228: 
                   11229:  #retrieving the hash
                   11230:  my %history=&Apache::lonnet::restore();
                   11231: 
                   11232:  #print the hash
                   11233:  foreach my $key (sort(keys(%history))) {
                   11234:    print("\%history{$key} = $history{$key}");
                   11235:  }
                   11236: 
                   11237: Will print out:
1.191     harris41 11238: 
1.394     bowersj2 11239:  %history{1:foo} = bar
                   11240:  %history{1:keys} = foo:timestamp
                   11241:  %history{1:timestamp} = 990455579
                   11242:  %history{2:bar} = foo
                   11243:  %history{2:foo} = notbar
                   11244:  %history{2:keys} = foo:bar:timestamp
                   11245:  %history{2:timestamp} = 990455580
                   11246:  %history{bar} = foo
                   11247:  %history{foo} = notbar
                   11248:  %history{timestamp} = 990455580
                   11249:  %history{version} = 2
                   11250: 
                   11251: Note that the special hash entries C<keys>, C<version> and
                   11252: C<timestamp> were added to the hash. C<version> will be equal to the
                   11253: total number of versions of the data that have been stored. The
                   11254: C<timestamp> attribute will be the UNIX time the hash was
                   11255: stored. C<keys> is available in every historical section to list which
                   11256: keys were added or changed at a specific historical revision of a
                   11257: hash.
                   11258: 
                   11259: B<Warning>: do not store the hash that restore returns directly. This
                   11260: will cause a mess since it will restore the historical keys as if the
                   11261: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 11262: 
1.394     bowersj2 11263: Calling convention:
1.191     harris41 11264: 
1.394     bowersj2 11265:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   11266:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 11267: 
1.394     bowersj2 11268: For more detailed information, see lonnet specific documentation.
1.191     harris41 11269: 
1.394     bowersj2 11270: =head1 RETURN MESSAGES
1.191     harris41 11271: 
1.394     bowersj2 11272: =over 4
1.191     harris41 11273: 
1.394     bowersj2 11274: =item * B<con_lost>: unable to contact remote host
1.191     harris41 11275: 
1.394     bowersj2 11276: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   11277: when the connection is brought back up
1.191     harris41 11278: 
1.394     bowersj2 11279: =item * B<con_failed>: unable to contact remote host and unable to save message
                   11280: for later delivery
1.191     harris41 11281: 
1.967     bisitz   11282: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 11283: 
1.394     bowersj2 11284: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 11285: that was requested
1.191     harris41 11286: 
1.243     albertel 11287: =back
1.191     harris41 11288: 
1.243     albertel 11289: =head1 PUBLIC SUBROUTINES
1.191     harris41 11290: 
1.243     albertel 11291: =head2 Session Environment Functions
1.191     harris41 11292: 
1.243     albertel 11293: =over 4
1.191     harris41 11294: 
1.394     bowersj2 11295: =item * 
                   11296: X<appenv()>
1.949     raeburn  11297: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 11298: the user envirnoment file, and will be restored for each access this
1.620     albertel 11299: user makes during this session, also modifies the %env for the current
1.949     raeburn  11300: process. Optional rolesarrayref - if defined contains a reference to an array
                   11301: of roles which are exempt from the restriction on modifying user.role entries 
                   11302: in the user's environment.db and in %env.    
1.191     harris41 11303: 
                   11304: =item *
1.394     bowersj2 11305: X<delenv()>
1.987     raeburn  11306: B<delenv($delthis,$regexp)>: removes all items from the session
                   11307: environment file that begin with $delthis. If the 
                   11308: optional second arg - $regexp - is true, $delthis is treated as a 
                   11309: regular expression, otherwise \Q$delthis\E is used. 
                   11310: The values are also deleted from the current processes %env.
1.191     harris41 11311: 
1.795     albertel 11312: =item * get_env_multiple($name) 
                   11313: 
                   11314: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   11315: values may be defined and end up as an array ref.
                   11316: 
                   11317: returns an array of values
                   11318: 
1.243     albertel 11319: =back
                   11320: 
                   11321: =head2 User Information
1.191     harris41 11322: 
1.243     albertel 11323: =over 4
1.191     harris41 11324: 
                   11325: =item *
1.394     bowersj2 11326: X<queryauthenticate()>
                   11327: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 11328: authentication scheme
                   11329: 
                   11330: =item *
1.394     bowersj2 11331: X<authenticate()>
1.1073    raeburn  11332: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 11333: authenticate user from domain's lib servers (first use the current
                   11334: one). C<$upass> should be the users password.
1.1073    raeburn  11335: $checkdefauth is optional (value is 1 if a check should be made to
                   11336:    authenticate user using default authentication method, and allow
                   11337:    account creation if username does not have account in the domain).
                   11338: $clientcancheckhost is optional (value is 1 if checking whether the
                   11339:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 11340: 
                   11341: =item *
1.394     bowersj2 11342: X<homeserver()>
                   11343: B<homeserver($uname,$udom)>: find the server which has
                   11344: the user's directory and files (there must be only one), this caches
                   11345: the answer, and also caches if there is a borken connection.
1.191     harris41 11346: 
                   11347: =item *
1.394     bowersj2 11348: X<idget()>
                   11349: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   11350: (IDs are a unique resource in a domain, there must be only 1 ID per
                   11351: username, and only 1 username per ID in a specific domain) (returns
                   11352: hash: id=>name,id=>name)
1.191     harris41 11353: 
                   11354: =item *
1.394     bowersj2 11355: X<idrget()>
                   11356: B<idrget($udom,@unames)>: find the IDs behind a list of
                   11357: usernames (returns hash: name=>id,name=>id)
1.191     harris41 11358: 
                   11359: =item *
1.394     bowersj2 11360: X<idput()>
                   11361: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 11362: 
                   11363: =item *
1.394     bowersj2 11364: X<rolesinit()>
                   11365: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 11366: 
                   11367: =item *
1.551     albertel 11368: X<getsection()>
                   11369: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 11370: course $cname, return section name/number or '' for "not in course"
                   11371: and '-1' for "no section"
                   11372: 
                   11373: =item *
1.394     bowersj2 11374: X<userenvironment()>
                   11375: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 11376: passed in @what from the requested user's environment, returns a hash
                   11377: 
1.858     raeburn  11378: =item * 
                   11379: X<userlog_query()>
1.859     albertel 11380: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   11381: activity.log file. %filters defines filters applied when parsing the
                   11382: log file. These can be start or end timestamps, or the type of action
                   11383: - log to look for Login or Logout events, check for Checkin or
                   11384: Checkout, role for role selection. The response is in the form
                   11385: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   11386: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  11387: 
1.243     albertel 11388: =back
                   11389: 
                   11390: =head2 User Roles
                   11391: 
                   11392: =over 4
                   11393: 
                   11394: =item *
                   11395: 
1.810     raeburn  11396: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 11397:  F: full access
                   11398:  U,I,K: authentication modes (cxx only)
                   11399:  '': forbidden
                   11400:  1: user needs to choose course
                   11401:  2: browse allowed
1.766     albertel 11402:  A: passphrase authentication needed
1.243     albertel 11403: 
                   11404: =item *
                   11405: 
                   11406: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   11407: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   11408: and course level
                   11409: 
                   11410: =item *
                   11411: 
1.988     raeburn  11412: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   11413: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  11414: $type is Course (default) or Community.
1.988     raeburn  11415: If $forcedefault evaluates to true, text returned will be default 
                   11416: text for $type. Otherwise, if this is a course, the text returned 
                   11417: will be a custom name for the role (if defined in the course's 
                   11418: environment).  If no custom name is defined the default is returned.
                   11419:    
1.832     raeburn  11420: =item *
                   11421: 
1.935     raeburn  11422: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  11423: All arguments are optional. Returns a hash of a roles, either for
                   11424: co-author/assistant author roles for a user's Construction Space
1.906     albertel 11425: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  11426: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   11427: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   11428: For each key, value is set to colon-separated start and end times for
                   11429: the role.  If no username and domain are specified, will default to
1.934     raeburn  11430: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  11431: of role statuses (active, future or previous), roles 
                   11432: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   11433: to restrict the list of roles reported. If no array ref is 
                   11434: provided for types, will default to return only active roles.
1.834     albertel 11435: 
1.243     albertel 11436: =back
                   11437: 
                   11438: =head2 User Modification
                   11439: 
                   11440: =over 4
                   11441: 
                   11442: =item *
                   11443: 
1.957     raeburn  11444: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 11445: user for the level given by URL.  Optional start and end dates (leave empty
                   11446: string or zero for "no date")
1.191     harris41 11447: 
                   11448: =item *
                   11449: 
1.243     albertel 11450: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   11451: change a users, password, possible return values are: ok,
                   11452: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   11453: refused
1.191     harris41 11454: 
                   11455: =item *
                   11456: 
1.243     albertel 11457: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 11458: 
                   11459: =item *
                   11460: 
1.1058    raeburn  11461: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   11462:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   11463: 
                   11464: will update user information (firstname,middlename,lastname,generation,
                   11465: permanentemail), and if forceid is true, student/employee ID also.
                   11466: A user's institutional affiliation(s) can also be updated.
                   11467: User information fields will not be overwritten with empty entries 
                   11468: unless the field is included in the $candelete array reference.
                   11469: This array is included when a single user is modified via "Manage Users",
                   11470: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 11471: 
                   11472: =item *
                   11473: 
1.286     matthew  11474: modifystudent
                   11475: 
1.957     raeburn  11476: modify a student's enrollment and identification information.
1.286     matthew  11477: The course id is resolved based on the current users environment.  
                   11478: This means the envoking user must be a course coordinator or otherwise
                   11479: associated with a course.
                   11480: 
1.297     matthew  11481: This call is essentially a wrapper for lonnet::modifyuser and
                   11482: lonnet::modify_student_enrollment
1.286     matthew  11483: 
                   11484: Inputs: 
                   11485: 
                   11486: =over 4
                   11487: 
1.957     raeburn  11488: =item B<$udom> Student's loncapa domain
1.286     matthew  11489: 
1.957     raeburn  11490: =item B<$uname> Student's loncapa login name
1.286     matthew  11491: 
1.964     bisitz   11492: =item B<$uid> Student/Employee ID
1.286     matthew  11493: 
1.957     raeburn  11494: =item B<$umode> Student's authentication mode
1.286     matthew  11495: 
1.957     raeburn  11496: =item B<$upass> Student's password
1.286     matthew  11497: 
1.957     raeburn  11498: =item B<$first> Student's first name
1.286     matthew  11499: 
1.957     raeburn  11500: =item B<$middle> Student's middle name
1.286     matthew  11501: 
1.957     raeburn  11502: =item B<$last> Student's last name
1.286     matthew  11503: 
1.957     raeburn  11504: =item B<$gene> Student's generation
1.286     matthew  11505: 
1.957     raeburn  11506: =item B<$usec> Student's section in course
1.286     matthew  11507: 
                   11508: =item B<$end> Unix time of the roles expiration
                   11509: 
                   11510: =item B<$start> Unix time of the roles start date
                   11511: 
                   11512: =item B<$forceid> If defined, allow $uid to be changed
                   11513: 
                   11514: =item B<$desiredhome> server to use as home server for student
                   11515: 
1.957     raeburn  11516: =item B<$email> Student's permanent e-mail address
                   11517: 
                   11518: =item B<$type> Type of enrollment (auto or manual)
                   11519: 
1.963     raeburn  11520: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   11521: 
                   11522: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  11523: 
1.963     raeburn  11524: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  11525: 
1.963     raeburn  11526: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  11527: 
1.963     raeburn  11528: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  11529: 
1.286     matthew  11530: =back
1.297     matthew  11531: 
                   11532: =item *
                   11533: 
                   11534: modify_student_enrollment
                   11535: 
                   11536: Change a students enrollment status in a class.  The environment variable
                   11537: 'role.request.course' must be defined for this function to proceed.
                   11538: 
                   11539: Inputs:
                   11540: 
                   11541: =over 4
                   11542: 
                   11543: =item $udom, students domain
                   11544: 
                   11545: =item $uname, students name
                   11546: 
                   11547: =item $uid, students user id
                   11548: 
                   11549: =item $first, students first name
                   11550: 
                   11551: =item $middle
                   11552: 
                   11553: =item $last
                   11554: 
                   11555: =item $gene
                   11556: 
                   11557: =item $usec
                   11558: 
                   11559: =item $end
                   11560: 
                   11561: =item $start
                   11562: 
1.957     raeburn  11563: =item $type
                   11564: 
                   11565: =item $locktype
                   11566: 
                   11567: =item $cid
                   11568: 
                   11569: =item $selfenroll
                   11570: 
                   11571: =item $context
                   11572: 
1.297     matthew  11573: =back
                   11574: 
1.191     harris41 11575: 
                   11576: =item *
                   11577: 
1.243     albertel 11578: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   11579: custom role; give a custom role to a user for the level given by URL.  Specify
                   11580: name and domain of role author, and role name
1.191     harris41 11581: 
                   11582: =item *
                   11583: 
1.243     albertel 11584: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 11585: 
                   11586: =item *
                   11587: 
1.243     albertel 11588: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   11589: 
                   11590: =back
                   11591: 
                   11592: =head2 Course Infomation
                   11593: 
                   11594: =over 4
1.191     harris41 11595: 
                   11596: =item *
                   11597: 
1.1118    foxr     11598: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 11599: specified course id, including all environment settings for the
                   11600: course, the description of the course will be in the hash under the
                   11601: key 'description'
1.191     harris41 11602: 
1.1118    foxr     11603: $options is an optional parameter that if supplied is a hash reference that controls
                   11604: what how this function works.  It has the following key/values:
                   11605: 
                   11606: =over 4
                   11607: 
                   11608: =item freshen_cache
                   11609: 
                   11610: If defined, and the environment cache for the course is valid, it is 
                   11611: returned in the returned hash.
                   11612: 
                   11613: =item one_time
                   11614: 
                   11615: If defined, the last cache time is set to _now_
                   11616: 
                   11617: =item user
                   11618: 
                   11619: If defined, the supplied username is used instead of the current user.
                   11620: 
                   11621: 
                   11622: =back
                   11623: 
1.191     harris41 11624: =item *
                   11625: 
1.624     albertel 11626: resdata($name,$domain,$type,@which) : request for current parameter
                   11627: setting for a specific $type, where $type is either 'course' or 'user',
                   11628: @what should be a list of parameters to ask about. This routine caches
                   11629: answers for 5 minutes.
1.243     albertel 11630: 
1.877     foxr     11631: =item *
                   11632: 
                   11633: get_courseresdata($courseid, $domain) : dump the entire course resource
                   11634: data base, returning a hash that is keyed by the resource name and has
                   11635: values that are the resource value.  I believe that the timestamps and
                   11636: versions are also returned.
                   11637: 
                   11638: 
1.243     albertel 11639: =back
                   11640: 
                   11641: =head2 Course Modification
                   11642: 
                   11643: =over 4
1.191     harris41 11644: 
                   11645: =item *
                   11646: 
1.243     albertel 11647: writecoursepref($courseid,%prefs) : write preferences (environment
                   11648: database) for a course
1.191     harris41 11649: 
                   11650: =item *
                   11651: 
1.1011    raeburn  11652: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   11653: 
                   11654: =item *
                   11655: 
1.1038    raeburn  11656: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 11657: 
                   11658: =back
                   11659: 
                   11660: =head2 Resource Subroutines
                   11661: 
                   11662: =over 4
1.191     harris41 11663: 
                   11664: =item *
                   11665: 
1.243     albertel 11666: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 11667: 
                   11668: =item *
                   11669: 
1.243     albertel 11670: repcopy($filename) : subscribes to the requested file, and attempts to
                   11671: replicate from the owning library server, Might return
1.607     raeburn  11672: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   11673: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 11674: resource. Expects the local filesystem pathname
                   11675: (/home/httpd/html/res/....)
                   11676: 
                   11677: =back
                   11678: 
                   11679: =head2 Resource Information
                   11680: 
                   11681: =over 4
1.191     harris41 11682: 
                   11683: =item *
                   11684: 
1.243     albertel 11685: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   11686: a vairety of different possible values, $varname should be a request
                   11687: string, and the other parameters can be used to specify who and what
                   11688: one is asking about.
                   11689: 
                   11690: Possible values for $varname are environment.lastname (or other item
                   11691: from the envirnment hash), user.name (or someother aspect about the
                   11692: user), resource.0.maxtries (or some other part and parameter of a
                   11693: resource)
1.204     albertel 11694: 
                   11695: =item *
                   11696: 
1.243     albertel 11697: directcondval($number) : get current value of a condition; reads from a state
                   11698: string
1.204     albertel 11699: 
                   11700: =item *
                   11701: 
1.243     albertel 11702: condval($condidx) : value of condition index based on state
1.204     albertel 11703: 
                   11704: =item *
                   11705: 
1.243     albertel 11706: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   11707: resource's metadata, $what should be either a specific key, or either
                   11708: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   11709: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   11710: 
                   11711: this function automatically caches all requests
1.191     harris41 11712: 
                   11713: =item *
                   11714: 
1.243     albertel 11715: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   11716: network of library servers; returns file handle of where SQL and regex results
                   11717: will be stored for query
1.191     harris41 11718: 
                   11719: =item *
                   11720: 
1.243     albertel 11721: symbread($filename) : return symbolic list entry (filename argument optional);
                   11722: returns the data handle
1.191     harris41 11723: 
                   11724: =item *
                   11725: 
1.243     albertel 11726: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 11727: a possible symb for the URL in $thisfn, and if is an encryypted
                   11728: resource that the user accessed using /enc/ returns a 1 on success, 0
                   11729: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 11730: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 11731: 
1.191     harris41 11732: 
                   11733: =item *
                   11734: 
1.243     albertel 11735: symbclean($symb) : removes versions numbers from a symb, returns the
                   11736: cleaned symb
1.191     harris41 11737: 
                   11738: =item *
                   11739: 
1.243     albertel 11740: is_on_map($uri) : checks if the $uri is somewhere on the current
                   11741: course map, user must be in a course for it to work.
1.191     harris41 11742: 
                   11743: =item *
                   11744: 
1.243     albertel 11745: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 11746: 
                   11747: =item *
                   11748: 
1.243     albertel 11749: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   11750: a random seed, all arguments are optional, if they aren't sent it uses the
                   11751: environment to derive them. Note: if symb isn't sent and it can't get one
                   11752: from &symbread it will use the current time as its return value
1.191     harris41 11753: 
                   11754: =item *
                   11755: 
1.243     albertel 11756: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   11757: unfakeable, receipt
1.191     harris41 11758: 
                   11759: =item *
                   11760: 
1.620     albertel 11761: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 11762: 
                   11763: =item *
                   11764: 
1.243     albertel 11765: countacc($url) : count the number of accesses to a given URL
1.191     harris41 11766: 
                   11767: =item *
                   11768: 
1.243     albertel 11769: 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 11770: 
                   11771: =item *
                   11772: 
1.243     albertel 11773: 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 11774: 
                   11775: =item *
                   11776: 
1.243     albertel 11777: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 11778: 
                   11779: =item *
                   11780: 
1.243     albertel 11781: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   11782: forcing spreadsheet to reevaluate the resource scores next time.
                   11783: 
                   11784: =back
                   11785: 
                   11786: =head2 Storing/Retreiving Data
                   11787: 
                   11788: =over 4
1.191     harris41 11789: 
                   11790: =item *
                   11791: 
1.243     albertel 11792: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   11793: for this url; hashref needs to be given and should be a \%hashname; the
                   11794: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 11795: be derived from the env
1.191     harris41 11796: 
                   11797: =item *
                   11798: 
1.243     albertel 11799: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   11800: uses critical subroutine
1.191     harris41 11801: 
                   11802: =item *
                   11803: 
1.243     albertel 11804: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   11805: all args are optional
1.191     harris41 11806: 
                   11807: =item *
                   11808: 
1.717     albertel 11809: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   11810: dumps the complete (or key matching regexp) namespace into a hash
                   11811: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   11812: normally &store()ed into
                   11813: 
                   11814: $range should be either an integer '100' (give me the first 100
                   11815:                                            matching records)
                   11816:               or be  two integers sperated by a - with no spaces
                   11817:                  '30-50' (give me the 30th through the 50th matching
                   11818:                           records)
                   11819: 
                   11820: 
                   11821: =item *
                   11822: 
                   11823: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   11824: replaces a &store() version of data with a replacement set of data
                   11825: for a particular resource in a namespace passed in the $storehash hash 
                   11826: reference
                   11827: 
                   11828: =item *
                   11829: 
1.243     albertel 11830: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   11831: works very similar to store/cstore, but all data is stored in a
                   11832: temporary location and can be reset using tmpreset, $storehash should
                   11833: be a hash reference, returns nothing on success
1.191     harris41 11834: 
                   11835: =item *
                   11836: 
1.243     albertel 11837: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   11838: similar to restore, but all data is stored in a temporary location and
                   11839: can be reset using tmpreset. Returns a hash of values on success,
                   11840: error string otherwise.
1.191     harris41 11841: 
                   11842: =item *
                   11843: 
1.243     albertel 11844: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   11845: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 11846: 
                   11847: =item *
                   11848: 
1.243     albertel 11849: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11850: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 11851: 
                   11852: =item *
                   11853: 
1.243     albertel 11854: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   11855: namesp ($udom and $uname are optional)
1.191     harris41 11856: 
                   11857: =item *
                   11858: 
1.702     albertel 11859: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 11860: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 11861: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  11862: 
1.702     albertel 11863: $range should be either an integer '100' (give me the first 100
                   11864:                                            matching records)
                   11865:               or be  two integers sperated by a - with no spaces
                   11866:                  '30-50' (give me the 30th through the 50th matching
                   11867:                           records)
1.449     matthew  11868: =item *
                   11869: 
                   11870: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   11871: $store can be a scalar, an array reference, or if the amount to be 
                   11872: incremented is > 1, a hash reference.
                   11873: 
                   11874: ($udom and $uname are optional)
1.191     harris41 11875: 
                   11876: =item *
                   11877: 
1.243     albertel 11878: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   11879: ($udom and $uname are optional)
1.191     harris41 11880: 
                   11881: =item *
                   11882: 
1.243     albertel 11883: cput($namespace,$storehash,$udom,$uname) : critical put
                   11884: ($udom and $uname are optional)
1.191     harris41 11885: 
                   11886: =item *
                   11887: 
1.748     albertel 11888: newput($namespace,$storehash,$udom,$uname) :
                   11889: 
                   11890: Attempts to store the items in the $storehash, but only if they don't
                   11891: currently exist, if this succeeds you can be certain that you have 
                   11892: successfully created a new key value pair in the $namespace db.
                   11893: 
                   11894: 
                   11895: Args:
                   11896:  $namespace: name of database to store values to
                   11897:  $storehash: hashref to store to the db
                   11898:  $udom: (optional) domain of user containing the db
                   11899:  $uname: (optional) name of user caontaining the db
                   11900: 
                   11901: Returns:
                   11902:  'ok' -> succeeded in storing all keys of $storehash
                   11903:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   11904:                         least <key> already existed in the db (other
                   11905:                         requested keys may also already exist)
1.967     bisitz   11906:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 11907:  'con_lost' -> unable to contact request server
                   11908:  'refused' -> action was not allowed by remote machine
                   11909: 
                   11910: 
                   11911: =item *
                   11912: 
1.243     albertel 11913: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11914: reference filled in from namesp (encrypts the return communication)
                   11915: ($udom and $uname are optional)
1.191     harris41 11916: 
                   11917: =item *
                   11918: 
1.243     albertel 11919: log($udom,$name,$home,$message) : write to permanent log for user; use
                   11920: critical subroutine
                   11921: 
1.806     raeburn  11922: =item *
                   11923: 
1.860     raeburn  11924: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   11925: array reference filled in from namespace found in domain level on either
                   11926: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  11927: 
                   11928: =item *
                   11929: 
1.860     raeburn  11930: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   11931: domain level either on specified domain server ($uhome) or primary domain 
                   11932: server ($udom and $uhome are optional)
1.806     raeburn  11933: 
1.943     raeburn  11934: =item * 
                   11935: 
                   11936: get_domain_defaults($target_domain) : returns hash with defaults for
                   11937: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   11938: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   11939: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   11940: Values are retrieved from cache (if current), or from domain's configuration.db
                   11941: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   11942: or lonTabs/domain.tab. 
                   11943: 
                   11944: %domdefaults = &get_auth_defaults($target_domain);
                   11945: 
1.243     albertel 11946: =back
                   11947: 
                   11948: =head2 Network Status Functions
                   11949: 
                   11950: =over 4
1.191     harris41 11951: 
                   11952: =item *
                   11953: 
1.1137    raeburn  11954: dirlist() : return directory list based on URI (first arg).
                   11955: 
                   11956: Inputs: 1 required, 5 optional.
                   11957: 
                   11958: =over
                   11959: 
                   11960: =item 
                   11961: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   11962: 
                   11963: =item
                   11964: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   11965: 
                   11966: =item
                   11967: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   11968: 
                   11969: =item
                   11970: $getpropath - boolean: 1 if prepend path using &propath(). 
                   11971: 
                   11972: =item
                   11973: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   11974: 
                   11975: =item 
                   11976: $alternateRoot - path to prepend in place of path from $uri.
                   11977: 
                   11978: =back
                   11979: 
                   11980: Returns: Array of up to two items.
                   11981: 
                   11982: =over
                   11983: 
                   11984: a reference to an array of files/subdirectories
                   11985: 
                   11986: =over
                   11987: 
                   11988: Each element in the array of files/subdirectories is a & separated list of
                   11989: item name and the result of running stat on the item.  If dirlist was requested
                   11990: for a file instead of a directory, the item name will be ''. For a directory 
                   11991: listing, if the item is a metadata file, the element will end &N&M 
                   11992: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   11993: default copyright set (1).  
                   11994: 
                   11995: =back
                   11996: 
                   11997: a scalar containing error condition (if encountered).
                   11998: 
                   11999: =over
                   12000: 
                   12001: =item 
                   12002: no_host (no homeserver identified for $username:$domain).
                   12003: 
                   12004: =item 
                   12005: no_such_host (server contacted for listing not identified as valid host).
                   12006: 
                   12007: =item 
                   12008: con_lost (connection to remote server failed).
                   12009: 
                   12010: =item 
                   12011: refused (invalid $username:$domain received on lond side).
                   12012: 
                   12013: =item 
                   12014: no_such_dir (directory at specified path on lond side does not exist). 
                   12015: 
                   12016: =item 
                   12017: empty (directory at specified path on lond side is empty).
                   12018: 
                   12019: =over
                   12020: 
                   12021: This is currently not encountered because the &ls3, &ls2, 
                   12022: &ls (_handler) routines on the lond side do not filter out
                   12023: . and .. from a directory listing. 
                   12024: 
                   12025: =back
                   12026: 
                   12027: =back
                   12028: 
                   12029: =back
1.191     harris41 12030: 
                   12031: =item *
                   12032: 
1.243     albertel 12033: spareserver() : find server with least workload from spare.tab
                   12034: 
1.986     foxr     12035: 
                   12036: =item *
                   12037: 
                   12038: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   12039: if there is no corresponding loncapa host.
                   12040: 
1.243     albertel 12041: =back
                   12042: 
1.986     foxr     12043: 
1.243     albertel 12044: =head2 Apache Request
                   12045: 
                   12046: =over 4
1.191     harris41 12047: 
                   12048: =item *
                   12049: 
1.243     albertel 12050: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   12051: localhost, posts hash
                   12052: 
                   12053: =back
                   12054: 
                   12055: =head2 Data to String to Data
                   12056: 
                   12057: =over 4
1.191     harris41 12058: 
                   12059: =item *
                   12060: 
1.243     albertel 12061: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   12062: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 12063: 
                   12064: =item *
                   12065: 
1.243     albertel 12066: hashref2str($hashref) : convert a hashref into a string complete with
                   12067: escaping and '=' and '&' separators, supports elements that are
                   12068: arrayrefs and hashrefs
1.191     harris41 12069: 
                   12070: =item *
                   12071: 
1.243     albertel 12072: arrayref2str($arrayref) : convert an arrayref into a string complete
                   12073: with escaping and '&' separators, supports elements that are arrayrefs
                   12074: and hashrefs
1.191     harris41 12075: 
                   12076: =item *
                   12077: 
1.243     albertel 12078: str2hash($string) : convert string to hash using unescaping and
                   12079: splitting on '=' and '&', supports elements that are arrayrefs and
                   12080: hashrefs
1.191     harris41 12081: 
                   12082: =item *
                   12083: 
1.243     albertel 12084: str2array($string) : convert string to hash using unescaping and
                   12085: splitting on '&', supports elements that are arrayrefs and hashrefs
                   12086: 
                   12087: =back
                   12088: 
                   12089: =head2 Logging Routines
                   12090: 
                   12091: 
                   12092: These routines allow one to make log messages in the lonnet.log and
                   12093: lonnet.perm logfiles.
1.191     harris41 12094: 
1.1119    foxr     12095: =over 4
                   12096: 
1.191     harris41 12097: =item *
                   12098: 
1.243     albertel 12099: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 12100: 
                   12101: =item *
                   12102: 
1.243     albertel 12103: logthis() : append message to the normal lonnet.log file, it gets
                   12104: preiodically rolled over and deleted.
1.191     harris41 12105: 
                   12106: =item *
                   12107: 
1.243     albertel 12108: logperm() : append a permanent message to lonnet.perm.log, this log
                   12109: file never gets deleted by any automated portion of the system, only
                   12110: messages of critical importance should go in here.
                   12111: 
1.1119    foxr     12112: 
1.243     albertel 12113: =back
                   12114: 
                   12115: =head2 General File Helper Routines
                   12116: 
                   12117: =over 4
1.191     harris41 12118: 
                   12119: =item *
                   12120: 
1.481     raeburn  12121: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   12122: (a) files in /uploaded
                   12123:   (i) If a local copy of the file exists - 
                   12124:       compares modification date of local copy with last-modified date for 
                   12125:       definitive version stored on home server for course. If local copy is 
                   12126:       stale, requests a new version from the home server and stores it. 
                   12127:       If the original has been removed from the home server, then local copy 
                   12128:       is unlinked.
                   12129:   (ii) If local copy does not exist -
                   12130:       requests the file from the home server and stores it. 
                   12131:   
                   12132:   If $caller is 'uploadrep':  
                   12133:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   12134:     for request for files originally uploaded via DOCS. 
                   12135:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   12136:   
                   12137:   Otherwise:
                   12138:      This indicates a call from the content generation phase of the request.
                   12139:      -  returns the entire contents of the file or -1.
                   12140:      
                   12141: (b) files in /res
                   12142:    - returns the entire contents of a file or -1; 
                   12143:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 12144: 
1.712     albertel 12145: 
                   12146: =item *
                   12147: 
                   12148: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   12149:                   reference
                   12150: 
                   12151: returns either a stat() list of data about the file or an empty list
                   12152: if the file doesn't exist or couldn't find out about it (connection
                   12153: problems or user unknown)
                   12154: 
1.191     harris41 12155: =item *
                   12156: 
1.243     albertel 12157: filelocation($dir,$file) : returns file system location of a file
                   12158: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   12159: directory that relative $file lookups are to looked in ($dir of /a/dir
                   12160: and a file of ../bob will become /a/bob)
1.191     harris41 12161: 
                   12162: =item *
                   12163: 
                   12164: hreflocation($dir,$file) : returns file system location or a URL; same as
                   12165: filelocation except for hrefs
                   12166: 
                   12167: =item *
                   12168: 
                   12169: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   12170: 
1.243     albertel 12171: =back
                   12172: 
1.608     albertel 12173: =head2 Usererfile file routines (/uploaded*)
                   12174: 
                   12175: =over 4
                   12176: 
                   12177: =item *
                   12178: 
                   12179: userfileupload(): main rotine for putting a file in a user or course's
                   12180:                   filespace, arguments are,
                   12181: 
1.620     albertel 12182:  formname - required - this is the name of the element in $env where the
1.608     albertel 12183:            filename, and the contents of the file to create/modifed exist
1.620     albertel 12184:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   12185:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  12186:  context - if coursedoc, store the file in the course of the active role
                   12187:              of the current user; 
                   12188:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   12189:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 12190:  subdir - required - subdirectory to put the file in under ../userfiles/
                   12191:          if undefined, it will be placed in "unknown"
                   12192: 
                   12193:  (This routine calls clean_filename() to remove any dangerous
                   12194:  characters from the filename, and then calls finuserfileupload() to
                   12195:  complete the transaction)
                   12196: 
                   12197:  returns either the url of the uploaded file (/uploaded/....) if successful
                   12198:  and /adm/notfound.html if unsuccessful
                   12199: 
                   12200: =item *
                   12201: 
                   12202: clean_filename(): routine for cleaing a filename up for storage in
                   12203:                  userfile space, argument is:
                   12204: 
                   12205:  filename - proposed filename
                   12206: 
                   12207: returns: the new clean filename
                   12208: 
                   12209: =item *
                   12210: 
1.1090    raeburn  12211: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 12212: userspace, probably shouldn't be called directly
                   12213: 
                   12214:   docuname: username or courseid of destination for the file
                   12215:   docudom: domain of user/course of destination for the file
                   12216:   formname: same as for userfileupload()
1.1090    raeburn  12217:   fname: filename (including subdirectories) for the file
                   12218:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   12219:   allfiles: reference to hash used to store objects found by parser
                   12220:   codebase: reference to hash used for codebases of java objects found by parser
                   12221:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   12222:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   12223:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   12224:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   12225:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   12226:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  12227:   mimetype: reference to scalar to accommodate mime type determined
                   12228:             from File::MMagic if $parser = parse.
1.608     albertel 12229: 
                   12230:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  12231:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   12232:  was 'overwrite').
                   12233:  
1.608     albertel 12234: 
                   12235: =item *
                   12236: 
                   12237: renameuserfile(): renames an existing userfile to a new name
                   12238: 
                   12239:   Args:
                   12240:    docuname: username or courseid of destination for the file
                   12241:    docudom: domain of user/course of destination for the file
                   12242:    old: current file name (including any subdirs under userfiles)
                   12243:    new: desired file name (including any subdirs under userfiles)
                   12244: 
                   12245: =item *
                   12246: 
                   12247: mkdiruserfile(): creates a directory is a userfiles dir
                   12248: 
                   12249:   Args:
                   12250:    docuname: username or courseid of destination for the file
                   12251:    docudom: domain of user/course of destination for the file
                   12252:    dir: dir to create (including any subdirs under userfiles)
                   12253: 
                   12254: =item *
                   12255: 
                   12256: removeuserfile(): removes a file that exists in userfiles
                   12257: 
                   12258:   Args:
                   12259:    docuname: username or courseid of destination for the file
                   12260:    docudom: domain of user/course of destination for the file
                   12261:    fname: filname to delete (including any subdirs under userfiles)
                   12262: 
                   12263: =item *
                   12264: 
                   12265: removeuploadedurl(): convience function for removeuserfile()
                   12266: 
                   12267:   Args:
                   12268:    url:  a full /uploaded/... url to delete
                   12269: 
1.747     albertel 12270: =item * 
                   12271: 
                   12272: get_portfile_permissions():
                   12273:   Args:
                   12274:     domain: domain of user or course contain the portfolio files
                   12275:     user: name of user or num of course contain the portfolio files
                   12276:   Returns:
                   12277:     hashref of a dump of the proper file_permissions.db
                   12278:    
                   12279: 
                   12280: =item * 
                   12281: 
                   12282: get_access_controls():
                   12283: 
                   12284: Args:
                   12285:   current_permissions: the hash ref returned from get_portfile_permissions()
                   12286:   group: (optional) the group you want the files associated with
                   12287:   file: (optional) the file you want access info on
                   12288: 
                   12289: Returns:
1.749     raeburn  12290:     a hash (keys are file names) of hashes containing
                   12291:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   12292:         values are XML containing access control settings (see below) 
1.747     albertel 12293: 
                   12294: Internal notes:
                   12295: 
1.749     raeburn  12296:  access controls are stored in file_permissions.db as key=value pairs.
                   12297:     key -> path to file/file_name\0uniqueID:scope_end_start
                   12298:         where scope -> public,guest,course,group,domains or users.
                   12299:               end -> UNIX time for end of access (0 -> no end date)
                   12300:               start -> UNIX time for start of access
                   12301: 
                   12302:     value -> XML description of access control
                   12303:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   12304:             <start></start>
                   12305:             <end></end>
                   12306: 
                   12307:             <password></password>  for scope type = guest
                   12308: 
                   12309:             <domain></domain>     for scope type = course or group
                   12310:             <number></number>
                   12311:             <roles id="">
                   12312:              <role></role>
                   12313:              <access></access>
                   12314:              <section></section>
                   12315:              <group></group>
                   12316:             </roles>
                   12317: 
                   12318:             <dom></dom>         for scope type = domains
                   12319: 
                   12320:             <users>             for scope type = users
                   12321:              <user>
                   12322:               <uname></uname>
                   12323:               <udom></udom>
                   12324:              </user>
                   12325:             </users>
                   12326:            </scope> 
                   12327:               
                   12328:  Access data is also aggregated for each file in an additional key=value pair:
                   12329:  key -> path to file/file_name\0accesscontrol 
                   12330:  value -> reference to hash
                   12331:           hash contains key = value pairs
                   12332:           where key = uniqueID:scope_end_start
                   12333:                 value = UNIX time record was last updated
                   12334: 
                   12335:           Used to improve speed of look-ups of access controls for each file.  
                   12336:  
                   12337:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   12338: 
                   12339: modify_access_controls():
                   12340: 
                   12341: Modifies access controls for a portfolio file
                   12342: Args
                   12343: 1. file name
                   12344: 2. reference to hash of required changes,
                   12345: 3. domain
                   12346: 4. username
                   12347:   where domain,username are the domain of the portfolio owner 
                   12348:   (either a user or a course) 
                   12349: 
                   12350: Returns:
                   12351: 1. result of additions or updates ('ok' or 'error', with error message). 
                   12352: 2. result of deletions ('ok' or 'error', with error message).
                   12353: 3. reference to hash of any new or updated access controls.
                   12354: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   12355:    key = integer (inbound ID)
                   12356:    value = uniqueID  
1.747     albertel 12357: 
1.608     albertel 12358: =back
                   12359: 
1.243     albertel 12360: =head2 HTTP Helper Routines
                   12361: 
                   12362: =over 4
                   12363: 
1.191     harris41 12364: =item *
                   12365: 
                   12366: escape() : unpack non-word characters into CGI-compatible hex codes
                   12367: 
                   12368: =item *
                   12369: 
                   12370: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   12371: 
1.243     albertel 12372: =back
                   12373: 
                   12374: =head1 PRIVATE SUBROUTINES
                   12375: 
                   12376: =head2 Underlying communication routines (Shouldn't call)
                   12377: 
                   12378: =over 4
                   12379: 
                   12380: =item *
                   12381: 
                   12382: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   12383: 
                   12384: =item *
                   12385: 
                   12386: reply() : uses subreply to send a message to remote machine, logs all failures
                   12387: 
                   12388: =item *
                   12389: 
                   12390: critical() : passes a critical message to another server; if cannot
                   12391: get through then place message in connection buffer directory and
                   12392: returns con_delayed, if incapable of saving message, returns
                   12393: con_failed
                   12394: 
                   12395: =item *
                   12396: 
                   12397: reconlonc() : tries to reconnect lonc client processes.
                   12398: 
                   12399: =back
                   12400: 
                   12401: =head2 Resource Access Logging
                   12402: 
                   12403: =over 4
                   12404: 
                   12405: =item *
                   12406: 
                   12407: flushcourselogs() : flush (save) buffer logs and access logs
                   12408: 
                   12409: =item *
                   12410: 
                   12411: courselog($what) : save message for course in hash
                   12412: 
                   12413: =item *
                   12414: 
                   12415: courseacclog($what) : save message for course using &courselog().  Perform
                   12416: special processing for specific resource types (problems, exams, quizzes, etc).
                   12417: 
1.191     harris41 12418: =item *
                   12419: 
                   12420: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   12421: as a PerlChildExitHandler
1.243     albertel 12422: 
                   12423: =back
                   12424: 
                   12425: =head2 Other
                   12426: 
                   12427: =over 4
                   12428: 
                   12429: =item *
                   12430: 
                   12431: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 12432: 
                   12433: =back
                   12434: 
                   12435: =cut
1.877     foxr     12436: 

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