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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1348  ! raeburn     4: # $Id: lonnet.pm,v 1.1347 2017/08/07 20:22:54 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.486     www        74: use HTTP::Date;
1.977     amueller   75: use Image::Magick;
                     76: 
1.1182    foxr       77: 
1.1173    foxr       78: use Encode;
                     79: 
1.1245    raeburn    80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138    raeburn    81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     82:             %managerstab);
1.871     albertel   83: 
                     84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        87:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        88: 
1.1       albertel   89: use IO::Socket;
1.31      www        90: use GDBM_File;
1.208     albertel   91: use HTML::LCParser;
1.88      www        92: use Fcntl qw(:flock);
1.870     albertel   93: use Storable qw(thaw nfreeze);
1.1289    damieng    94: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   95: use Cache::Memcached;
1.676     albertel   96: use Digest::MD5;
1.790     albertel   97: use Math::Random;
1.1024    raeburn    98: use File::MMagic;
1.807     albertel   99: use LONCAPA qw(:DEFAULT :match);
1.740     www       100: use LONCAPA::Configuration;
1.1160    www       101: use LONCAPA::lonmetadata;
1.1167    droeschl  102: use LONCAPA::Lond;
1.1345    raeburn   103: use LONCAPA::LWPReq;
1.1117    foxr      104: 
1.1090    raeburn   105: use File::Copy;
1.676     albertel  106: 
1.195     www       107: my $readit;
1.1288    damieng   108: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  109: 
1.619     albertel  110: require Exporter;
                    111: 
                    112: our @ISA = qw (Exporter);
                    113: our @EXPORT = qw(%env);
                    114: 
1.449     matthew   115: 
1.1187    raeburn   116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       117: {
                    118:     my $logid;
1.1187    raeburn   119:     sub write_log {
1.1188    raeburn   120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184    raeburn   121:         if ($context eq 'course') {
                    122:             if (($cnum eq '') || ($cdom eq '')) {
                    123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    125:             }
1.957     raeburn   126:         }
1.1184    raeburn   127: 	$logid ++;
1.957     raeburn   128:         my $now = time();
                    129: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1184    raeburn   130:         my $logentry = { 
                    131:                           $id => {
                    132:                                    'exe_uname' => $env{'user.name'},
                    133:                                    'exe_udom'  => $env{'user.domain'},
                    134:                                    'exe_time'  => $now,
                    135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    136:                                    'delflag'   => $delflag,
                    137:                                    'logentry'  => $storehash,
                    138:                                    'uname'     => $uname,
                    139:                                    'udom'      => $udom,
                    140:                                   }
                    141:                        };
                    142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       143:     }
                    144: }
1.1       albertel  145: 
1.163     harris41  146: sub logtouch {
                    147:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  148:     unless (-e "$execdir/logs/lonnet.log") {	
                    149: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  150: 	close $fh;
                    151:     }
                    152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    154: }
                    155: 
1.1       albertel  156: sub logthis {
                    157:     my $message=shift;
                    158:     my $execdir=$perlvar{'lonDaemons'};
                    159:     my $now=time;
                    160:     my $local=localtime($now);
1.448     albertel  161:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    163: 	print $fh $logstring;
1.448     albertel  164: 	close($fh);
                    165:     }
1.1       albertel  166:     return 1;
                    167: }
                    168: 
                    169: sub logperm {
                    170:     my $message=shift;
                    171:     my $execdir=$perlvar{'lonDaemons'};
                    172:     my $now=time;
                    173:     my $local=localtime($now);
1.448     albertel  174:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    175: 	print $fh "$now:$message:$local\n";
                    176: 	close($fh);
                    177:     }
1.1       albertel  178:     return 1;
                    179: }
                    180: 
1.850     albertel  181: sub create_connection {
1.853     albertel  182:     my ($hostname,$lonid) = @_;
1.851     albertel  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  184: 				     Type    => SOCK_STREAM,
                    185: 				     Timeout => 10);
                    186:     return 0 if (!$client);
1.890     albertel  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  188:     my $result = <$client>;
                    189:     chomp($result);
                    190:     return 1 if ($result eq 'done');
                    191:     return 0;
                    192: }
                    193: 
1.983     raeburn   194: sub get_server_timezone {
                    195:     my ($cnum,$cdom) = @_;
                    196:     my $home=&homeserver($cnum,$cdom);
                    197:     if ($home ne 'no_host') {
                    198:         my $cachetime = 24*3600;
                    199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    200:         if (defined($cached)) {
                    201:             return $timezone;
                    202:         } else {
                    203:             my $timezone = &reply('servertimezone',$home);
                    204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    205:         }
                    206:     }
                    207: }
1.850     albertel  208: 
1.1106    raeburn   209: sub get_server_distarch {
                    210:     my ($lonhost,$ignore_cache) = @_;
                    211:     if (defined($lonhost)) {
                    212:         if (!defined(&hostname($lonhost))) {
                    213:             return;
                    214:         }
                    215:         my $cachetime = 12*3600;
                    216:         if (!$ignore_cache) {
                    217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    218:             if (defined($cached)) {
                    219:                 return $distarch;
                    220:             }
                    221:         }
                    222:         my $rep = &reply('serverdistarch',$lonhost);
                    223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    225:                 $rep eq '') {
                    226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    227:         }
                    228:     }
                    229:     return;
                    230: }
                    231: 
1.1315    raeburn   232: sub get_servercerts_info {
                    233:     my ($lonhost,$context) = @_;
                    234:     my ($rep,$uselocal);
                    235:     if (grep { $_ eq $lonhost } &current_machine_ids()) {
                    236:         $uselocal = 1;
                    237:     }
1.1316    raeburn   238:     if (($context ne 'cgi') && ($uselocal)) {
1.1315    raeburn   239:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
1.1323    raeburn   240:         if ($distro eq '') {
                    241:             $uselocal = 0;
                    242:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
1.1315    raeburn   243:             if ($1 < 6) {
                    244:                 $uselocal = 0;
                    245:             }
1.1346    raeburn   246:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
                    247:             if ($1 < 12) {
                    248:                 $uselocal = 0;
                    249:             }
1.1315    raeburn   250:         }
                    251:     }
                    252:     if ($uselocal) {
                    253:         $rep = LONCAPA::Lond::server_certs(\%perlvar);
                    254:     } else {
                    255:         $rep=&reply('servercerts',$lonhost);
                    256:     }
                    257:     my ($result,%returnhash);
                    258:     if (defined($lonhost)) {
                    259:         if (!defined(&hostname($lonhost))) {
                    260:             return;
                    261:         }
                    262:     }
                    263:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    264:         ($rep eq 'unknown_cmd')) {
                    265:         $result = $rep;
                    266:     } else {
                    267:         $result = 'ok';
                    268:         my @pairs=split(/\&/,$rep);
                    269:         foreach my $item (@pairs) {
                    270:             my ($key,$value)=split(/=/,$item,2);
                    271:             my $what = &unescape($key);
                    272:             $returnhash{$what}=&thaw_unescape($value);
                    273:         }
                    274:     }
                    275:     return ($result,\%returnhash);
                    276: }
                    277: 
1.993     raeburn   278: sub get_server_loncaparev {
1.1073    raeburn   279:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   280:     if (defined($lonhost)) {
                    281:         if (!defined(&hostname($lonhost))) {
                    282:             undef($lonhost);
                    283:         }
                    284:     }
                    285:     if (!defined($lonhost)) {
                    286:         if (defined(&domain($dom,'primary'))) {
                    287:             $lonhost=&domain($dom,'primary');
                    288:             if ($lonhost eq 'no_host') {
                    289:                 undef($lonhost);
                    290:             }
                    291:         }
                    292:     }
                    293:     if (defined($lonhost)) {
1.1073    raeburn   294:         my $cachetime = 12*3600;
                    295:         if (!$ignore_cache) {
                    296:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    297:             if (defined($cached)) {
                    298:                 return $loncaparev;
                    299:             }
                    300:         }
                    301:         my ($answer,$loncaparev);
                    302:         my @ids=&current_machine_ids();
                    303:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    304:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   305:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   306:                 $loncaparev = $1;
                    307:             }
                    308:         } else {
                    309:             $answer = &reply('serverloncaparev',$lonhost);
                    310:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    311:                 if ($caller eq 'loncron') {
                    312:                     my $protocol = $protocol{$lonhost};
                    313:                     $protocol = 'http' if ($protocol ne 'https');
                    314:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    315:                     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn   316:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
1.1073    raeburn   317:                     unless ($response->is_error()) {
                    318:                         my $content = $response->content;
1.1081    raeburn   319:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   320:                             $loncaparev = $1;
                    321:                         }
                    322:                     }
                    323:                 } else {
                    324:                     $loncaparev = $loncaparevs{$lonhost};
                    325:                 }
1.1081    raeburn   326:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   327:                 $loncaparev = $1;
                    328:             }
1.993     raeburn   329:         }
1.1073    raeburn   330:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   331:     }
                    332: }
                    333: 
1.1074    raeburn   334: sub get_server_homeID {
                    335:     my ($hostname,$ignore_cache,$caller) = @_;
                    336:     unless ($ignore_cache) {
                    337:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    338:         if (defined($cached)) {
                    339:             return $serverhomeID;
                    340:         }
                    341:     }
                    342:     my $cachetime = 12*3600;
                    343:     my $serverhomeID;
                    344:     if ($caller eq 'loncron') { 
                    345:         my @machine_ids = &machine_ids($hostname);
                    346:         foreach my $id (@machine_ids) {
                    347:             my $response = &reply('serverhomeID',$id);
                    348:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    349:                 $serverhomeID = $response;
                    350:                 last;
                    351:             }
                    352:         }
                    353:         if ($serverhomeID eq '') {
                    354:             $serverhomeID = $machine_ids[-1];
                    355:         }
                    356:     } else {
                    357:         $serverhomeID = $serverhomeIDs{$hostname};
                    358:     }
                    359:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    360: }
                    361: 
1.1121    raeburn   362: sub get_remote_globals {
                    363:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   364:     my ($result,%returnhash,%whatneeded);
                    365:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   366:         foreach my $what (sort(keys(%{$whathash}))) {
                    367:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   368:             my ($response,$cached);
1.1121    raeburn   369:             unless ($ignore_cache) {
1.1125    raeburn   370:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   371:             }
                    372:             if (defined($cached)) {
1.1125    raeburn   373:                 $returnhash{$what} = $response;
1.1121    raeburn   374:             } else {
1.1125    raeburn   375:                 $whatneeded{$what} = 1;
1.1121    raeburn   376:             }
                    377:         }
1.1125    raeburn   378:         if (keys(%whatneeded) == 0) {
                    379:             $result = 'ok';
                    380:         } else {
1.1121    raeburn   381:             my $requested = &freeze_escape(\%whatneeded);
                    382:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   383:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    384:                 ($rep eq 'unknown_cmd')) {
                    385:                 $result = $rep;
                    386:             } else {
                    387:                 $result = 'ok';
1.1121    raeburn   388:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   389:                 foreach my $item (@pairs) {
                    390:                     my ($key,$value)=split(/=/,$item,2);
                    391:                     my $what = &unescape($key);
                    392:                     my $hashid = $lonhost.'-'.$what;
                    393:                     $returnhash{$what}=&thaw_unescape($value);
                    394:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   395:                 }
                    396:             }
                    397:         }
                    398:     }
1.1125    raeburn   399:     return ($result,\%returnhash);
1.1121    raeburn   400: }
                    401: 
1.1124    raeburn   402: sub remote_devalidate_cache {
1.1241    raeburn   403:     my ($lonhost,$cachekeys) = @_;
                    404:     my $items;
                    405:     return unless (ref($cachekeys) eq 'ARRAY');
                    406:     my $cachestr = join('&',@{$cachekeys});
                    407:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   408:     return $response;
                    409: }
                    410: 
1.1       albertel  411: # -------------------------------------------------- Non-critical communication
                    412: sub subreply {
                    413:     my ($cmd,$server)=@_;
1.838     albertel  414:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      415:     #
                    416:     #  With loncnew process trimming, there's a timing hole between lonc server
                    417:     #  process exit and the master server picking up the listen on the AF_UNIX
                    418:     #  socket.  In that time interval, a lock file will exist:
                    419: 
                    420:     my $lockfile=$peerfile.".lock";
                    421:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1289    damieng   422: 	sleep(0.1);
1.549     foxr      423:     }
                    424:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      425:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      426:     #
1.550     foxr      427:     #   We'll give the connection a few tries before abandoning it.  If
                    428:     #   connection is not possible, we'll con_lost back to the client.
                    429:     #   
                    430:     my $client;
                    431:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    432: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    433: 				      Type    => SOCK_STREAM,
                    434: 				      Timeout => 10);
1.869     albertel  435: 	if ($client) {
1.550     foxr      436: 	    last;		# Connected!
1.850     albertel  437: 	} else {
1.853     albertel  438: 	    &create_connection(&hostname($server),$server);
1.550     foxr      439: 	}
1.1289    damieng   440:         sleep(0.1);	# Try again later if failed connection.
1.550     foxr      441:     }
                    442:     my $answer;
                    443:     if ($client) {
1.704     albertel  444: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      445: 	$answer=<$client>;
                    446: 	if (!$answer) { $answer="con_lost"; }
                    447: 	chomp($answer);
                    448:     } else {
                    449: 	$answer = 'con_lost';	# Failed connection.
                    450:     }
1.1       albertel  451:     return $answer;
                    452: }
                    453: 
                    454: sub reply {
                    455:     my ($cmd,$server)=@_;
1.838     albertel  456:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  457:     my $answer=subreply($cmd,$server);
1.65      www       458:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  459:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       460:                 " $cmd to $server returned $answer</font>");
                    461:     }
1.1       albertel  462:     return $answer;
                    463: }
                    464: 
                    465: # ----------------------------------------------------------- Send USR1 to lonc
                    466: 
                    467: sub reconlonc {
1.891     albertel  468:     my ($lonid) = @_;
                    469:     if ($lonid) {
1.1295    raeburn   470:         my $hostname = &hostname($lonid);
1.891     albertel  471: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    472: 	if ($hostname && -e $peerfile) {
                    473: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    474: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    475: 					     Type    => SOCK_STREAM,
                    476: 					     Timeout => 10);
                    477: 	    if ($client) {
                    478: 		print $client ("reset_retries\n");
                    479: 		my $answer=<$client>;
                    480: 		#reset just this one.
                    481: 	    }
                    482: 	}
                    483: 	return;
                    484:     }
                    485: 
1.836     www       486:     &logthis("Trying to reconnect lonc");
1.1       albertel  487:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  488:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  489: 	my $loncpid=<$fh>;
                    490:         chomp($loncpid);
                    491:         if (kill 0 => $loncpid) {
                    492: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    493:             kill USR1 => $loncpid;
                    494:             sleep 1;
1.1295    raeburn   495:         } else {
1.12      www       496: 	    &logthis(
1.672     albertel  497:                "<font color=\"blue\">WARNING:".
1.12      www       498:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  499:         }
                    500:     } else {
1.836     www       501: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  502:     }
                    503: }
                    504: 
                    505: # ------------------------------------------------------ Critical communication
1.12      www       506: 
1.1       albertel  507: sub critical {
                    508:     my ($cmd,$server)=@_;
1.838     albertel  509:     unless (&hostname($server)) {
1.672     albertel  510:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       511:                " Critical message to unknown server ($server)</font>");
                    512:         return 'no_such_host';
                    513:     }
1.1       albertel  514:     my $answer=reply($cmd,$server);
                    515:     if ($answer eq 'con_lost') {
1.1295    raeburn   516: 	&reconlonc($server);
1.589     albertel  517: 	my $answer=reply($cmd,$server);
1.1       albertel  518:         if ($answer eq 'con_lost') {
                    519:             my $now=time;
                    520:             my $middlename=$cmd;
1.5       www       521:             $middlename=substr($middlename,0,16);
1.1       albertel  522:             $middlename=~s/\W//g;
                    523:             my $dfilename=
1.305     www       524:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    525:             $dumpcount++;
1.1       albertel  526:             {
1.448     albertel  527: 		my $dfh;
                    528: 		if (open($dfh,">$dfilename")) {
                    529: 		    print $dfh "$cmd\n"; 
                    530: 		    close($dfh);
                    531: 		}
1.1       albertel  532:             }
1.1288    damieng   533:             sleep 1;
1.1       albertel  534:             my $wcmd='';
                    535:             {
1.448     albertel  536: 		my $dfh;
                    537: 		if (open($dfh,"<$dfilename")) {
                    538: 		    $wcmd=<$dfh>; 
                    539: 		    close($dfh);
                    540: 		}
1.1       albertel  541:             }
                    542:             chomp($wcmd);
1.7       www       543:             if ($wcmd eq $cmd) {
1.672     albertel  544: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       545:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  546:                 &logperm("D:$server:$cmd");
                    547: 	        return 'con_delayed';
                    548:             } else {
1.672     albertel  549:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       550:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  551:                 &logperm("F:$server:$cmd");
                    552:                 return 'con_failed';
                    553:             }
                    554:         }
                    555:     }
                    556:     return $answer;
1.405     albertel  557: }
                    558: 
1.755     albertel  559: # ------------------------------------------- check if return value is an error
                    560: 
                    561: sub error {
                    562:     my ($result) = @_;
1.756     albertel  563:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  564: 	if ($2 == 2) { return undef; }
                    565: 	return $1;
                    566:     }
                    567:     return undef;
                    568: }
                    569: 
1.783     albertel  570: sub convert_and_load_session_env {
                    571:     my ($lonidsdir,$handle)=@_;
                    572:     my @profile;
                    573:     {
1.917     albertel  574: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    575: 	if (!$opened) {
1.915     albertel  576: 	    return 0;
                    577: 	}
1.783     albertel  578: 	flock($idf,LOCK_SH);
                    579: 	@profile=<$idf>;
                    580: 	close($idf);
                    581:     }
                    582:     my %temp_env;
                    583:     foreach my $line (@profile) {
1.786     albertel  584: 	if ($line !~ m/=/) {
                    585: 	    return 0;
                    586: 	}
1.783     albertel  587: 	chomp($line);
                    588: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    589: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    590:     }
                    591:     unlink("$lonidsdir/$handle.id");
                    592:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    593: 	    0640)) {
                    594: 	%disk_env = %temp_env;
                    595: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    596: 	untie(%disk_env);
                    597:     }
1.786     albertel  598:     return 1;
1.783     albertel  599: }
                    600: 
1.374     www       601: # ------------------------------------------- Transfer profile into environment
1.780     albertel  602: my $env_loaded;
                    603: sub transfer_profile_to_env {
1.788     albertel  604:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    605:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       606: 
1.720     albertel  607:     if (!defined($lonidsdir)) {
                    608: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    609:     }
                    610:     if (!defined($handle)) {
                    611:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    612:     }
                    613: 
1.786     albertel  614:     my $convert;
                    615:     {
1.917     albertel  616:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    617: 	if (!$opened) {
1.915     albertel  618: 	    return;
                    619: 	}
1.786     albertel  620: 	flock($idf,LOCK_SH);
                    621: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    622: 		&GDBM_READER(),0640)) {
                    623: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    624: 	    untie(%disk_env);
                    625: 	} else {
                    626: 	    $convert = 1;
                    627: 	}
                    628:     }
                    629:     if ($convert) {
                    630: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    631: 	    &logthis("Failed to load session, or convert session.");
                    632: 	}
1.374     www       633:     }
1.783     albertel  634: 
1.786     albertel  635:     my %remove;
1.783     albertel  636:     while ( my $envname = each(%env) ) {
1.433     matthew   637:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    638:             if ($time < time-300) {
1.783     albertel  639:                 $remove{$key}++;
1.433     matthew   640:             }
                    641:         }
                    642:     }
1.783     albertel  643: 
1.619     albertel  644:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  645:     $env_loaded=1;
1.783     albertel  646:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   647:         &delenv($expired_key);
1.374     www       648:     }
1.1       albertel  649: }
                    650: 
1.916     albertel  651: # ---------------------------------------------------- Check for valid session 
                    652: sub check_for_valid_session {
1.1245    raeburn   653:     my ($r,$name,$userhashref) = @_;
1.916     albertel  654:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1337    raeburn   655:     my ($linkname,$pubname);
1.1155    raeburn   656:     if ($name eq '') {
                    657:         $name = 'lonID';
1.1337    raeburn   658:         $linkname = 'lonLinkID';
                    659:         $pubname = 'lonPubID';
1.1155    raeburn   660:     }
                    661:     my $lonid=$cookies{$name};
1.1337    raeburn   662:     if (!$lonid) {
                    663:         if (($name eq 'lonID') && ($ENV{'SERVER_PORT'} != 443) && ($linkname)) {
                    664:             $lonid=$cookies{$linkname};
                    665:         }
                    666:         if (!$lonid) {
                    667:             if (($name eq 'lonID') && ($pubname)) {
                    668:                 $lonid=$cookies{$pubname};
                    669:             }
                    670:         }
                    671:     }
1.916     albertel  672:     return undef if (!$lonid);
                    673: 
                    674:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   675:     my $lonidsdir;
                    676:     if ($name eq 'lonDAV') {
                    677:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    678:     } else {
                    679:         $lonidsdir=$r->dir_config('lonIDsDir');
                    680:     }
1.916     albertel  681:     return undef if (!-e "$lonidsdir/$handle.id");
                    682: 
1.917     albertel  683:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    684:     return undef if (!$opened);
1.916     albertel  685: 
                    686:     flock($idf,LOCK_SH);
                    687:     my %disk_env;
                    688:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    689: 	    &GDBM_READER(),0640)) {
                    690: 	return undef;	
                    691:     }
                    692: 
                    693:     if (!defined($disk_env{'user.name'})
                    694: 	|| !defined($disk_env{'user.domain'})) {
                    695: 	return undef;
                    696:     }
1.1245    raeburn   697: 
                    698:     if (ref($userhashref) eq 'HASH') {
                    699:         $userhashref->{'name'} = $disk_env{'user.name'};
                    700:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1212    raeburn   701:     }
1.1245    raeburn   702: 
1.916     albertel  703:     return $handle;
                    704: }
                    705: 
1.830     albertel  706: sub timed_flock {
                    707:     my ($file,$lock_type) = @_;
                    708:     my $failed=0;
                    709:     eval {
                    710: 	local $SIG{__DIE__}='DEFAULT';
                    711: 	local $SIG{ALRM}=sub {
                    712: 	    $failed=1;
                    713: 	    die("failed lock");
                    714: 	};
                    715: 	alarm(13);
                    716: 	flock($file,$lock_type);
                    717: 	alarm(0);
                    718:     };
                    719:     if ($failed) {
                    720: 	return undef;
                    721:     } else {
                    722: 	return 1;
                    723:     }
                    724: }
                    725: 
1.5       www       726: # ---------------------------------------------------------- Append Environment
                    727: 
                    728: sub appenv {
1.949     raeburn   729:     my ($newenv,$roles) = @_;
                    730:     if (ref($newenv) eq 'HASH') {
                    731:         foreach my $key (keys(%{$newenv})) {
                    732:             my $refused = 0;
                    733: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    734:                 $refused = 1;
                    735:                 if (ref($roles) eq 'ARRAY') {
1.1250    raeburn   736:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   737:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    738:                         $refused = 0;
                    739:                     }
                    740:                 }
                    741:             }
                    742:             if ($refused) {
                    743:                 &logthis("<font color=\"blue\">WARNING: ".
                    744:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    745:                          .'</font>');
                    746: 	        delete($newenv->{$key});
                    747:             } else {
                    748:                 $env{$key}=$newenv->{$key};
                    749:             }
                    750:         }
                    751:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    752:         if ($opened
                    753: 	    && &timed_flock($env_file,LOCK_EX)
                    754: 	    &&
                    755: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    756: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    757: 	    while (my ($key,$value) = each(%{$newenv})) {
                    758: 	        $disk_env{$key} = $value;
                    759: 	    }
                    760: 	    untie(%disk_env);
1.35      www       761:         }
1.191     harris41  762:     }
1.56      www       763:     return 'ok';
                    764: }
                    765: # ----------------------------------------------------- Delete from Environment
                    766: 
                    767: sub delenv {
1.1104    raeburn   768:     my ($delthis,$regexp,$roles) = @_;
                    769:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    770:         my $refused = 1;
                    771:         if (ref($roles) eq 'ARRAY') {
                    772:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    773:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    774:                 $refused = 0;
                    775:             }
                    776:         }
                    777:         if ($refused) {
                    778:             &logthis("<font color=\"blue\">WARNING: ".
                    779:                      "Attempt to delete from environment ".$delthis);
                    780:             return 'error';
                    781:         }
1.56      www       782:     }
1.917     albertel  783:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    784:     if ($opened
1.915     albertel  785: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  786: 	&&
                    787: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    788: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  789: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   790: 	    if ($regexp) {
                    791:                 if ($key=~/^$delthis/) {
                    792:                     delete($env{$key});
                    793:                     delete($disk_env{$key});
                    794:                 } 
                    795:             } else {
                    796:                 if ($key=~/^\Q$delthis\E/) {
                    797: 		    delete($env{$key});
                    798: 		    delete($disk_env{$key});
                    799: 	        }
                    800:             }
1.448     albertel  801: 	}
1.783     albertel  802: 	untie(%disk_env);
1.5       www       803:     }
                    804:     return 'ok';
1.369     albertel  805: }
                    806: 
1.790     albertel  807: sub get_env_multiple {
                    808:     my ($name) = @_;
                    809:     my @values;
                    810:     if (defined($env{$name})) {
                    811:         # exists is it an array
                    812:         if (ref($env{$name})) {
                    813:             @values=@{ $env{$name} };
                    814:         } else {
                    815:             $values[0]=$env{$name};
                    816:         }
                    817:     }
                    818:     return(@values);
                    819: }
                    820: 
1.958     www       821: # ------------------------------------------------------------------- Locking
                    822: 
                    823: sub set_lock {
                    824:     my ($text)=@_;
                    825:     $locknum++;
                    826:     my $id=$$.'-'.$locknum;
                    827:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    828:              'session.lock.'.$id => $text});
                    829:     return $id;
                    830: }
                    831: 
                    832: sub get_locks {
                    833:     my $num=0;
                    834:     my %texts=();
                    835:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    836:        if ($lock=~/\w/) {
                    837:           $num++;
                    838:           $texts{$lock}=$env{'session.lock.'.$lock};
                    839:        }
                    840:    }
                    841:    return ($num,%texts);
                    842: }
                    843: 
                    844: sub remove_lock {
                    845:     my ($id)=@_;
                    846:     my $newlocks='';
                    847:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    848:        if (($lock=~/\w/) && ($lock ne $id)) {
                    849:           $newlocks.=','.$lock;
                    850:        }
                    851:     }
                    852:     &appenv({'session.locks' => $newlocks});
                    853:     &delenv('session.lock.'.$id);
                    854: }
                    855: 
                    856: sub remove_all_locks {
                    857:     my $activelocks=$env{'session.locks'};
                    858:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    859:        if ($lock=~/\w/) {
                    860:           &remove_lock($lock);
                    861:        }
                    862:     }
                    863: }
                    864: 
                    865: 
1.369     albertel  866: # ------------------------------------------ Find out current server userload
                    867: sub userload {
                    868:     my $numusers=0;
                    869:     {
                    870: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    871: 	my $filename;
                    872: 	my $curtime=time;
                    873: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  874: 	    next if ($filename eq '.' || $filename eq '..');
                    875: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  876: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  877: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  878: 	}
                    879: 	closedir(LONIDS);
                    880:     }
                    881:     my $userloadpercent=0;
                    882:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    883:     if ($maxuserload) {
1.371     albertel  884: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  885:     }
1.372     albertel  886:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  887:     return $userloadpercent;
1.283     www       888: }
                    889: 
1.1       albertel  890: # ------------------------------ Find server with least workload from spare.tab
1.11      www       891: 
1.1       albertel  892: sub spareserver {
1.1083    raeburn   893:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  894:     my $spare_server;
1.370     albertel  895:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  896:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    897:                                                      :  $userloadpercent;
1.1083    raeburn   898:     my ($uint_dom,$remotesessions);
                    899:     if (($udom ne '') && (&domain($udom) ne '')) {
                    900:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    901:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    902:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    903:         $remotesessions = $udomdefaults{'remotesessions'};
                    904:     }
1.1123    raeburn   905:     my $spareshash = &this_host_spares($udom);
                    906:     if (ref($spareshash) eq 'HASH') {
                    907:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    908:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279    raeburn   909:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    910:                                              $try_server));
1.1123    raeburn   911: 	        ($spare_server, $lowest_load) =
                    912: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    913:             }
1.1083    raeburn   914:         }
1.784     albertel  915: 
1.1123    raeburn   916:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    917: 
                    918:         if (!$found_server) {
                    919:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    920: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn   921:                     next unless (&spare_can_host($udom,$uint_dom,
                    922:                                                  $remotesessions,$try_server));
1.1123    raeburn   923: 	            ($spare_server, $lowest_load) =
                    924: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    925:                 }
                    926: 	    }
                    927:         }
1.784     albertel  928:     }
                    929: 
                    930:     if (!$want_server_name) {
1.968     raeburn   931:         my $protocol = 'http';
                    932:         if ($protocol{$spare_server} eq 'https') {
                    933:             $protocol = $protocol{$spare_server};
                    934:         }
1.1001    raeburn   935:         if (defined($spare_server)) {
                    936:             my $hostname = &hostname($spare_server);
1.1083    raeburn   937:             if (defined($hostname)) {
1.1001    raeburn   938: 	        $spare_server = $protocol.'://'.$hostname;
                    939:             }
                    940:         }
1.784     albertel  941:     }
                    942:     return $spare_server;
                    943: }
                    944: 
                    945: sub compare_server_load {
1.1253    raeburn   946:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    947: 
                    948:     if ($required) {
                    949:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    950:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    951:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    952:         if (($major eq '' && $minor eq '') ||
                    953:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    954:             return ($spare_server,$lowest_load);
                    955:         }
                    956:     }
1.784     albertel  957: 
                    958:     my $loadans     = &reply('load',    $try_server);
                    959:     my $userloadans = &reply('userload',$try_server);
                    960: 
                    961:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   962: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  963:     }
                    964: 
                    965:     my $load;
                    966:     if ($loadans =~ /\d/) {
                    967: 	if ($userloadans =~ /\d/) {
                    968: 	    #both are numbers, pick the bigger one
                    969: 	    $load = ($loadans > $userloadans) ? $loadans 
                    970: 		                              : $userloadans;
1.411     albertel  971: 	} else {
1.784     albertel  972: 	    $load = $loadans;
1.411     albertel  973: 	}
1.784     albertel  974:     } else {
                    975: 	$load = $userloadans;
                    976:     }
                    977: 
                    978:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    979: 	$spare_server = $try_server;
                    980: 	$lowest_load  = $load;
1.370     albertel  981:     }
1.784     albertel  982:     return ($spare_server,$lowest_load);
1.202     matthew   983: }
1.914     albertel  984: 
                    985: # --------------------------- ask offload servers if user already has a session
                    986: sub find_existing_session {
                    987:     my ($udom,$uname) = @_;
1.1123    raeburn   988:     my $spareshash = &this_host_spares($udom);
                    989:     if (ref($spareshash) eq 'HASH') {
                    990:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    991:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    992:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    993:             }
                    994:         }
                    995:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    996:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    997:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    998:             }
                    999:         }
1.914     albertel 1000:     }
                   1001:     return;
                   1002: }
                   1003: 
                   1004: # -------------------------------- ask if server already has a session for user
                   1005: sub has_user_session {
                   1006:     my ($lonid,$udom,$uname) = @_;
                   1007:     my $result = &reply(join(':','userhassession',
                   1008: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1009:     return 1 if ($result eq 'ok');
                   1010: 
                   1011:     return 0;
                   1012: }
                   1013: 
1.1076    raeburn  1014: # --------- determine least loaded server in a user's domain which allows login
                   1015: 
                   1016: sub choose_server {
1.1259    raeburn  1017:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1018:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1019:     my %servers = &get_servers($udom);
1.1076    raeburn  1020:     my $lowest_load = 30000;
1.1259    raeburn  1021:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1022:     if ($skiploadbal) {
                   1023:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1024:         unless (defined($cached)) {
                   1025:             my $cachetime = 60*60*24;
                   1026:             my %domconfig =
                   1027:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1028:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1029:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1030:                                            $cachetime);
                   1031:             }
                   1032:         }
                   1033:     }
1.1076    raeburn  1034:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn  1035:         if ($skiploadbal) {
                   1036:             if (ref($balancers) eq 'HASH') {
                   1037:                 next if (exists($balancers->{$lonhost}));
                   1038:             }
                   1039:         }   
1.1115    raeburn  1040:         my $loginvia;
                   1041:         if ($checkloginvia) {
                   1042:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1043:             if ($loginvia) {
                   1044:                 my ($server,$path) = split(/:/,$loginvia);
                   1045:                 ($login_host, $lowest_load) =
1.1253    raeburn  1046:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1047:                 if ($login_host eq $server) {
                   1048:                     $portal_path = $path;
1.1151    raeburn  1049:                     $isredirect = 1;
1.1116    raeburn  1050:                 }
                   1051:             } else {
                   1052:                 ($login_host, $lowest_load) =
1.1253    raeburn  1053:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1054:                 if ($login_host eq $lonhost) {
                   1055:                     $portal_path = '';
1.1151    raeburn  1056:                     $isredirect = ''; 
1.1116    raeburn  1057:                 }
                   1058:             }
                   1059:         } else {
1.1076    raeburn  1060:             ($login_host, $lowest_load) =
1.1253    raeburn  1061:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1062:         }
                   1063:     }
                   1064:     if ($login_host ne '') {
1.1116    raeburn  1065:         $hostname = &hostname($login_host);
1.1076    raeburn  1066:     }
1.1331    raeburn  1067:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1068: }
                   1069: 
1.202     matthew  1070: # --------------------------------------------- Try to change a user's password
                   1071: 
                   1072: sub changepass {
1.799     raeburn  1073:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1074:     $currentpass = &escape($currentpass);
                   1075:     $newpass     = &escape($newpass);
1.1030    raeburn  1076:     my $lonhost = $perlvar{'lonHostID'};
                   1077:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1078: 		       $server);
                   1079:     if (! $answer) {
                   1080: 	&logthis("No reply on password change request to $server ".
                   1081: 		 "by $uname in domain $udom.");
                   1082:     } elsif ($answer =~ "^ok") {
                   1083:         &logthis("$uname in $udom successfully changed their password ".
                   1084: 		 "on $server.");
                   1085:     } elsif ($answer =~ "^pwchange_failure") {
                   1086: 	&logthis("$uname in $udom was unable to change their password ".
                   1087: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1088: 		 "or pwchange");
                   1089:     } elsif ($answer =~ "^non_authorized") {
                   1090:         &logthis("$uname in $udom did not get their password correct when ".
                   1091: 		 "attempting to change it on $server.");
                   1092:     } elsif ($answer =~ "^auth_mode_error") {
                   1093:         &logthis("$uname in $udom attempted to change their password despite ".
                   1094: 		 "not being locally or internally authenticated on $server.");
                   1095:     } elsif ($answer =~ "^unknown_user") {
                   1096:         &logthis("$uname in $udom attempted to change their password ".
                   1097: 		 "on $server but were unable to because $server is not ".
                   1098: 		 "their home server.");
                   1099:     } elsif ($answer =~ "^refused") {
                   1100: 	&logthis("$server refused to change $uname in $udom password because ".
                   1101: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1102:     } elsif ($answer =~ "invalid_client") {
                   1103:         &logthis("$server refused to change $uname in $udom password because ".
                   1104:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1105:     }
                   1106:     return $answer;
1.1       albertel 1107: }
                   1108: 
1.169     harris41 1109: # ----------------------- Try to determine user's current authentication scheme
                   1110: 
                   1111: sub queryauthenticate {
                   1112:     my ($uname,$udom)=@_;
1.456     albertel 1113:     my $uhome=&homeserver($uname,$udom);
                   1114:     if (!$uhome) {
                   1115: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1116: 	return 'no_host';
                   1117:     }
                   1118:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1119:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1120: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1121:     }
1.456     albertel 1122:     return $answer;
1.169     harris41 1123: }
                   1124: 
1.1       albertel 1125: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1126: 
1.1       albertel 1127: sub authenticate {
1.1073    raeburn  1128:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1129:     $upass=&escape($upass);
                   1130:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1131:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1132:     my $newhome;
1.836     www      1133:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1134: # Maybe the machine was offline and only re-appeared again recently?
                   1135:         &reconlonc();
                   1136: # One more
1.952     raeburn  1137: 	$uhome=&homeserver($uname,$udom,1);
                   1138:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1139:             if (defined(&domain($udom,'primary'))) {
                   1140:                 $newhome=&domain($udom,'primary');
                   1141:             }
                   1142:             if ($newhome ne '') {
                   1143:                 $uhome = $newhome;
                   1144:             }
                   1145:         }
1.836     www      1146: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1147: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1148: 	    return 'no_host';
                   1149:         }
1.1       albertel 1150:     }
1.1073    raeburn  1151:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1152:     if ($answer eq 'authorized') {
1.952     raeburn  1153:         if ($newhome) {
                   1154:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1155:             return 'no_account_on_host'; 
                   1156:         } else {
                   1157:             &logthis("User $uname at $udom authorized by $uhome");
                   1158:             return $uhome;
                   1159:         }
1.471     albertel 1160:     }
                   1161:     if ($answer eq 'non_authorized') {
                   1162: 	&logthis("User $uname at $udom rejected by $uhome");
                   1163: 	return 'no_host'; 
1.9       www      1164:     }
1.471     albertel 1165:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1166:     return 'no_host';
                   1167: }
                   1168: 
1.1073    raeburn  1169: sub can_host_session {
1.1074    raeburn  1170:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1171:     my $canhost = 1;
1.1074    raeburn  1172:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1173:     if (ref($remotesessions) eq 'HASH') {
                   1174:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1175:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1176:                 $canhost = 0;
                   1177:             } else {
                   1178:                 $canhost = 1;
                   1179:             }
                   1180:         }
                   1181:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1182:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1183:                 $canhost = 1;
                   1184:             } else {
                   1185:                 $canhost = 0;
                   1186:             }
                   1187:         }
                   1188:         if ($canhost) {
                   1189:             if ($remotesessions->{'version'} ne '') {
                   1190:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1191:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1192:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1193:                         my $major = $1;
                   1194:                         my $minor = $2;
                   1195:                         if (($major < $reqmajor ) ||
                   1196:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1197:                             $canhost = 0;
                   1198:                         }
                   1199:                     } else {
                   1200:                         $canhost = 0;
                   1201:                     }
                   1202:                 }
                   1203:             }
                   1204:         }
                   1205:     }
                   1206:     if ($canhost) {
                   1207:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1208:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1209:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1210:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1211:                 if (($uint_dom ne '') && 
                   1212:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1213:                     $canhost = 0;
                   1214:                 } else {
                   1215:                     $canhost = 1;
                   1216:                 }
                   1217:             }
                   1218:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1219:                 if (($uint_dom ne '') && 
                   1220:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1221:                     $canhost = 1;
                   1222:                 } else {
                   1223:                     $canhost = 0;
                   1224:                 }
                   1225:             }
                   1226:         }
                   1227:     }
                   1228:     return $canhost;
                   1229: }
                   1230: 
1.1083    raeburn  1231: sub spare_can_host {
                   1232:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1233:     my $canhost=1;
1.1279    raeburn  1234:     my $try_server_hostname = &hostname($try_server);
                   1235:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1236:     my $serverhomedom = &host_domain($serverhomeID);
                   1237:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1238:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1239:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1240:             $canhost = 0;
                   1241:         }
                   1242:     }
                   1243:     if (($canhost) && ($uint_dom)) {
                   1244:         my @intdoms;
                   1245:         my $internet_names = &get_internet_names($try_server);
                   1246:         if (ref($internet_names) eq 'ARRAY') {
                   1247:             @intdoms = @{$internet_names};
                   1248:         }
                   1249:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1250:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1251:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1252:                                          $remotesessions,
                   1253:                                          $defdomdefaults{'hostedsessions'});
                   1254:         }
1.1083    raeburn  1255:     }
                   1256:     return $canhost;
                   1257: }
                   1258: 
1.1123    raeburn  1259: sub this_host_spares {
                   1260:     my ($dom) = @_;
1.1126    raeburn  1261:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1262:     my @hosts = &current_machine_ids();
                   1263:     foreach my $lonhost (@hosts) {
                   1264:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1265:             $dom_in_use = $dom;
                   1266:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1267:             last;
                   1268:         }
                   1269:     }
1.1126    raeburn  1270:     if ($dom_in_use ne '') {
                   1271:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1272:     }
                   1273:     if (ref($result) ne 'HASH') {
                   1274:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1275:         $dom_in_use = &host_domain($lonhost_in_use);
                   1276:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1277:         if (ref($result) ne 'HASH') {
                   1278:             $result = \%spareid;
                   1279:         }
                   1280:     }
                   1281:     return $result;
                   1282: }
                   1283: 
                   1284: sub spares_for_offload  {
                   1285:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1286:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1287:     if (defined($cached)) {
                   1288:         return $result;
                   1289:     } else {
1.1126    raeburn  1290:         my $cachetime = 60*60*24;
                   1291:         my %domconfig =
                   1292:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1293:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1294:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1295:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1296:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1297:                 }
                   1298:             }
                   1299:         }
                   1300:     }
1.1126    raeburn  1301:     return;
1.1123    raeburn  1302: }
                   1303: 
1.1129    raeburn  1304: sub get_lonbalancer_config {
                   1305:     my ($servers) = @_;
                   1306:     my ($currbalancer,$currtargets);
                   1307:     if (ref($servers) eq 'HASH') {
                   1308:         foreach my $server (keys(%{$servers})) {
                   1309:             my %what = (
                   1310:                          spareid => 1,
                   1311:                          perlvar => 1,
                   1312:                        );
                   1313:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1314:             if ($result eq 'ok') {
                   1315:                 if (ref($returnhash) eq 'HASH') {
                   1316:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1317:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1318:                             $currbalancer = $server;
                   1319:                             $currtargets = {};
                   1320:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1321:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1322:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1323:                                 }
                   1324:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1325:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1326:                                 }
                   1327:                             }
                   1328:                             last;
                   1329:                         }
                   1330:                     }
                   1331:                 }
                   1332:             }
                   1333:         }
                   1334:     }
                   1335:     return ($currbalancer,$currtargets);
                   1336: }
                   1337: 
                   1338: sub check_loadbalancing {
1.1331    raeburn  1339:     my ($uname,$udom,$caller) = @_;
1.1191    raeburn  1340:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1341:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1342:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1343:     my @hosts = &current_machine_ids();
1.1129    raeburn  1344:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1345:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1346:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1347:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1348:     my $domneedscache;
1.1129    raeburn  1349:     my $cachetime = 60*60*24;
                   1350: 
                   1351:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1352:         $dom_in_use = $udom;
                   1353:         $homeintdom = 1;
                   1354:     } else {
                   1355:         $dom_in_use = $serverhomedom;
                   1356:     }
                   1357:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1358:     unless (defined($cached)) {
                   1359:         my %domconfig =
                   1360:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1361:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1362:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1363:         } else {
                   1364:             $domneedscache = $dom_in_use;
1.1129    raeburn  1365:         }
                   1366:     }
                   1367:     if (ref($result) eq 'HASH') {
1.1191    raeburn  1368:         ($is_balancer,$currtargets,$currrules) = 
                   1369:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1370:         if ($is_balancer) {
                   1371:             if (ref($currrules) eq 'HASH') {
                   1372:                 if ($homeintdom) {
                   1373:                     if ($uname ne '') {
                   1374:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1375:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1376:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1377:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1378:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1379:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1380:                             }
                   1381:                         }
                   1382:                         if ($rule_in_effect eq '') {
                   1383:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1384:                             if ($userenv{'inststatus'} ne '') {
                   1385:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1386:                                 my ($othertitle,$usertypes,$types) =
                   1387:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1388:                                 if (ref($types) eq 'ARRAY') {
                   1389:                                     foreach my $type (@{$types}) {
                   1390:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1391:                                             if (exists($currrules->{$type})) {
                   1392:                                                 $rule_in_effect = $currrules->{$type};
                   1393:                                             }
                   1394:                                         }
                   1395:                                     }
                   1396:                                 }
                   1397:                             } else {
                   1398:                                 if (exists($currrules->{'default'})) {
                   1399:                                     $rule_in_effect = $currrules->{'default'};
                   1400:                                 }
                   1401:                             }
                   1402:                         }
                   1403:                     } else {
                   1404:                         if (exists($currrules->{'default'})) {
                   1405:                             $rule_in_effect = $currrules->{'default'};
                   1406:                         }
                   1407:                     }
                   1408:                 } else {
                   1409:                     if ($currrules->{'_LC_external'} ne '') {
                   1410:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1411:                     }
                   1412:                 }
                   1413:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1414:                                                        $uname,$udom);
                   1415:             }
                   1416:         }
                   1417:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1418:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1419:         unless (defined($cached)) {
                   1420:             my %domconfig =
                   1421:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1422:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1423:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1424:             } else {
                   1425:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1426:             }
                   1427:         }
                   1428:         if (ref($result) eq 'HASH') {
1.1191    raeburn  1429:             ($is_balancer,$currtargets,$currrules) = 
                   1430:                 &check_balancer_result($result,@hosts);
                   1431:             if ($is_balancer) {
1.1129    raeburn  1432:                 if (ref($currrules) eq 'HASH') {
                   1433:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1434:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1435:                     }
                   1436:                 }
                   1437:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1438:                                                        $uname,$udom);
                   1439:             }
                   1440:         } else {
                   1441:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1442:                 $is_balancer = 1;
                   1443:                 $offloadto = &this_host_spares($dom_in_use);
                   1444:             }
1.1307    raeburn  1445:             unless (defined($cached)) {
                   1446:                 $domneedscache = $serverhomedom;
                   1447:             }
1.1129    raeburn  1448:         }
                   1449:     } else {
                   1450:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1451:             $is_balancer = 1;
                   1452:             $offloadto = &this_host_spares($dom_in_use);
                   1453:         }
1.1307    raeburn  1454:         unless (defined($cached)) {
                   1455:             $domneedscache = $serverhomedom;
                   1456:         }
                   1457:     }
                   1458:     if ($domneedscache) {
                   1459:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1460:     }
1.1176    raeburn  1461:     if ($is_balancer) {
                   1462:         my $lowest_load = 30000;
                   1463:         if (ref($offloadto) eq 'HASH') {
                   1464:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1465:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1466:                     ($otherserver,$lowest_load) =
                   1467:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1468:                 }
1.1129    raeburn  1469:             }
1.1176    raeburn  1470:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1471: 
1.1176    raeburn  1472:             if (!$found_server) {
                   1473:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1474:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1475:                         ($otherserver,$lowest_load) =
                   1476:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1477:                     }
                   1478:                 }
                   1479:             }
                   1480:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1481:             if (@{$offloadto} == 1) {
                   1482:                 $otherserver = $offloadto->[0];
                   1483:             } elsif (@{$offloadto} > 1) {
                   1484:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1485:                     ($otherserver,$lowest_load) =
                   1486:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1487:                 }
                   1488:             }
                   1489:         }
1.1331    raeburn  1490:         unless ($caller eq 'login') {
                   1491:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1492:                 $is_balancer = 0;
                   1493:                 if ($uname ne '' && $udom ne '') {
                   1494:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1176    raeburn  1495:                     
1.1331    raeburn  1496:                         &appenv({'user.loadbalexempt'     => $lonhost,  
                   1497:                                  'user.loadbalcheck.time' => time});
                   1498:                     }
1.1176    raeburn  1499:                 }
1.1129    raeburn  1500:             }
                   1501:         }
                   1502:     }
                   1503:     return ($is_balancer,$otherserver);
                   1504: }
                   1505: 
1.1191    raeburn  1506: sub check_balancer_result {
                   1507:     my ($result,@hosts) = @_;
                   1508:     my ($is_balancer,$currtargets,$currrules);
                   1509:     if (ref($result) eq 'HASH') {
                   1510:         if ($result->{'lonhost'} ne '') {
                   1511:             my $currbalancer = $result->{'lonhost'};
                   1512:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1513:                 $is_balancer = 1;
                   1514:                 $currtargets = $result->{'targets'};
                   1515:                 $currrules = $result->{'rules'};
                   1516:             }
                   1517:         } else {
                   1518:             foreach my $key (keys(%{$result})) {
                   1519:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1520:                     (ref($result->{$key}) eq 'HASH')) {
                   1521:                     $is_balancer = 1;
                   1522:                     $currrules = $result->{$key}{'rules'};
                   1523:                     $currtargets = $result->{$key}{'targets'};
                   1524:                     last;
                   1525:                 }
                   1526:             }
                   1527:         }
                   1528:     }
                   1529:     return ($is_balancer,$currtargets,$currrules);
                   1530: }
                   1531: 
1.1129    raeburn  1532: sub get_loadbalancer_targets {
                   1533:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1534:     my $offloadto;
1.1175    raeburn  1535:     if ($rule_in_effect eq 'none') {
                   1536:         return [$perlvar{'lonHostID'}];
                   1537:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1538:         $offloadto = $currtargets;
                   1539:     } else {
                   1540:         if ($rule_in_effect eq 'homeserver') {
                   1541:             my $homeserver = &homeserver($uname,$udom);
                   1542:             if ($homeserver ne 'no_host') {
                   1543:                 $offloadto = [$homeserver];
                   1544:             }
                   1545:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1546:             my %domconfig =
                   1547:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1548:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1549:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1550:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1551:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1552:                     }
                   1553:                 }
                   1554:             } else {
1.1178    raeburn  1555:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1556:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1557:                 if (&hostname($remotebalancer) ne '') {
                   1558:                     $offloadto = [$remotebalancer];
                   1559:                 }
                   1560:             }
                   1561:         } elsif (&hostname($rule_in_effect) ne '') {
                   1562:             $offloadto = [$rule_in_effect];
                   1563:         }
                   1564:     }
                   1565:     return $offloadto;
                   1566: }
                   1567: 
1.1127    raeburn  1568: sub internet_dom_servers {
                   1569:     my ($dom) = @_;
                   1570:     my (%uniqservers,%servers);
                   1571:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1572:     my @machinedoms = &machine_domains($primaryserver);
                   1573:     foreach my $mdom (@machinedoms) {
                   1574:         my %currservers = %servers;
                   1575:         my %server = &get_servers($mdom);
                   1576:         %servers = (%currservers,%server);
                   1577:     }
                   1578:     my %by_hostname;
                   1579:     foreach my $id (keys(%servers)) {
                   1580:         push(@{$by_hostname{$servers{$id}}},$id);
                   1581:     }
                   1582:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1583:         if (@{$by_hostname{$hostname}} > 1) {
                   1584:             my $match = 0;
                   1585:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1586:                 if (&host_domain($id) eq $dom) {
                   1587:                     $uniqservers{$id} = $hostname;
                   1588:                     $match = 1;
                   1589:                 }
                   1590:             }
                   1591:             unless ($match) {
                   1592:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1593:             }
                   1594:         } else {
                   1595:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1596:         }
                   1597:     }
                   1598:     return %uniqservers;
                   1599: }
                   1600: 
1.1347    raeburn  1601: sub trusted_domains {
                   1602:     my ($cmdtype,$calldom) = @_;
                   1603:     my (%trusted,%untrusted);
                   1604:     if (&domain($calldom) eq '') {
                   1605:         return (\%trusted,\%untrusted);
                   1606:     }
                   1607:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|domroles|catalog|reqcrs|msg)$/) {
                   1608:         return (\%trusted,\%untrusted);
                   1609:     }
                   1610:     my $callprimary = &domain($calldom,'primary');
                   1611:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
                   1612:     if ($intcalldom eq '') {
                   1613:         return (\%trusted,\%untrusted);
                   1614:     }
                   1615: 
                   1616:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
                   1617:     unless (defined($cached)) {
                   1618:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
                   1619:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
                   1620:         $trustconfig = $domconfig{'trust'};
                   1621:     }
                   1622:     if (ref($trustconfig)) {
                   1623:         my (%possexc,%possinc,@allexc,@allinc); 
                   1624:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
                   1625:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
                   1626:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
                   1627:             }
                   1628:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
                   1629:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
                   1630:             }
                   1631:         }
                   1632:         if (keys(%possexc)) {
                   1633:             if (keys(%possinc)) {
                   1634:                 foreach my $key (sort(keys(%possexc))) {
                   1635:                     next if ($key eq $intcalldom);
                   1636:                     unless ($possinc{$key}) {
                   1637:                         push(@allexc,$key);
                   1638:                     }
                   1639:                 }
                   1640:             } else {
                   1641:                 @allexc = sort(keys(%possexc));
                   1642:             }
                   1643:         }
                   1644:         if (keys(%possinc)) {
                   1645:             $possinc{$intcalldom} = 1;
                   1646:             @allinc = sort(keys(%possinc));
                   1647:         }
                   1648:         if ((@allexc > 0) || (@allinc > 0)) {
                   1649:             my %doms_by_intdom;
                   1650:             my %allintdoms = &all_host_intdom();
                   1651:             my %alldoms = &all_host_domain();
                   1652:             foreach my $key (%allintdoms) {
                   1653:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
                   1654:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
                   1655:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
                   1656:                     }
                   1657:                 } else {
                   1658:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
                   1659:                 }
                   1660:             }
                   1661:             foreach my $exc (@allexc) {
                   1662:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
                   1663:                     map { $untrusted{$_}; } @{$doms_by_intdom{$exc}};
                   1664:                 }
                   1665:             }
                   1666:             foreach my $inc (@allinc) {
                   1667:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
                   1668:                     map { $trusted{$_}; } @{$doms_by_intdom{$inc}};
                   1669:                 }
                   1670:             }
                   1671:         }
                   1672:     }
                   1673:     return(\%trusted,\%untrusted);
                   1674: }
                   1675: 
                   1676: sub will_trust {
                   1677:     my ($cmdtype,$domain,$possdom) = @_;
                   1678:     return 1 if ($domain eq $possdom);
                   1679:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
                   1680:     my $willtrust; 
                   1681:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
                   1682:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
                   1683:             $willtrust = 1;
                   1684:         }
                   1685:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
                   1686:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
                   1687:             $willtrust = 1;
                   1688:         }
                   1689:     } else {
                   1690:         $willtrust = 1;
                   1691:     }
                   1692:     return $willtrust;
                   1693: }
                   1694: 
1.1       albertel 1695: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1696: 
1.599     albertel 1697: my %homecache;
1.1       albertel 1698: sub homeserver {
1.230     stredwic 1699:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1700:     my $index="$uname:$udom";
1.426     albertel 1701: 
1.599     albertel 1702:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1703: 
                   1704:     my %servers = &get_servers($udom,'library');
                   1705:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1706:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1707: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1708: 
                   1709: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1710: 	if ($answer eq 'found') {
                   1711: 	    delete($badServerCache{$tryserver}); 
                   1712: 	    return $homecache{$index}=$tryserver;
                   1713: 	} elsif ($answer eq 'no_host') {
                   1714: 	    $badServerCache{$tryserver}=1;
                   1715: 	}
1.1       albertel 1716:     }    
                   1717:     return 'no_host';
1.70      www      1718: }
                   1719: 
1.1300    raeburn  1720: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1721: 
                   1722: sub idget {
1.1300    raeburn  1723:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1724:     my %returnhash=();
1.1300    raeburn  1725:     my @ids=(); 
                   1726:     if (ref($idsref) eq 'ARRAY') {
                   1727:         @ids = @{$idsref};
                   1728:     } else {
                   1729:         return %returnhash; 
                   1730:     }
                   1731:     if ($namespace eq '') {
                   1732:         $namespace = 'ids';
                   1733:     }
1.70      www      1734:     
1.841     albertel 1735:     my %servers = &get_servers($udom,'library');
                   1736:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1737: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1738: 	if ($namespace eq 'ids') {
                   1739: 	    $idlist=~tr/A-Z/a-z/;
                   1740: 	}
                   1741: 	my $reply;
                   1742: 	if ($namespace eq 'ids') {
                   1743: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1744: 	} else {
                   1745: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1746: 	}
1.841     albertel 1747: 	my @answer=();
                   1748: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1749: 	    @answer=split(/\&/,$reply);
                   1750: 	}                    ;
                   1751: 	my $i;
                   1752: 	for ($i=0;$i<=$#ids;$i++) {
                   1753: 	    if ($answer[$i]) {
1.1299    raeburn  1754: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1755: 	    }
1.841     albertel 1756: 	}
1.1300    raeburn  1757:     }
1.70      www      1758:     return %returnhash;
                   1759: }
                   1760: 
                   1761: # ------------------------------------- Find the IDs behind a list of usernames
                   1762: 
                   1763: sub idrget {
                   1764:     my ($udom,@unames)=@_;
                   1765:     my %returnhash=();
1.800     albertel 1766:     foreach my $uname (@unames) {
                   1767:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1768:     }
1.70      www      1769:     return %returnhash;
                   1770: }
                   1771: 
1.1300    raeburn  1772: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      1773: 
                   1774: sub idput {
1.1300    raeburn  1775:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      1776:     my %servers=();
1.1300    raeburn  1777:     my %ids=();
                   1778:     my %byid = ();
                   1779:     if (ref($idsref) eq 'HASH') {
                   1780:         %ids=%{$idsref};
                   1781:     }
                   1782:     if ($namespace eq '') {
                   1783:         $namespace = 'ids'; 
                   1784:     }
1.800     albertel 1785:     foreach my $uname (keys(%ids)) {
                   1786: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  1787:         if ($uhom eq '') {
                   1788:             $uhom=&homeserver($uname,$udom);
                   1789:         }
1.70      www      1790:         if ($uhom ne 'no_host') {
1.800     albertel 1791:             my $esc_unam=&escape($uname);
1.1300    raeburn  1792:             if ($namespace eq 'ids') {
                   1793:                 my $id=&escape($ids{$uname});
                   1794:                 $id=~tr/A-Z/a-z/;
                   1795:                 my $esc_unam=&escape($uname);
                   1796:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      1797:             } else {
1.1300    raeburn  1798:                 my @currids = split(/,/,$ids{$uname});
                   1799:                 foreach my $id (@currids) {
                   1800:                     $byid{$uhom}{$id} .= $uname.',';
                   1801:                 }
                   1802:             }
                   1803:         }
                   1804:     }
                   1805:     if ($namespace eq 'clickers') {
                   1806:         foreach my $server (keys(%byid)) {
                   1807:             if (ref($byid{$server}) eq 'HASH') {
                   1808:                 foreach my $id (keys(%{$byid{$server}})) {
                   1809:                     $byid{$server} =~ s/,$//;
                   1810:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   1811:                 }
1.70      www      1812:             }
                   1813:         }
1.191     harris41 1814:     }
1.800     albertel 1815:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1816:         $servers{$server} =~ s/\&$//;
                   1817:         if ($namespace eq 'ids') {     
                   1818:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   1819:         } else {
                   1820:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   1821:         }
1.191     harris41 1822:     }
1.344     www      1823: }
                   1824: 
1.1300    raeburn  1825: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  1826: 
                   1827: sub iddel {
1.1300    raeburn  1828:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  1829:     my %result=();
1.1300    raeburn  1830:     my %ids=();
                   1831:     my %byid = ();
                   1832:     if (ref($idshashref) eq 'HASH') {
                   1833:         %ids=%{$idshashref};
                   1834:     } else {
1.1231    raeburn  1835:         return %result;
                   1836:     }
1.1300    raeburn  1837:     if ($namespace eq '') {
                   1838:         $namespace = 'ids';
                   1839:     }
1.1231    raeburn  1840:     my %servers=();
1.1300    raeburn  1841:     while (my ($id,$unamestr) = each(%ids)) {
                   1842:         if ($namespace eq 'ids') {
                   1843:             my $uhom = $uhome;
                   1844:             if ($uhom eq '') { 
                   1845:                 $uhom=&homeserver($unamestr,$udom);
                   1846:             }
                   1847:             if ($uhom ne 'no_host') {
                   1848:                 $servers{$uhom}.='&'.&escape($id);
                   1849:             }
                   1850:          } else {
                   1851:             my @curritems = split(/,/,$ids{$id});
                   1852:             foreach my $uname (@curritems) {
                   1853:                 my $uhom = $uhome;
                   1854:                 if ($uhom eq '') {
                   1855:                     $uhom=&homeserver($uname,$udom);
                   1856:                 }
                   1857:                 if ($uhom ne 'no_host') { 
                   1858:                     $byid{$uhom}{$id} .= $uname.',';
                   1859:                 }
                   1860:             }
1.1231    raeburn  1861:         }
1.1300    raeburn  1862:     }
                   1863:     if ($namespace eq 'clickers') {
                   1864:         foreach my $server (keys(%byid)) {
                   1865:             if (ref($byid{$server}) eq 'HASH') {
                   1866:                 foreach my $id (keys(%{$byid{$server}})) {
                   1867:                     $byid{$server}{$id} =~ s/,$//;
                   1868:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   1869:                 }
1.1231    raeburn  1870:             }
                   1871:         }
                   1872:     }
                   1873:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1874:         $servers{$server} =~ s/\&$//;
                   1875:         if ($namespace eq 'ids') {
                   1876:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1877:         } elsif ($namespace eq 'clickers') {
                   1878:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   1879:         }
1.1231    raeburn  1880:     }
                   1881:     return %result;
                   1882: }
                   1883: 
1.1300    raeburn  1884: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   1885: 
                   1886: sub updateclickers {
                   1887:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   1888:     my %clickers;
                   1889:     if (ref($idshashref) eq 'HASH') {
                   1890:         %clickers=%{$idshashref};
                   1891:     } else {
                   1892:         return;
                   1893:     }
                   1894:     my $items='';
                   1895:     foreach my $item (keys(%clickers)) {
                   1896:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   1897:     }
                   1898:     $items=~s/\&$//;
                   1899:     my $request = "updateclickers:$udom:$action:$items";
                   1900:     if ($critical) {
                   1901:         return &critical($request,$uhome);
                   1902:     } else {
                   1903:         return &reply($request,$uhome);
                   1904:     }
                   1905: }
                   1906: 
1.1023    raeburn  1907: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1908: sub dump_dom {
1.1165    droeschl 1909:     my ($namespace, $udom, $regexp) = @_;
                   1910: 
                   1911:     $udom ||= $env{'user.domain'};
                   1912: 
                   1913:     return () unless $udom;
                   1914: 
                   1915:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1916: }
                   1917: 
1.1023    raeburn  1918: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1919: 
                   1920: sub get_dom {
1.860     raeburn  1921:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  1922:     return if ($udom eq 'public');
1.806     raeburn  1923:     my $items='';
                   1924:     foreach my $item (@$storearr) {
                   1925:         $items.=&escape($item).'&';
                   1926:     }
                   1927:     $items=~s/\&$//;
1.860     raeburn  1928:     if (!$udom) {
                   1929:         $udom=$env{'user.domain'};
1.1267    raeburn  1930:         return if ($udom eq 'public');
1.860     raeburn  1931:         if (defined(&domain($udom,'primary'))) {
                   1932:             $uhome=&domain($udom,'primary');
                   1933:         } else {
1.874     albertel 1934:             undef($uhome);
1.860     raeburn  1935:         }
                   1936:     } else {
                   1937:         if (!$uhome) {
                   1938:             if (defined(&domain($udom,'primary'))) {
                   1939:                 $uhome=&domain($udom,'primary');
                   1940:             }
                   1941:         }
                   1942:     }
                   1943:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344    raeburn  1944:         my $rep;
                   1945:         if ($namespace =~ /^enc/) {
                   1946:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   1947:         } else {
                   1948:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   1949:         }
1.866     raeburn  1950:         my %returnhash;
1.875     albertel 1951:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1952:             return %returnhash;
                   1953:         }
1.806     raeburn  1954:         my @pairs=split(/\&/,$rep);
                   1955:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1956:             return @pairs;
                   1957:         }
                   1958:         my $i=0;
                   1959:         foreach my $item (@$storearr) {
                   1960:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1961:             $i++;
                   1962:         }
                   1963:         return %returnhash;
                   1964:     } else {
1.880     banghart 1965:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1966:     }
                   1967: }
                   1968: 
                   1969: # -------------------------------------------- put items in domain db files 
                   1970: 
                   1971: sub put_dom {
1.860     raeburn  1972:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1973:     if (!$udom) {
                   1974:         $udom=$env{'user.domain'};
                   1975:         if (defined(&domain($udom,'primary'))) {
                   1976:             $uhome=&domain($udom,'primary');
                   1977:         } else {
1.874     albertel 1978:             undef($uhome);
1.860     raeburn  1979:         }
                   1980:     } else {
                   1981:         if (!$uhome) {
                   1982:             if (defined(&domain($udom,'primary'))) {
                   1983:                 $uhome=&domain($udom,'primary');
                   1984:             }
                   1985:         }
                   1986:     } 
                   1987:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1988:         my $items='';
                   1989:         foreach my $item (keys(%$storehash)) {
                   1990:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1991:         }
                   1992:         $items=~s/\&$//;
1.1344    raeburn  1993:         if ($namespace =~ /^enc/) {
                   1994:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   1995:         } else {
                   1996:             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1997:         }
1.806     raeburn  1998:     } else {
1.860     raeburn  1999:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  2000:     }
                   2001: }
                   2002: 
1.1023    raeburn  2003: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  2004: sub newput_dom {
1.1023    raeburn  2005:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  2006:     my $result;
                   2007:     if (!$udom) {
                   2008:         $udom=$env{'user.domain'};
                   2009:     }
1.1023    raeburn  2010:     if ($udom) {
                   2011:         my $uname = &get_domainconfiguser($udom);
                   2012:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2013:     }
                   2014:     return $result;
                   2015: }
                   2016: 
1.1023    raeburn  2017: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2018: sub del_dom {
1.1023    raeburn  2019:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2020:     if (ref($storearr) eq 'ARRAY') {
                   2021:         if (!$udom) {
                   2022:             $udom=$env{'user.domain'};
                   2023:         }
1.1023    raeburn  2024:         if ($udom) {
                   2025:             my $uname = &get_domainconfiguser($udom); 
                   2026:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2027:         }
                   2028:     }
                   2029: }
                   2030: 
1.1023    raeburn  2031: # ----------------------------------construct domainconfig user for a domain 
                   2032: sub get_domainconfiguser {
                   2033:     my ($udom) = @_;
                   2034:     return $udom.'-domainconfig';
                   2035: }
                   2036: 
1.837     raeburn  2037: sub retrieve_inst_usertypes {
                   2038:     my ($udom) = @_;
                   2039:     my (%returnhash,@order);
1.989     raeburn  2040:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2041:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2042:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  2043:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2044:     } else {
                   2045:         if (defined(&domain($udom,'primary'))) {
                   2046:             my $uhome=&domain($udom,'primary');
                   2047:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2048:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  2049:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2050:                 return (\%returnhash,\@order);
                   2051:             }
                   2052:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2053:             my @pairs=split(/\&/,$hashitems);
                   2054:             foreach my $item (@pairs) {
                   2055:                 my ($key,$value)=split(/=/,$item,2);
                   2056:                 $key = &unescape($key);
                   2057:                 next if ($key =~ /^error: 2 /);
                   2058:                 $returnhash{$key}=&thaw_unescape($value);
                   2059:             }
                   2060:             my @esc_order = split(/\&/,$orderitems);
                   2061:             foreach my $item (@esc_order) {
                   2062:                 push(@order,&unescape($item));
                   2063:             }
                   2064:         } else {
1.1256    raeburn  2065:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2066:         }
1.1256    raeburn  2067:         return (\%returnhash,\@order);
1.837     raeburn  2068:     }
                   2069: }
                   2070: 
1.868     raeburn  2071: sub is_domainimage {
                   2072:     my ($url) = @_;
1.1306    raeburn  2073:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2074:         if (&domain($1) ne '') {
                   2075:             return '1';
                   2076:         }
                   2077:     }
                   2078:     return;
                   2079: }
                   2080: 
1.899     raeburn  2081: sub inst_directory_query {
                   2082:     my ($srch) = @_;
                   2083:     my $udom = $srch->{'srchdomain'};
                   2084:     my %results;
                   2085:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2086:     my $outcome;
1.899     raeburn  2087:     if ($homeserver ne '') {
1.904     albertel 2088: 	my $queryid=&reply("querysend:instdirsearch:".
                   2089: 			   &escape($srch->{'srchby'}).':'.
                   2090: 			   &escape($srch->{'srchterm'}).':'.
                   2091: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2092: 	my $host=&hostname($homeserver);
                   2093: 	if ($queryid !~/^\Q$host\E\_/) {
1.1343    raeburn  2094: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2095: 	    return;
                   2096: 	}
                   2097: 	my $response = &get_query_reply($queryid);
                   2098: 	my $maxtries = 5;
                   2099: 	my $tries = 1;
                   2100: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2101: 	    $response = &get_query_reply($queryid);
                   2102: 	    $tries ++;
                   2103: 	}
                   2104: 
                   2105:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2106:             if ($response eq 'unavailable') {
                   2107:                 $outcome = $response;
                   2108:             } else {
                   2109:                 $outcome = 'ok';
                   2110:                 my @matches = split(/\n/,$response);
                   2111:                 foreach my $match (@matches) {
                   2112:                     my ($key,$value) = split(/=/,$match);
                   2113:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2114:                 }
1.899     raeburn  2115:             }
                   2116:         }
                   2117:     }
1.909     raeburn  2118:     return ($outcome,%results);
1.899     raeburn  2119: }
                   2120: 
                   2121: sub usersearch {
                   2122:     my ($srch) = @_;
                   2123:     my $dom = $srch->{'srchdomain'};
                   2124:     my %results;
                   2125:     my %libserv = &all_library();
                   2126:     my $query = 'usersearch';
                   2127:     foreach my $tryserver (keys(%libserv)) {
                   2128:         if (&host_domain($tryserver) eq $dom) {
                   2129:             my $host=&hostname($tryserver);
                   2130:             my $queryid=
1.911     raeburn  2131:                 &reply("querysend:".&escape($query).':'.
                   2132:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2133:                        &escape($srch->{'srchtype'}).':'.
                   2134:                        &escape($srch->{'srchterm'}),$tryserver);
                   2135:             if ($queryid !~/^\Q$host\E\_/) {
                   2136:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2137:                 next;
1.899     raeburn  2138:             }
                   2139:             my $reply = &get_query_reply($queryid);
                   2140:             my $maxtries = 1;
                   2141:             my $tries = 1;
                   2142:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2143:                 $reply = &get_query_reply($queryid);
                   2144:                 $tries ++;
                   2145:             }
                   2146:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2147:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2148:             } else {
1.911     raeburn  2149:                 my @matches;
                   2150:                 if ($reply =~ /\n/) {
                   2151:                     @matches = split(/\n/,$reply);
                   2152:                 } else {
                   2153:                     @matches = split(/\&/,$reply);
                   2154:                 }
1.899     raeburn  2155:                 foreach my $match (@matches) {
                   2156:                     my ($uname,$udom,%userhash);
1.911     raeburn  2157:                     foreach my $entry (split(/:/,$match)) {
                   2158:                         my ($key,$value) =
                   2159:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2160:                         $userhash{$key} = $value;
                   2161:                         if ($key eq 'username') {
                   2162:                             $uname = $value;
                   2163:                         } elsif ($key eq 'domain') {
                   2164:                             $udom = $value;
1.911     raeburn  2165:                         }
1.899     raeburn  2166:                     }
                   2167:                     $results{$uname.':'.$udom} = \%userhash;
                   2168:                 }
                   2169:             }
                   2170:         }
                   2171:     }
                   2172:     return %results;
                   2173: }
                   2174: 
1.912     raeburn  2175: sub get_instuser {
                   2176:     my ($udom,$uname,$id) = @_;
                   2177:     my $homeserver = &domain($udom,'primary');
                   2178:     my ($outcome,%results);
                   2179:     if ($homeserver ne '') {
                   2180:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2181:                            &escape($id).':'.&escape($udom),$homeserver);
                   2182:         my $host=&hostname($homeserver);
                   2183:         if ($queryid !~/^\Q$host\E\_/) {
                   2184:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2185:             return;
                   2186:         }
                   2187:         my $response = &get_query_reply($queryid);
                   2188:         my $maxtries = 5;
                   2189:         my $tries = 1;
                   2190:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2191:             $response = &get_query_reply($queryid);
                   2192:             $tries ++;
                   2193:         }
                   2194:         if (!&error($response) && $response ne 'refused') {
                   2195:             if ($response eq 'unavailable') {
                   2196:                 $outcome = $response;
                   2197:             } else {
                   2198:                 $outcome = 'ok';
                   2199:                 my @matches = split(/\n/,$response);
                   2200:                 foreach my $match (@matches) {
                   2201:                     my ($key,$value) = split(/=/,$match);
                   2202:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2203:                 }
                   2204:             }
                   2205:         }
                   2206:     }
                   2207:     my %userinfo;
                   2208:     if (ref($results{$uname}) eq 'HASH') {
                   2209:         %userinfo = %{$results{$uname}};
                   2210:     } 
                   2211:     return ($outcome,%userinfo);
                   2212: }
                   2213: 
1.1290    raeburn  2214: sub get_multiple_instusers {
                   2215:     my ($udom,$users,$caller) = @_;
                   2216:     my ($outcome,$results);
                   2217:     if (ref($users) eq 'HASH') {
                   2218:         my $count = keys(%{$users}); 
                   2219:         my $requested = &freeze_escape($users);
                   2220:         my $homeserver = &domain($udom,'primary');
                   2221:         if ($homeserver ne '') {
                   2222:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2223:             my $host=&hostname($homeserver);
                   2224:             if ($queryid !~/^\Q$host\E\_/) {
                   2225:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2226:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2227:                 return ($outcome,$results);
                   2228:             }
                   2229:             my $response = &get_query_reply($queryid);
                   2230:             my $maxtries = 5;
                   2231:             if ($count > 100) {
                   2232:                 $maxtries = 1+int($count/20);
                   2233:             }
                   2234:             my $tries = 1;
                   2235:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2236:                 $response = &get_query_reply($queryid);
                   2237:                 $tries ++;
                   2238:             }
                   2239:             if ($response eq '') {
                   2240:                 $results = {};
                   2241:                 foreach my $key (keys(%{$users})) {
                   2242:                     my ($uname,$id);
                   2243:                     if ($caller eq 'id') {
                   2244:                         $id = $key;
                   2245:                     } else {
                   2246:                         $uname = $key;
                   2247:                     }
                   2248:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2249:                     $outcome = $resp;
1.1290    raeburn  2250:                     if ($resp eq 'ok') {
                   2251:                         %{$results} = (%{$results}, %info);
                   2252:                     } else {
                   2253:                         last;
                   2254:                     }
                   2255:                 }
                   2256:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2257:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2258:                     $outcome = $response;
                   2259:                 } else {
1.1291    raeburn  2260:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2261:                     if ($outcome eq 'ok') {
                   2262:                         $results = &thaw_unescape($userdata); 
                   2263:                     }
                   2264:                 }
                   2265:             }
                   2266:         }
                   2267:     }
                   2268:     return ($outcome,$results);
                   2269: }
                   2270: 
1.912     raeburn  2271: sub inst_rulecheck {
1.923     raeburn  2272:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2273:     my %returnhash;
                   2274:     if ($udom ne '') {
                   2275:         if (ref($rules) eq 'ARRAY') {
                   2276:             @{$rules} = map {&escape($_);} (@{$rules});
                   2277:             my $rulestr = join(':',@{$rules});
                   2278:             my $homeserver=&domain($udom,'primary');
                   2279:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2280:                 my $response;
                   2281:                 if ($item eq 'username') {                
                   2282:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2283:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2284:                                               $homeserver));
1.923     raeburn  2285:                 } elsif ($item eq 'id') {
                   2286:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2287:                                               ':'.&escape($id).':'.$rulestr,
                   2288:                                               $homeserver));
1.945     raeburn  2289:                 } elsif ($item eq 'selfcreate') {
                   2290:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2291:                                                &escape($udom).':'.&escape($uname).
                   2292:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2293:                 }
1.912     raeburn  2294:                 if ($response ne 'refused') {
                   2295:                     my @pairs=split(/\&/,$response);
                   2296:                     foreach my $item (@pairs) {
                   2297:                         my ($key,$value)=split(/=/,$item,2);
                   2298:                         $key = &unescape($key);
                   2299:                         next if ($key =~ /^error: 2 /);
                   2300:                         $returnhash{$key}=&thaw_unescape($value);
                   2301:                     }
                   2302:                 }
                   2303:             }
                   2304:         }
                   2305:     }
                   2306:     return %returnhash;
                   2307: }
                   2308: 
                   2309: sub inst_userrules {
1.923     raeburn  2310:     my ($udom,$check) = @_;
1.912     raeburn  2311:     my (%ruleshash,@ruleorder);
                   2312:     if ($udom ne '') {
                   2313:         my $homeserver=&domain($udom,'primary');
                   2314:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2315:             my $response;
                   2316:             if ($check eq 'id') {
                   2317:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2318:                                  $homeserver);
1.943     raeburn  2319:             } elsif ($check eq 'email') {
                   2320:                 $response=&reply('instemailrules:'.&escape($udom),
                   2321:                                  $homeserver);
1.923     raeburn  2322:             } else {
                   2323:                 $response=&reply('instuserrules:'.&escape($udom),
                   2324:                                  $homeserver);
                   2325:             }
1.912     raeburn  2326:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2327:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2328:                 ($response ne 'no_such_host')) {
                   2329:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2330:                 my @pairs=split(/\&/,$hashitems);
                   2331:                 foreach my $item (@pairs) {
                   2332:                     my ($key,$value)=split(/=/,$item,2);
                   2333:                     $key = &unescape($key);
                   2334:                     next if ($key =~ /^error: 2 /);
                   2335:                     $ruleshash{$key}=&thaw_unescape($value);
                   2336:                 }
                   2337:                 my @esc_order = split(/\&/,$orderitems);
                   2338:                 foreach my $item (@esc_order) {
                   2339:                     push(@ruleorder,&unescape($item));
                   2340:                 }
                   2341:             }
                   2342:         }
                   2343:     }
                   2344:     return (\%ruleshash,\@ruleorder);
                   2345: }
                   2346: 
1.976     raeburn  2347: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2348: 
                   2349: sub get_domain_defaults {
1.1240    raeburn  2350:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2351:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2352:     my $cachetime = 60*60*24;
1.1240    raeburn  2353:     unless ($ignore_cache) {
                   2354:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2355:         if (defined($cached)) {
                   2356:             if (ref($result) eq 'HASH') {
                   2357:                 return %{$result};
                   2358:             }
1.943     raeburn  2359:         }
                   2360:     }
                   2361:     my %domdefaults;
                   2362:     my %domconfig =
1.989     raeburn  2363:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2364:                                   'requestcourses','inststatus',
1.1183    raeburn  2365:                                   'coursedefaults','usersessions',
1.1258    raeburn  2366:                                   'requestauthor','selfenrollment',
1.1320    raeburn  2367:                                   'coursecategories','ssl','autoenroll',
1.1332    raeburn  2368:                                   'trust','helpsettings'],$domain);
1.1305    raeburn  2369:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2370:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2371:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2372:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2373:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2374:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2375:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2376:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340    raeburn  2377:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2378:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2379:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2380:     } else {
                   2381:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2382:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2383:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2384:     }
1.976     raeburn  2385:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2386:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2387:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2388:         } else {
                   2389:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2390:         }
1.1177    raeburn  2391:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2392:         foreach my $item (@usertools) {
                   2393:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2394:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2395:             }
                   2396:         }
1.1229    raeburn  2397:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2398:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2399:         }
1.976     raeburn  2400:     }
1.985     raeburn  2401:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2402:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2403:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2404:         }
                   2405:     }
1.1183    raeburn  2406:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2407:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2408:     }
1.989     raeburn  2409:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2410:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2411:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2412:         }
                   2413:     }
1.1047    raeburn  2414:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2415:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2416:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2417:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2418:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2419:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2420:         }
1.1254    raeburn  2421:         foreach my $type (@coursetypes) {
                   2422:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2423:                 unless ($type eq 'community') {
                   2424:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2425:                 }
                   2426:             }
                   2427:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2428:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2429:             }
1.1277    raeburn  2430:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2431:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2432:                     $domdefaults{$type.'postsubtimeout'} = 
                   2433:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2434:                 }
                   2435:             }
1.1230    raeburn  2436:         }
1.1286    raeburn  2437:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2438:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2439:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2440:                 if (@clonecodes) {
                   2441:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2442:                 }
                   2443:             }
                   2444:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2445:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2446:         }
1.1047    raeburn  2447:     }
1.1073    raeburn  2448:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2449:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2450:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2451:         }
                   2452:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2453:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2454:         }
1.1279    raeburn  2455:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2456:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2457:         }
1.1073    raeburn  2458:     }
1.1254    raeburn  2459:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2460:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2461:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2462:                             'approval','limit');
                   2463:             foreach my $type (@coursetypes) {
                   2464:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2465:                     my @mgrdc = ();
                   2466:                     foreach my $item (@settings) {
                   2467:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2468:                             push(@mgrdc,$item);
                   2469:                         }
                   2470:                     }
                   2471:                     if (@mgrdc) {
                   2472:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2473:                     }
                   2474:                 }
                   2475:             }
                   2476:         }
                   2477:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2478:             foreach my $type (@coursetypes) {
                   2479:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2480:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2481:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2482:                     }
                   2483:                 }
                   2484:             }
                   2485:         }
                   2486:     }
1.1258    raeburn  2487:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2488:         $domdefaults{'catauth'} = 'std';
                   2489:         $domdefaults{'catunauth'} = 'std';
                   2490:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2491:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2492:         }
                   2493:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2494:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2495:         }
                   2496:     }
1.1315    raeburn  2497:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2498:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2499:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2500:         }
1.1338    raeburn  2501:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
                   2502:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
                   2503:         }
                   2504:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
                   2505:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315    raeburn  2506:         }
                   2507:     }
1.1320    raeburn  2508:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2509:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2510:         foreach my $prefix (@prefixes) {
                   2511:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2512:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2513:             }
                   2514:         }
                   2515:     }
1.1314    raeburn  2516:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2517:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2518:     }
1.1332    raeburn  2519:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2520:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2521:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2522:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2523:         }
                   2524:     }
1.1219    raeburn  2525:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2526:     return %domdefaults;
                   2527: }
                   2528: 
1.1311    raeburn  2529: sub course_portal_url {
                   2530:     my ($cnum,$cdom) = @_;
                   2531:     my $chome = &homeserver($cnum,$cdom);
                   2532:     my $hostname = &hostname($chome);
                   2533:     my $protocol = $protocol{$chome};
                   2534:     $protocol = 'http' if ($protocol ne 'https');
                   2535:     my %domdefaults = &get_domain_defaults($cdom);
                   2536:     my $firsturl;
                   2537:     if ($domdefaults{'portal_def'}) {
                   2538:         $firsturl = $domdefaults{'portal_def'};
                   2539:     } else {
                   2540:         $firsturl = $protocol.'://'.$hostname;
                   2541:     }
                   2542:     return $firsturl;
                   2543: }
                   2544: 
1.344     www      2545: # --------------------------------------------------- Assign a key to a student
                   2546: 
                   2547: sub assign_access_key {
1.364     www      2548: #
                   2549: # a valid key looks like uname:udom#comments
                   2550: # comments are being appended
                   2551: #
1.498     www      2552:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2553:     $kdom=
1.620     albertel 2554:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2555:     $knum=
1.620     albertel 2556:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2557:     $cdom=
1.620     albertel 2558:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2559:     $cnum=
1.620     albertel 2560:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2561:     $udom=$env{'user.name'} unless (defined($udom));
                   2562:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2563:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2564:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2565:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2566:                                                   # assigned to this person
                   2567:                                                   # - this should not happen,
1.345     www      2568:                                                   # unless something went wrong
                   2569:                                                   # the first time around
                   2570: # ready to assign
1.364     www      2571:         $logentry=$1.'; '.$logentry;
1.496     www      2572:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2573:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2574: # key now belongs to user
1.346     www      2575: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2576:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2577:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2578:                 return 'ok';
                   2579:             } else {
                   2580:                 return 
                   2581:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2582: 	    }
                   2583:         } else {
                   2584:             return 'error: Could not assign key, try again later.';
                   2585:         }
1.364     www      2586:     } elsif (!$existing{$ckey}) {
1.345     www      2587: # the key does not exist
                   2588: 	return 'error: The key does not exist';
                   2589:     } else {
                   2590: # the key is somebody else's
                   2591: 	return 'error: The key is already in use';
                   2592:     }
1.344     www      2593: }
                   2594: 
1.364     www      2595: # ------------------------------------------ put an additional comment on a key
                   2596: 
                   2597: sub comment_access_key {
                   2598: #
                   2599: # a valid key looks like uname:udom#comments
                   2600: # comments are being appended
                   2601: #
                   2602:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2603:     $cdom=
1.620     albertel 2604:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2605:     $cnum=
1.620     albertel 2606:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2607:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2608:     if ($existing{$ckey}) {
                   2609:         $existing{$ckey}.='; '.$logentry;
                   2610: # ready to assign
1.367     www      2611:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2612:                                                  $cdom,$cnum) eq 'ok') {
                   2613: 	    return 'ok';
                   2614:         } else {
                   2615: 	    return 'error: Count not store comment.';
                   2616:         }
                   2617:     } else {
                   2618: # the key does not exist
                   2619: 	return 'error: The key does not exist';
                   2620:     }
                   2621: }
                   2622: 
1.344     www      2623: # ------------------------------------------------------ Generate a set of keys
                   2624: 
                   2625: sub generate_access_keys {
1.364     www      2626:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2627:     $cdom=
1.620     albertel 2628:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2629:     $cnum=
1.620     albertel 2630:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2631:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2632:     unless (($cdom) && ($cnum)) { return 0; }
                   2633:     if ($number>10000) { return 0; }
                   2634:     sleep(2); # make sure don't get same seed twice
                   2635:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2636:     my $total=0;
                   2637:     for (my $i=1;$i<=$number;$i++) {
                   2638:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2639:                   sprintf("%lx",int(100000*rand)).'-'.
                   2640:                   sprintf("%lx",int(100000*rand));
                   2641:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2642:        $newkey=~s/0/h/g; # and also 0 and O
                   2643:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2644:        if ($existing{$newkey}) {
                   2645:            $i--;
                   2646:        } else {
1.364     www      2647: 	  if (&put('accesskeys',
                   2648:               { $newkey => '# generated '.localtime().
1.620     albertel 2649:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2650:                            '; '.$logentry },
                   2651: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2652:               $total++;
                   2653: 	  }
                   2654:        }
                   2655:     }
1.620     albertel 2656:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2657:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2658:     return $total;
                   2659: }
                   2660: 
                   2661: # ------------------------------------------------------- Validate an accesskey
                   2662: 
                   2663: sub validate_access_key {
                   2664:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2665:     $cdom=
1.620     albertel 2666:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2667:     $cnum=
1.620     albertel 2668:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2669:     $udom=$env{'user.domain'} unless (defined($udom));
                   2670:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2671:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2672:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2673: }
                   2674: 
                   2675: # ------------------------------------- Find the section of student in a course
1.652     albertel 2676: sub devalidate_getsection_cache {
                   2677:     my ($udom,$unam,$courseid)=@_;
                   2678:     my $hashid="$udom:$unam:$courseid";
                   2679:     &devalidate_cache_new('getsection',$hashid);
                   2680: }
1.298     matthew  2681: 
1.815     albertel 2682: sub courseid_to_courseurl {
                   2683:     my ($courseid) = @_;
                   2684:     #already url style courseid
                   2685:     return $courseid if ($courseid =~ m{^/});
                   2686: 
                   2687:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2688: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2689: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2690: 	return "/$cdom/$cnum";
                   2691:     }
                   2692: 
                   2693:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2694:     if (exists($courseinfo{'num'})) {
                   2695: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2696:     }
                   2697: 
                   2698:     return undef;
                   2699: }
                   2700: 
1.298     matthew  2701: sub getsection {
                   2702:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2703:     my $cachetime=1800;
1.551     albertel 2704: 
                   2705:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2706:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2707:     if (defined($cached)) { return $result; }
                   2708: 
1.298     matthew  2709:     my %Pending; 
                   2710:     my %Expired;
                   2711:     #
                   2712:     # Each role can either have not started yet (pending), be active, 
                   2713:     #    or have expired.
                   2714:     #
                   2715:     # If there is an active role, we are done.
                   2716:     #
                   2717:     # If there is more than one role which has not started yet, 
                   2718:     #     choose the one which will start sooner
                   2719:     # If there is one role which has not started yet, return it.
                   2720:     #
                   2721:     # If there is more than one expired role, choose the one which ended last.
                   2722:     # If there is a role which has expired, return it.
                   2723:     #
1.815     albertel 2724:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2725:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2726:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2727:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2728:         my $section=$1;
                   2729:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2730:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2731:         my $now=time;
1.548     albertel 2732:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2733:             $Expired{$end}=$section;
                   2734:             next;
                   2735:         }
1.548     albertel 2736:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2737:             $Pending{$start}=$section;
                   2738:             next;
                   2739:         }
1.599     albertel 2740:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2741:     }
                   2742:     #
                   2743:     # Presumedly there will be few matching roles from the above
                   2744:     # loop and the sorting time will be negligible.
                   2745:     if (scalar(keys(%Pending))) {
                   2746:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2747:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2748:     } 
                   2749:     if (scalar(keys(%Expired))) {
                   2750:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2751:         my $time = pop(@sorted);
1.599     albertel 2752:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2753:     }
1.599     albertel 2754:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2755: }
1.70      www      2756: 
1.599     albertel 2757: sub save_cache {
                   2758:     &purge_remembered();
1.722     albertel 2759:     #&Apache::loncommon::validate_page();
1.620     albertel 2760:     undef(%env);
1.780     albertel 2761:     undef($env_loaded);
1.599     albertel 2762: }
1.452     albertel 2763: 
1.599     albertel 2764: my $to_remember=-1;
                   2765: my %remembered;
                   2766: my %accessed;
                   2767: my $kicks=0;
                   2768: my $hits=0;
1.849     albertel 2769: sub make_key {
                   2770:     my ($name,$id) = @_;
1.872     albertel 2771:     if (length($id) > 65 
                   2772: 	&& length(&escape($id)) > 200) {
                   2773: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2774:     }
1.849     albertel 2775:     return &escape($name.':'.$id);
                   2776: }
                   2777: 
1.599     albertel 2778: sub devalidate_cache_new {
                   2779:     my ($name,$id,$debug) = @_;
                   2780:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  2781:     my $remembered_id=$name.':'.$id;
1.849     albertel 2782:     $id=&make_key($name,$id);
1.599     albertel 2783:     $memcache->delete($id);
1.1319    damieng  2784:     delete($remembered{$remembered_id});
                   2785:     delete($accessed{$remembered_id});
1.599     albertel 2786: }
                   2787: 
                   2788: sub is_cached_new {
                   2789:     my ($name,$id,$debug) = @_;
1.1319    damieng  2790:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   2791:     if (exists($remembered{$remembered_id})) {
                   2792: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2793: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2794: 	$hits++;
1.1319    damieng  2795: 	return ($remembered{$remembered_id},1);
1.599     albertel 2796:     }
1.1319    damieng  2797:     $id=&make_key($name,$id);
1.599     albertel 2798:     my $value = $memcache->get($id);
                   2799:     if (!(defined($value))) {
                   2800: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2801: 	return (undef,undef);
1.416     albertel 2802:     }
1.599     albertel 2803:     if ($value eq '__undef__') {
                   2804: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2805: 	$value=undef;
                   2806:     }
1.1319    damieng  2807:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2808:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2809:     return ($value,1);
                   2810: }
                   2811: 
                   2812: sub do_cache_new {
                   2813:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  2814:     my $remembered_id=$name.':'.$id;
1.849     albertel 2815:     $id=&make_key($name,$id);
1.599     albertel 2816:     my $setvalue=$value;
                   2817:     if (!defined($setvalue)) {
                   2818: 	$setvalue='__undef__';
                   2819:     }
1.623     albertel 2820:     if (!defined($time) ) {
                   2821: 	$time=600;
                   2822:     }
1.599     albertel 2823:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2824:     my $result = $memcache->set($id,$setvalue,$time);
                   2825:     if (! $result) {
1.872     albertel 2826: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2827: 	$memcache->disconnect_all();
1.872     albertel 2828:     }
1.600     albertel 2829:     # need to make a copy of $value
1.1319    damieng  2830:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2831:     return $value;
                   2832: }
                   2833: 
                   2834: sub make_room {
1.1319    damieng  2835:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2836: 
1.1319    damieng  2837:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2838:                                     : $value;
1.599     albertel 2839:     if ($to_remember<0) { return; }
1.1319    damieng  2840:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2841:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2842:     my $to_kick;
                   2843:     my $max_time=0;
                   2844:     foreach my $other (keys(%accessed)) {
                   2845: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2846: 	    $to_kick=$other;
                   2847: 	    $max_time=&tv_interval($accessed{$other});
                   2848: 	}
                   2849:     }
                   2850:     delete($remembered{$to_kick});
                   2851:     delete($accessed{$to_kick});
                   2852:     $kicks++;
                   2853:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2854:     return;
                   2855: }
                   2856: 
1.599     albertel 2857: sub purge_remembered {
1.604     albertel 2858:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2859:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2860:     undef(%remembered);
                   2861:     undef(%accessed);
1.428     albertel 2862: }
1.70      www      2863: # ------------------------------------- Read an entry from a user's environment
                   2864: 
                   2865: sub userenvironment {
                   2866:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2867:     my $items;
                   2868:     foreach my $item (@what) {
                   2869:         $items.=&escape($item).'&';
                   2870:     }
                   2871:     $items=~s/\&$//;
1.70      www      2872:     my %returnhash=();
1.1009    raeburn  2873:     my $uhome = &homeserver($unam,$udom);
                   2874:     unless ($uhome eq 'no_host') {
                   2875:         my @answer=split(/\&/, 
                   2876:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2877:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2878:             return %returnhash;
                   2879:         }
1.1009    raeburn  2880:         my $i;
                   2881:         for ($i=0;$i<=$#what;$i++) {
                   2882: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2883:         }
1.70      www      2884:     }
                   2885:     return %returnhash;
1.1       albertel 2886: }
                   2887: 
1.617     albertel 2888: # ---------------------------------------------------------- Get a studentphoto
                   2889: sub studentphoto {
                   2890:     my ($udom,$unam,$ext) = @_;
                   2891:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2892:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2893:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2894:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2895:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2896:             } else {
                   2897:                 my ($result,$perm_reqd)=
1.707     albertel 2898: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2899:                 if ($result eq 'ok') {
                   2900:                     if (!($perm_reqd eq 'yes')) {
                   2901:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2902:                     }
                   2903:                 }
                   2904:             }
                   2905:         }
                   2906:     } else {
                   2907:         my ($result,$perm_reqd) = 
1.707     albertel 2908: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2909:         if ($result eq 'ok') {
                   2910:             if (!($perm_reqd eq 'yes')) {
                   2911:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2912:             }
                   2913:         }
                   2914:     }
                   2915:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2916: }
                   2917: 
                   2918: sub retrievestudentphoto {
                   2919:     my ($udom,$unam,$ext,$type) = @_;
                   2920:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2921:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2922:     if ($ret eq 'ok') {
                   2923:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2924:         if ($type eq 'thumbnail') {
                   2925:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2926:         }
                   2927:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2928:         return $tokenurl;
                   2929:     } else {
                   2930:         if ($type eq 'thumbnail') {
                   2931:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2932:         } else { 
                   2933:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2934:         }
1.617     albertel 2935:     }
                   2936: }
                   2937: 
1.263     www      2938: # -------------------------------------------------------------------- New chat
                   2939: 
                   2940: sub chatsend {
1.724     raeburn  2941:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2942:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2943:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2944:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2945:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2946: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2947: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2948: }
                   2949: 
                   2950: # ------------------------------------------ Find current version of a resource
                   2951: 
                   2952: sub getversion {
                   2953:     my $fname=&clutter(shift);
1.1189    raeburn  2954:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2955:     return &currentversion(&filelocation('',$fname));
                   2956: }
                   2957: 
                   2958: sub currentversion {
                   2959:     my $fname=shift;
                   2960:     my $author=$fname;
                   2961:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2962:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2963:     my $home=&homeserver($uname,$udom);
1.292     www      2964:     if ($home eq 'no_host') { 
                   2965:         return -1; 
                   2966:     }
1.1112    www      2967:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2968:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2969: 	return -1;
                   2970:     }
1.1112    www      2971:     return $answer;
1.263     www      2972: }
                   2973: 
1.1111    www      2974: #
                   2975: # Return special version number of resource if set by override, empty otherwise
                   2976: #
                   2977: sub usedversion {
                   2978:     my $fname=shift;
                   2979:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2980:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2981:     if ($urlversion) { return $urlversion; }
                   2982:     return '';
                   2983: }
                   2984: 
1.1       albertel 2985: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2986: 
1.1       albertel 2987: sub subscribe {
                   2988:     my $fname=shift;
1.761     raeburn  2989:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2990:     $fname=~s/[\n\r]//g;
1.1       albertel 2991:     my $author=$fname;
                   2992:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2993:     my ($udom,$uname)=split(/\//,$author);
                   2994:     my $home=homeserver($uname,$udom);
1.335     albertel 2995:     if ($home eq 'no_host') {
                   2996:         return 'not_found';
1.1       albertel 2997:     }
                   2998:     my $answer=reply("sub:$fname",$home);
1.64      www      2999:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3000: 	$answer.=' by '.$home;
                   3001:     }
1.1       albertel 3002:     return $answer;
                   3003: }
                   3004:     
1.8       www      3005: # -------------------------------------------------------------- Replicate file
                   3006: 
                   3007: sub repcopy {
                   3008:     my $filename=shift;
1.23      www      3009:     $filename=~s/\/+/\//g;
1.1142    raeburn  3010:     my $londocroot = $perlvar{'lonDocRoot'};
                   3011:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3012:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3013:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3014: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3015: 	return &repcopy_userfile($filename);
                   3016:     }
1.532     albertel 3017:     $filename=~s/[\n\r]//g;
1.8       www      3018:     my $transname="$filename.in.transfer";
1.828     www      3019: # FIXME: this should flock
1.607     raeburn  3020:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3021:     my $remoteurl=subscribe($filename);
1.64      www      3022:     if ($remoteurl =~ /^con_lost by/) {
                   3023: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3024:            return 'unavailable';
1.8       www      3025:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3026: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3027: 	   return 'not_found';
1.64      www      3028:     } elsif ($remoteurl =~ /^rejected by/) {
                   3029: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3030:            return 'forbidden';
1.20      www      3031:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3032:            return 'ok';
1.8       www      3033:     } else {
1.290     www      3034:         my $author=$filename;
                   3035:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3036:         my ($udom,$uname)=split(/\//,$author);
                   3037:         my $home=homeserver($uname,$udom);
                   3038:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3039:            my @parts=split(/\//,$filename);
                   3040:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3041:            if ($path ne "$londocroot/res") {
1.8       www      3042:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3043: 	       return 'bad_request';
1.8       www      3044:            }
                   3045:            my $count;
                   3046:            for ($count=5;$count<$#parts;$count++) {
                   3047:                $path.="/$parts[$count]";
                   3048:                if ((-e $path)!=1) {
                   3049: 		   mkdir($path,0777);
                   3050:                }
                   3051:            }
                   3052:            my $request=new HTTP::Request('GET',"$remoteurl");
1.1345    raeburn  3053:            my $response;
                   3054:            if ($remoteurl =~ m{/raw/}) {
                   3055:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
                   3056:            } else {
                   3057:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
                   3058:            }
1.8       www      3059:            if ($response->is_error()) {
                   3060: 	       unlink($transname);
                   3061:                my $message=$response->status_line;
1.672     albertel 3062:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3063:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3064:                return 'unavailable';
1.8       www      3065:            } else {
1.16      www      3066: 	       if ($remoteurl!~/\.meta$/) {
                   3067:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345    raeburn  3068:                   my $mresponse;
                   3069:                   if ($remoteurl =~ m{/raw/}) {
                   3070:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
                   3071:                   } else {
                   3072:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
                   3073:                   }
1.16      www      3074:                   if ($mresponse->is_error()) {
                   3075: 		      unlink($filename.'.meta');
                   3076:                       &logthis(
1.672     albertel 3077:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3078:                   }
                   3079: 	       }
1.8       www      3080:                rename($transname,$filename);
1.607     raeburn  3081:                return 'ok';
1.8       www      3082:            }
1.290     www      3083:        }
1.8       www      3084:     }
1.330     www      3085: }
                   3086: 
                   3087: # ------------------------------------------------ Get server side include body
                   3088: sub ssi_body {
1.381     albertel 3089:     my ($filelink,%form)=@_;
1.606     matthew  3090:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3091:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3092:     }
1.953     www      3093:     my $output='';
                   3094:     my $response;
1.980     raeburn  3095:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3096:        ($output,$response)=&externalssi($filelink);
1.953     www      3097:     } else {
1.1004    droeschl 3098:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3099:        $filelink .= 'inhibitmenu=yes';
1.953     www      3100:        ($output,$response)=&ssi($filelink,%form);
                   3101:     }
1.778     albertel 3102:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3103:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3104:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3105:     if (wantarray) {
                   3106:         return ($output, $response);
                   3107:     } else {
                   3108:         return $output;
                   3109:     }
1.8       www      3110: }
                   3111: 
1.15      www      3112: # --------------------------------------------------------- Server Side Include
                   3113: 
1.782     albertel 3114: sub absolute_url {
                   3115:     my ($host_name) = @_;
                   3116:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3117:     if ($host_name eq '') {
                   3118: 	$host_name = $ENV{'SERVER_NAME'};
                   3119:     }
                   3120:     return $protocol.$host_name;
                   3121: }
                   3122: 
1.942     foxr     3123: #
                   3124: #   Server side include.
                   3125: # Parameters:
                   3126: #  fn     Possibly encrypted resource name/id.
                   3127: #  form   Hash that describes how the rendering should be done
                   3128: #         and other things.
1.944     foxr     3129: # Returns:
1.950     raeburn  3130: #   Scalar context: The content of the response.
                   3131: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3132: #     
1.15      www      3133: sub ssi {
                   3134: 
1.944     foxr     3135:     my ($fn,%form)=@_;
1.23      www      3136:     my $request;
1.711     albertel 3137: 
                   3138:     $form{'no_update_last_known'}=1;
1.895     albertel 3139:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3140:     if (%form) {
1.782     albertel 3141:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 3142:       $request->content(join('&',map { 
                   3143:             my $name = escape($_);
                   3144:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3145:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3146:             : &escape($form{$_}) );    
                   3147:         } keys(%form)));
1.23      www      3148:     } else {
1.782     albertel 3149:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3150:     }
                   3151: 
1.15      www      3152:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345    raeburn  3153:     my $lonhost = $perlvar{'lonHostID'};
                   3154:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar);
1.1182    foxr     3155: 
1.944     foxr     3156:     if (wantarray) {
1.1345    raeburn  3157: 	return ($response->content, $response);
1.944     foxr     3158:     } else {
1.1345    raeburn  3159: 	return $response->content;
1.942     foxr     3160:     }
1.324     www      3161: }
                   3162: 
                   3163: sub externalssi {
                   3164:     my ($url)=@_;
                   3165:     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn  3166:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954     raeburn  3167:     if (wantarray) {
                   3168:         return ($response->content, $response);
                   3169:     } else {
                   3170:         return $response->content;
                   3171:     }
1.15      www      3172: }
1.254     www      3173: 
1.492     albertel 3174: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3175: 
                   3176: sub allowuploaded {
                   3177:     my ($srcurl,$url)=@_;
                   3178:     $url=&clutter(&declutter($url));
                   3179:     my $dir=$url;
                   3180:     $dir=~s/\/[^\/]+$//;
                   3181:     my %httpref=();
                   3182:     my $httpurl=&hreflocation('',$url);
                   3183:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3184:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3185: }
1.477     raeburn  3186: 
1.1193    raeburn  3187: #
                   3188: # Determine if the current user should be able to edit a particular resource,
                   3189: # when viewing in course context.
                   3190: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3191: #     Functions.
                   3192: # (b) When displaying folder contents in course editor, used to determine if
                   3193: #     "Edit" link will be displayed alongside resource.
                   3194: #
1.1196    raeburn  3195: #  input: six args -- filename (decluttered), course number, course domain,
                   3196: #                   url, symb (if registered) and group (if this is a group
                   3197: #                   item -- e.g., bulletin board, group page etc.).
                   3198: #  output: array of five scalars -- 
1.1193    raeburn  3199: #          $cfile -- url for file editing if editable on current server
                   3200: #          $home -- homeserver of resource (i.e., for author if published,
                   3201: #                                           or course if uploaded.).
                   3202: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3203: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3204: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3205: #
                   3206: 
                   3207: sub can_edit_resource {
1.1194    raeburn  3208:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3209:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3210: #
                   3211: # For aboutme pages user can only edit his/her own.
                   3212: #
1.1199    raeburn  3213:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3214:         my ($sdom,$sname) = ($1,$2);
                   3215:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3216:             $home = $env{'user.home'};
                   3217:             $cfile = $resurl;
                   3218:             if ($env{'form.forceedit'}) {
                   3219:                 $forceview = 1;
                   3220:             } else {
                   3221:                 $forceedit = 1;
                   3222:             }
                   3223:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3224:         } else {
                   3225:             return;
                   3226:         }
                   3227:     }
                   3228: 
                   3229:     if ($env{'request.course.id'}) {
                   3230:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3231:         if ($group ne '') {
                   3232: # if this is a group homepage or group bulletin board, check group privs
                   3233:             my $allowed = 0;
1.1197    raeburn  3234:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3235:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3236:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3237:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3238:                     $allowed = 1;
                   3239:                 }
1.1197    raeburn  3240:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3241:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3242:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3243:                     $allowed = 1;
                   3244:                 }
                   3245:             }
                   3246:             if ($allowed) {
                   3247:                 $home=&homeserver($cnum,$cdom);
                   3248:                 if ($env{'form.forceedit'}) {
                   3249:                     $forceview = 1;
                   3250:                 } else {
                   3251:                     $forceedit = 1;
                   3252:                 }
                   3253:                 $cfile = $resurl;
                   3254:             } else {
                   3255:                 return;
                   3256:             }
                   3257:         } else {
1.1208    raeburn  3258:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3259:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3260:                     return;
                   3261:                 }
                   3262:             } elsif (!$crsedit) {
1.1194    raeburn  3263: #
                   3264: # No edit allowed where CC has switched to student role.
                   3265: #
                   3266:                 return;
                   3267:             }
                   3268:         }
                   3269:     }
                   3270: 
1.1193    raeburn  3271:     if ($file ne '') {
                   3272:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3273:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3274:                 $uploaded = 1;
                   3275:                 $incourse = 1;
1.1193    raeburn  3276:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3277:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3278:                     if ($env{'form.forceedit'}) {
                   3279:                         $forceview = 1;
                   3280:                     } else {
                   3281:                         $forceedit = 1;
                   3282:                     }
1.1194    raeburn  3283:                 }
                   3284:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3285:                 $incourse = 1;
                   3286:                 if ($env{'form.forceedit'}) {
                   3287:                     $forceview = 1;
                   3288:                 } else {
                   3289:                     $forceedit = 1;
                   3290:                 }
                   3291:                 $cfile = $resurl;
                   3292:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3293:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3294:                     $incourse = 1;
                   3295:                     if ($env{'form.forceedit'}) {
                   3296:                         $forceview = 1;
                   3297:                     } else {
                   3298:                         $forceedit = 1;
                   3299:                     }
                   3300:                     $cfile = $resurl;
1.1199    raeburn  3301:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3302:                     $incourse = 1;
                   3303:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3304:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3305:                     $incourse = 1;
1.1199    raeburn  3306:                     if ($env{'form.forceedit'}) {
                   3307:                         $forceview = 1;
                   3308:                     } else {
                   3309:                         $forceedit = 1;
                   3310:                     }
                   3311:                     $cfile = $resurl;
1.1343    raeburn  3312:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3313:                     $incourse = 1;
                   3314:                     if ($env{'form.forceedit'}) {
                   3315:                         $forceview = 1;
                   3316:                     } else {
                   3317:                         $forceedit = 1;
                   3318:                     }
                   3319:                     $cfile = $resurl;
1.1208    raeburn  3320:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3321:                     $incourse = 1;
                   3322:                     if ($env{'form.forceedit'}) {
                   3323:                         $forceview = 1;
                   3324:                     } else {
                   3325:                         $forceedit = 1;
                   3326:                     }
                   3327:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3328:                 }
                   3329:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3330:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3331:                 if (&is_on_map($template)) { 
                   3332:                     $incourse = 1;
                   3333:                     $forceview = 1;
                   3334:                     $cfile = $template;
1.1193    raeburn  3335:                 }
1.1199    raeburn  3336:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3337:                     $incourse = 1;
                   3338:                     if ($env{'form.forceedit'}) {
                   3339:                         $forceview = 1;
                   3340:                     } else {
                   3341:                         $forceedit = 1;
                   3342:                     }
                   3343:                     $cfile = $resurl;
1.1343    raeburn  3344:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298    raeburn  3345:                 $incourse = 1;
                   3346:                 if ($env{'form.forceedit'}) {
                   3347:                     $forceview = 1;
                   3348:                 } else {
                   3349:                     $forceedit = 1;
                   3350:                 }
                   3351:                 $cfile = $resurl;
1.1199    raeburn  3352:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3353:                 $incourse = 1;
                   3354:                 $forceview = 1;
                   3355:                 if ($symb) {
                   3356:                     my ($map,$id,$res)=&decode_symb($symb);
                   3357:                     $env{'request.symb'} = $symb;
                   3358:                     $cfile = &clutter($res);
                   3359:                 } else {
                   3360:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3361:                     my $escfile = &unescape($cfile);
1.1343    raeburn  3362:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3363:                         $cfile = '/adm/wrapper'.$escfile;
                   3364:                     } else {
                   3365:                         $escfile =~ s{^http://}{};
                   3366:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3367:                     }
1.1199    raeburn  3368:                 }
1.1234    raeburn  3369:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3370:                 if ($env{'form.forceedit'}) {
                   3371:                     $forceview = 1;
                   3372:                 } else {
                   3373:                     $forceedit = 1;
                   3374:                 }
                   3375:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3376:             }
                   3377:         }
1.1194    raeburn  3378:         if ($uploaded || $incourse) {
                   3379:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3380:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3381:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3382:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3383:             # Check that the user has permission to edit this resource
                   3384:             my $setpriv = 1;
                   3385:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3386:             if (defined($cfudom)) {
                   3387:                 $home=&homeserver($cfuname,$cfudom);
                   3388:                 $cfile=$file;
                   3389:             }
                   3390:         }
1.1194    raeburn  3391:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3392:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3393:             my @ids=&current_machine_ids();
                   3394:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3395:                 $switchserver=1;
                   3396:             }
                   3397:         }
                   3398:     }
1.1194    raeburn  3399:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3400: }
                   3401: 
                   3402: sub is_course_upload {
                   3403:     my ($file,$cnum,$cdom) = @_;
                   3404:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3405:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3406:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3407:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3408:         return 1;
                   3409:     }
                   3410:     return;
                   3411: }
                   3412: 
1.1194    raeburn  3413: sub in_course {
1.1195    raeburn  3414:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3415:     if ($hideprivileged) {
                   3416:         my $skipuser;
1.1219    raeburn  3417:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3418:         my @possdoms = ($cdom);  
                   3419:         if ($coursehash{'checkforpriv'}) { 
                   3420:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3421:         }
                   3422:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3423:             $skipuser = 1;
                   3424:             if ($coursehash{'nothideprivileged'}) {
                   3425:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3426:                     my $user;
                   3427:                     if ($item =~ /:/) {
                   3428:                         $user = $item;
                   3429:                     } else {
                   3430:                         $user = join(':',split(/[\@]/,$item));
                   3431:                     }
                   3432:                     if ($user eq $uname.':'.$udom) {
                   3433:                         undef($skipuser);
                   3434:                         last;
                   3435:                     }
                   3436:                 }
                   3437:             }
                   3438:             if ($skipuser) {
                   3439:                 return 0;
                   3440:             }
                   3441:         }
                   3442:     }
1.1194    raeburn  3443:     $type ||= 'any';
                   3444:     if (!defined($cdom) || !defined($cnum)) {
                   3445:         my $cid  = $env{'request.course.id'};
                   3446:         $cdom = $env{'course.'.$cid.'.domain'};
                   3447:         $cnum = $env{'course.'.$cid.'.num'};
                   3448:     }
                   3449:     my $typesref;
1.1195    raeburn  3450:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3451:         $typesref = ['active','previous','future'];
                   3452:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3453:         $typesref = [$type];
                   3454:     }
                   3455:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3456:                               $typesref,undef,[$cdom]);
                   3457:     my ($tmp) = keys(%roles);
                   3458:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3459:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3460:     if (@course_roles > 0) {
                   3461:         return 1;
                   3462:     }
                   3463:     return 0;
                   3464: }
                   3465: 
1.478     albertel 3466: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3467: # input: action, courseID, current domain, intended
1.637     raeburn  3468: #        path to file, source of file, instruction to parse file for objects,
                   3469: #        ref to hash for embedded objects,
                   3470: #        ref to hash for codebase of java objects.
1.1095    raeburn  3471: #        reference to scalar to accommodate mime type determined
                   3472: #          from File::MMagic if $parser = parse.
1.637     raeburn  3473: #
1.485     raeburn  3474: # output: url to file (if action was uploaddoc), 
                   3475: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3476: #
1.478     albertel 3477: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3478: # course.
1.477     raeburn  3479: #
1.478     albertel 3480: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3481: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3482: #          course's home server.
1.477     raeburn  3483: #
1.478     albertel 3484: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3485: #          be copied from $source (current location) to 
                   3486: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3487: #         and will then be copied to
                   3488: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3489: #         course's home server.
1.485     raeburn  3490: #
1.481     raeburn  3491: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3492: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3493: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3494: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3495: #         in course's home server.
1.637     raeburn  3496: #
1.477     raeburn  3497: 
                   3498: sub process_coursefile {
1.1095    raeburn  3499:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3500:         $mimetype)=@_;
1.477     raeburn  3501:     my $fetchresult;
1.638     albertel 3502:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3503:     if ($action eq 'propagate') {
1.638     albertel 3504:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3505: 			     $home);
1.481     raeburn  3506:     } else {
1.477     raeburn  3507:         my $fpath = '';
                   3508:         my $fname = $file;
1.478     albertel 3509:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3510:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3511:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3512:         if ($action eq 'copy') {
                   3513:             if ($source eq '') {
                   3514:                 $fetchresult = 'no source file';
                   3515:                 return $fetchresult;
                   3516:             } else {
                   3517:                 my $destination = $filepath.'/'.$fname;
                   3518:                 rename($source,$destination);
                   3519:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3520:                                  $home);
1.481     raeburn  3521:             }
                   3522:         } elsif ($action eq 'uploaddoc') {
                   3523:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3524:             print $fh $env{'form.'.$source};
1.481     raeburn  3525:             close($fh);
1.637     raeburn  3526:             if ($parser eq 'parse') {
1.1024    raeburn  3527:                 my $mm = new File::MMagic;
1.1095    raeburn  3528:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3529:                 if ($type eq 'text/html') {
1.1024    raeburn  3530:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3531:                     unless ($parse_result eq 'ok') {
                   3532:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3533:                     }
1.637     raeburn  3534:                 }
1.1095    raeburn  3535:                 if (ref($mimetype)) {
                   3536:                     $$mimetype = $type;
                   3537:                 } 
1.637     raeburn  3538:             }
1.477     raeburn  3539:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3540:                                  $home);
1.481     raeburn  3541:             if ($fetchresult eq 'ok') {
                   3542:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3543:             } else {
                   3544:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3545:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3546:                 return '/adm/notfound.html';
                   3547:             }
1.477     raeburn  3548:         }
                   3549:     }
1.485     raeburn  3550:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3551:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3552:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3553:     }
                   3554:     return $fetchresult;
                   3555: }
                   3556: 
1.637     raeburn  3557: sub build_filepath {
                   3558:     my ($fpath) = @_;
                   3559:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3560:     unless ($fpath eq '') {
                   3561:         my @parts=split('/',$fpath);
                   3562:         foreach my $part (@parts) {
                   3563:             $filepath.= '/'.$part;
                   3564:             if ((-e $filepath)!=1) {
                   3565:                 mkdir($filepath,0777);
                   3566:             }
                   3567:         }
                   3568:     }
                   3569:     return $filepath;
                   3570: }
                   3571: 
                   3572: sub store_edited_file {
1.638     albertel 3573:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3574:     my $file = $primary_url;
                   3575:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3576:     my $fpath = '';
                   3577:     my $fname = $file;
                   3578:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3579:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3580:     my $filepath = &build_filepath($fpath);
                   3581:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3582:     print $fh $content;
                   3583:     close($fh);
1.638     albertel 3584:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3585:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3586: 			  $home);
1.637     raeburn  3587:     if ($$fetchresult eq 'ok') {
                   3588:         return '/uploaded/'.$fpath.'/'.$fname;
                   3589:     } else {
1.638     albertel 3590:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3591: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3592:         return '/adm/notfound.html';
                   3593:     }
                   3594: }
                   3595: 
1.531     albertel 3596: sub clean_filename {
1.831     albertel 3597:     my ($fname,$args)=@_;
1.315     www      3598: # Replace Windows backslashes by forward slashes
1.257     www      3599:     $fname=~s/\\/\//g;
1.831     albertel 3600:     if (!$args->{'keep_path'}) {
                   3601:         # Get rid of everything but the actual filename
                   3602: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3603:     }
1.315     www      3604: # Replace spaces by underscores
                   3605:     $fname=~s/\s+/\_/g;
                   3606: # Replace all other weird characters by nothing
1.831     albertel 3607:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3608: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3609: # numbers
                   3610:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3611:     return $fname;
                   3612: }
1.1051    raeburn  3613: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3614: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3615: # image with the same aspect ratio as the original, but with dimensions which do 
                   3616: # not exceed $resizewidth and $resizeheight.
                   3617:  
1.984     neumanie 3618: sub resizeImage {
1.1051    raeburn  3619:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3620:     my $ima = Image::Magick->new;
                   3621:     my $resized;
                   3622:     if (-e $img_path) {
                   3623:         $ima->Read($img_path);
                   3624:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3625:             my $width = $ima->Get('width');
                   3626:             my $height = $ima->Get('height');
                   3627:             if ($width > $resizewidth) {
                   3628: 	        my $factor = $width/$resizewidth;
                   3629:                 my $newheight = $height/$factor;
                   3630:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3631:                 $resized = 1;
                   3632:             }
                   3633:         }
                   3634:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3635:             my $width = $ima->Get('width');
                   3636:             my $height = $ima->Get('height');
                   3637:             if ($height > $resizeheight) {
                   3638:                 my $factor = $height/$resizeheight;
                   3639:                 my $newwidth = $width/$factor;
                   3640:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3641:                 $resized = 1;
                   3642:             }
                   3643:         }
                   3644:         if ($resized) {
                   3645:             $ima->Write($img_path);
                   3646:         }
                   3647:     }
                   3648:     return;
1.977     amueller 3649: }
                   3650: 
1.608     albertel 3651: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3652: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3653: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3654: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3655: #                                    canceloverwrite, or ''. 
                   3656: #                   if 'coursedoc': upload to the current course
                   3657: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3658: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3659: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3660: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3661: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3662: #        $allfiles - reference to hash for embedded objects
                   3663: #        $codebase - reference to hash for codebase of java objects
                   3664: #        $desuname - username for permanent storage of uploaded file
                   3665: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3666: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3667: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3668: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3669: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3670: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3671: #                    from File::MMagic.
1.858     raeburn  3672: # 
1.686     albertel 3673: # output: url of file in userspace, or error: <message> 
                   3674: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3675: 
1.531     albertel 3676: sub userfileupload {
1.1090    raeburn  3677:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3678:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3679:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3680:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3681:     $fname=&clean_filename($fname);
1.1090    raeburn  3682:     # See if there is anything left
1.257     www      3683:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3684:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3685:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3686:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3687:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3688:         my $now = time;
1.1090    raeburn  3689:         my $filepath;
1.1095    raeburn  3690:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3691:              $filepath = 'tmp/helprequests/'.$now;
                   3692:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3693:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3694:                          '_'.$env{'user.domain'}.'/pending';
                   3695:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3696:             my ($docuname,$docudom);
                   3697:             if ($destudom) {
                   3698:                 $docudom = $destudom;
                   3699:             } else {
                   3700:                 $docudom = $env{'user.domain'};
                   3701:             }
                   3702:             if ($destuname) {
                   3703:                 $docuname = $destuname;
                   3704:             } else {
                   3705:                 $docuname = $env{'user.name'};
                   3706:             }
                   3707:             if (exists($env{'form.group'})) {
                   3708:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3709:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3710:             }
                   3711:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3712:             if ($context eq 'canceloverwrite') {
                   3713:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3714:                 if (-e  $tempfile) {
                   3715:                     my @info = stat($tempfile);
                   3716:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3717:                         unlink($tempfile);
                   3718:                     }
                   3719:                 }
                   3720:                 return;
1.523     raeburn  3721:             }
                   3722:         }
1.1090    raeburn  3723:         # Create the directory if not present
1.741     raeburn  3724:         my @parts=split(/\//,$filepath);
                   3725:         my $fullpath = $perlvar{'lonDaemons'};
                   3726:         for (my $i=0;$i<@parts;$i++) {
                   3727:             $fullpath .= '/'.$parts[$i];
                   3728:             if ((-e $fullpath)!=1) {
                   3729:                 mkdir($fullpath,0777);
                   3730:             }
                   3731:         }
                   3732:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3733:         print $fh $env{'form.'.$formname};
                   3734:         close($fh);
1.1090    raeburn  3735:         if ($context eq 'existingfile') {
                   3736:             my @info = stat($fullpath.'/'.$fname);
                   3737:             return ($fullpath.'/'.$fname,$info[9]);
                   3738:         } else {
                   3739:             return $fullpath.'/'.$fname;
                   3740:         }
1.523     raeburn  3741:     }
1.995     raeburn  3742:     if ($subdir eq 'scantron') {
                   3743:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3744:     } else {
1.995     raeburn  3745:         $fname="$subdir/$fname";
                   3746:     }
1.1090    raeburn  3747:     if ($context eq 'coursedoc') {
1.638     albertel 3748: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3749: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3750:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3751:             return &finishuserfileupload($docuname,$docudom,
                   3752: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3753: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3754:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3755:         } else {
1.1218    raeburn  3756:             if ($env{'form.folder'}) {
                   3757:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3758:             }
1.638     albertel 3759:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3760: 				       $fname,$formname,$parser,
1.1095    raeburn  3761: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3762:         }
1.719     banghart 3763:     } elsif (defined($destuname)) {
                   3764:         my $docuname=$destuname;
                   3765:         my $docudom=$destudom;
1.860     raeburn  3766: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3767: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3768:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3769:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3770:     } else {
1.638     albertel 3771:         my $docuname=$env{'user.name'};
                   3772:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3773:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3774:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3775:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3776:         }
1.860     raeburn  3777: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3778: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3779:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3780:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3781:     }
1.271     www      3782: }
                   3783: 
                   3784: sub finishuserfileupload {
1.860     raeburn  3785:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3786:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3787:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3788:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3789:   
1.860     raeburn  3790:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3791:     $file=$fname;
                   3792:     if ($fname=~m|/|) {
                   3793:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3794: 	$path.=$fnamepath.'/';
                   3795:     }
1.259     www      3796:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3797:     my $count;
                   3798:     for ($count=4;$count<=$#parts;$count++) {
                   3799:         $filepath.="/$parts[$count]";
                   3800:         if ((-e $filepath)!=1) {
                   3801: 	    mkdir($filepath,0777);
                   3802:         }
                   3803:     }
1.984     neumanie 3804: 
1.258     www      3805: # Save the file
                   3806:     {
1.701     albertel 3807: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3808: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3809: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3810: 	    return '/adm/notfound.html';
                   3811: 	}
1.1090    raeburn  3812:         if ($context eq 'overwrite') {
1.1117    foxr     3813:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3814:             my $target = $filepath.'/'.$file;
                   3815:             if (-e $source) {
                   3816:                 my @info = stat($source);
                   3817:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3818:                     unless (&File::Copy::move($source,$target)) {
                   3819:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3820:                         return "Moving from $source failed";
                   3821:                     }
                   3822:                 } else {
                   3823:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3824:                 }
                   3825:             } else {
                   3826:                 return "Temporary file: $source missing";
                   3827:             }
                   3828:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3829: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3830: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3831: 	    return '/adm/notfound.html';
                   3832: 	}
1.570     albertel 3833: 	close(FH);
1.1051    raeburn  3834:         if ($resizewidth && $resizeheight) {
                   3835:             my $mm = new File::MMagic;
                   3836:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3837:             if ($mime_type =~ m{^image/}) {
                   3838: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3839:             }  
1.977     amueller 3840: 	}
1.258     www      3841:     }
1.1152    raeburn  3842:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3843:         if (ref($mimetype)) {
                   3844:             if ($$mimetype eq '') {
                   3845:                 my $mm = new File::MMagic;
                   3846:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3847:                 $$mimetype = $type;
                   3848:             }
                   3849:         }
                   3850:     }
1.637     raeburn  3851:     if ($parser eq 'parse') {
1.1152    raeburn  3852:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3853:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3854:                                                        $allfiles,$codebase);
                   3855:             unless ($parse_result eq 'ok') {
                   3856:                 &logthis('Failed to parse '.$filepath.$file.
                   3857: 	   	         ' for embedded media: '.$parse_result); 
                   3858:             }
1.637     raeburn  3859:         }
                   3860:     }
1.860     raeburn  3861:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3862:         my $input = $filepath.'/'.$file;
                   3863:         my $output = $filepath.'/'.'tn-'.$file;
                   3864:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3865:         system("convert -sample $thumbsize $input $output");
                   3866:         if (-e $filepath.'/'.'tn-'.$file) {
                   3867:             $fetchthumb  = 1; 
                   3868:         }
                   3869:     }
1.858     raeburn  3870:  
1.259     www      3871: # Notify homeserver to grep it
                   3872: #
1.984     neumanie 3873:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3874:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3875:     if ($fetchresult eq 'ok') {
1.860     raeburn  3876:         if ($fetchthumb) {
                   3877:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3878:             if ($thumbresult ne 'ok') {
                   3879:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3880:                          $docuhome.': '.$thumbresult);
                   3881:             }
                   3882:         }
1.259     www      3883: #
1.258     www      3884: # Return the URL to it
1.494     albertel 3885:         return '/uploaded/'.$path.$file;
1.263     www      3886:     } else {
1.494     albertel 3887:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3888: 		 ': '.$fetchresult);
1.263     www      3889:         return '/adm/notfound.html';
1.858     raeburn  3890:     }
1.493     albertel 3891: }
                   3892: 
1.637     raeburn  3893: sub extract_embedded_items {
1.961     raeburn  3894:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3895:     my @state = ();
1.1164    raeburn  3896:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3897:     my %javafiles = (
                   3898:                       codebase => '',
                   3899:                       code => '',
                   3900:                       archive => ''
                   3901:                     );
                   3902:     my %mediafiles = (
                   3903:                       src => '',
                   3904:                       movie => '',
                   3905:                      );
1.648     raeburn  3906:     my $p;
                   3907:     if ($content) {
                   3908:         $p = HTML::LCParser->new($content);
                   3909:     } else {
1.961     raeburn  3910:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3911:     }
1.641     albertel 3912:     while (my $t=$p->get_token()) {
1.640     albertel 3913: 	if ($t->[0] eq 'S') {
                   3914: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3915: 	    push(@state, $tagname);
1.648     raeburn  3916:             if (lc($tagname) eq 'allow') {
                   3917:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3918:             }
1.640     albertel 3919: 	    if (lc($tagname) eq 'img') {
                   3920: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3921: 	    }
1.886     albertel 3922: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  3923:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  3924:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3925:                 }
1.886     albertel 3926: 	    }
1.645     raeburn  3927:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3928:                 my $src;
1.645     raeburn  3929:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3930:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3931:                 } else {
1.1164    raeburn  3932:                     if ($attr->{'src'} ne '') {
                   3933:                         $src = $attr->{'src'};
                   3934:                         &add_filetype($allfiles,$src,'src');
                   3935:                     }
                   3936:                 }
                   3937:                 my $text = $p->get_trimmed_text();
                   3938:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3939:                     my @swfargs = split(/,/,$1);
                   3940:                     foreach my $item (@swfargs) {
                   3941:                         $item =~ s/["']//g;
                   3942:                         $item =~ s/^\s+//;
                   3943:                         $item =~ s/\s+$//;
                   3944:                     }
                   3945:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3946:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3947:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3948:                         } else {
                   3949:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3950:                         }
                   3951:                     }
1.645     raeburn  3952:                 }
                   3953:             }
                   3954:             if (lc($tagname) eq 'link') {
                   3955:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3956:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3957:                 }
                   3958:             }
1.640     albertel 3959: 	    if (lc($tagname) eq 'object' ||
                   3960: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3961: 		foreach my $item (keys(%javafiles)) {
                   3962: 		    $javafiles{$item} = '';
                   3963: 		}
1.1164    raeburn  3964:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3965:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3966:                 }
1.640     albertel 3967: 	    }
                   3968: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3969: 		my $name = lc($attr->{'name'});
                   3970: 		foreach my $item (keys(%javafiles)) {
                   3971: 		    if ($name eq $item) {
                   3972: 			$javafiles{$item} = $attr->{'value'};
                   3973: 			last;
                   3974: 		    }
                   3975: 		}
1.1164    raeburn  3976:                 my $pathfrom;
1.640     albertel 3977: 		foreach my $item (keys(%mediafiles)) {
                   3978: 		    if ($name eq $item) {
1.1164    raeburn  3979:                         $pathfrom = $attr->{'value'};
                   3980:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3981: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3982: 			last;
                   3983: 		    }
                   3984: 		}
1.1164    raeburn  3985:                 if ($name eq 'flashvars') {
                   3986:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3987:                 }
                   3988:                 if ($pathfrom ne '') {
                   3989:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3990:                                          $pathfrom);
                   3991:                 }
1.640     albertel 3992: 	    }
                   3993: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3994: 		foreach my $item (keys(%javafiles)) {
                   3995: 		    if ($attr->{$item}) {
                   3996: 			$javafiles{$item} = $attr->{$item};
                   3997: 			last;
                   3998: 		    }
                   3999: 		}
                   4000: 		foreach my $item (keys(%mediafiles)) {
                   4001: 		    if ($attr->{$item}) {
                   4002: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4003: 			last;
                   4004: 		    }
                   4005: 		}
1.1164    raeburn  4006:                 if (lc($tagname) eq 'embed') {
                   4007:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4008:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4009:                                              $attr->{'src'});
                   4010:                     }
                   4011:                 }
1.640     albertel 4012: 	    }
1.1243    raeburn  4013:             if (lc($tagname) eq 'iframe') {
                   4014:                 my $src = $attr->{'src'} ;
                   4015:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4016:                     &add_filetype($allfiles,$src,'src');
                   4017:                 } elsif ($src =~ m{^/}) {
                   4018:                     if ($env{'request.course.id'}) {
                   4019:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4020:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4021:                         my $url = &hreflocation('',$fullpath);
                   4022:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4023:                             my $relpath = $1;
                   4024:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4025:                                 &add_filetype($allfiles,$1,'src');
                   4026:                             }
                   4027:                         }
                   4028:                     }
                   4029:                 }
                   4030:             }
1.1164    raeburn  4031:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  4032:                 pop(@state);
1.1164    raeburn  4033:             }
1.640     albertel 4034: 	} elsif ($t->[0] eq 'E') {
                   4035: 	    my ($tagname) = ($t->[1]);
                   4036: 	    if ($javafiles{'codebase'} ne '') {
                   4037: 		$javafiles{'codebase'} .= '/';
                   4038: 	    }  
                   4039: 	    if (lc($tagname) eq 'applet' ||
                   4040: 		lc($tagname) eq 'object' ||
                   4041: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4042: 		) {
                   4043: 		foreach my $item (keys(%javafiles)) {
                   4044: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4045: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4046: 			&add_filetype($allfiles,$file,$item);
                   4047: 		    }
                   4048: 		}
                   4049: 	    } 
                   4050: 	    pop @state;
                   4051: 	}
                   4052:     }
1.1164    raeburn  4053:     foreach my $id (sort(keys(%flashvars))) {
                   4054:         if ($shockwave{$id} ne '') {
                   4055:             my @pairs = split(/\&/,$flashvars{$id});
                   4056:             foreach my $pair (@pairs) {
                   4057:                 my ($key,$value) = split(/\=/,$pair);
                   4058:                 if ($key eq 'thumb') {
                   4059:                     &add_filetype($allfiles,$value,$key);
                   4060:                 } elsif ($key eq 'content') {
                   4061:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4062:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4063:                     if ($ext ne '') {
                   4064:                         &add_filetype($allfiles,$path.$value,$ext);
                   4065:                     }
                   4066:                 }
                   4067:             }
                   4068:         }
                   4069:     }
1.637     raeburn  4070:     return 'ok';
                   4071: }
                   4072: 
1.639     albertel 4073: sub add_filetype {
                   4074:     my ($allfiles,$file,$type)=@_;
                   4075:     if (exists($allfiles->{$file})) {
                   4076: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4077: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4078: 	}
                   4079:     } else {
                   4080: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4081:     }
                   4082: }
                   4083: 
1.1164    raeburn  4084: sub embedded_dependency {
                   4085:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4086:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4087:         if (($identifier ne '') &&
                   4088:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4089:             ($pathfrom ne '')) {
                   4090:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4091:             foreach my $dep (@{$related->{$identifier}}) {
                   4092:                 &add_filetype($allfiles,$path.$dep,'object');
                   4093:             }
                   4094:         }
                   4095:     }
                   4096:     return;
                   4097: }
                   4098: 
1.493     albertel 4099: sub removeuploadedurl {
1.984     neumanie 4100:     my ($url)=@_;	
                   4101:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4102:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4103: }
                   4104: 
                   4105: sub removeuserfile {
                   4106:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4107:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4108:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4109:     if ($result eq 'ok') {	
1.798     raeburn  4110:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4111:             my $metafile = $fname.'.meta';
                   4112:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4113: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4114:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4115:             my $sqlresult = 
1.823     albertel 4116:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4117:                                         'portfolio_metadata',$group,
                   4118:                                         'delete');
1.798     raeburn  4119:         }
                   4120:     }
                   4121:     return $result;
1.257     www      4122: }
1.15      www      4123: 
1.530     albertel 4124: sub mkdiruserfile {
                   4125:     my ($docuname,$docudom,$dir)=@_;
                   4126:     my $home=&homeserver($docuname,$docudom);
                   4127:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4128: }
                   4129: 
1.531     albertel 4130: sub renameuserfile {
                   4131:     my ($docuname,$docudom,$old,$new)=@_;
                   4132:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4133:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4134:                         &escape("$old").':'.&escape("$new"),$home);
                   4135:     if ($result eq 'ok') {
                   4136:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4137:             my $oldmeta = $old.'.meta';
                   4138:             my $newmeta = $new.'.meta';
                   4139:             my $metaresult = 
                   4140:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4141: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4142:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4143:             my $sqlresult = 
1.823     albertel 4144:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4145:                                         'portfolio_metadata',$group,
                   4146:                                         'delete');
1.798     raeburn  4147:         }
                   4148:     }
                   4149:     return $result;
1.531     albertel 4150: }
                   4151: 
1.14      www      4152: # ------------------------------------------------------------------------- Log
                   4153: 
                   4154: sub log {
                   4155:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4156:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4157: }
                   4158: 
                   4159: # ------------------------------------------------------------------ Course Log
1.352     www      4160: #
                   4161: # This routine flushes several buffers of non-mission-critical nature
                   4162: #
1.157     www      4163: 
                   4164: sub flushcourselogs {
1.352     www      4165:     &logthis('Flushing log buffers');
                   4166: #
                   4167: # course logs
                   4168: # This is a log of all transactions in a course, which can be used
                   4169: # for data mining purposes
                   4170: #
                   4171: # It also collects the courseid database, which lists last transaction
                   4172: # times and course titles for all courseids
                   4173: #
                   4174:     my %courseidbuffer=();
1.921     raeburn  4175:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4176:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4177: 		          &escape($courselogs{$crsid}),
                   4178: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4179: 	    delete $courselogs{$crsid};
                   4180:         } else {
                   4181:             &logthis('Failed to flush log buffer for '.$crsid);
                   4182:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4183:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4184:                         " exceeded maximum size, deleting.</font>");
                   4185:                delete $courselogs{$crsid};
                   4186:             }
1.352     www      4187:         }
1.920     raeburn  4188:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4189:             'description' => $coursedescrbuf{$crsid},
                   4190:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4191:             'type'        => $coursetypebuf{$crsid},
                   4192:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4193:         };
1.191     harris41 4194:     }
1.352     www      4195: #
                   4196: # Write course id database (reverse lookup) to homeserver of courses 
                   4197: # Is used in pickcourse
                   4198: #
1.840     albertel 4199:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4200:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4201:                                     $courseidbuffer{$crs_home},
                   4202:                                     $crs_home,'timeonly');
1.352     www      4203:     }
                   4204: #
                   4205: # File accesses
                   4206: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4207: #
1.449     matthew  4208:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4209:         if ($entry =~ /___count$/) {
                   4210:             my ($dom,$name);
1.807     albertel 4211:             ($dom,$name,undef)=
1.811     albertel 4212: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4213:             if (! defined($dom) || $dom eq '' || 
                   4214:                 ! defined($name) || $name eq '') {
1.620     albertel 4215:                 my $cid = $env{'request.course.id'};
                   4216:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4217:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4218:             }
1.450     matthew  4219:             my $value = $accesshash{$entry};
                   4220:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4221:             my %temphash=($url => $value);
1.449     matthew  4222:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4223:             if ($result eq 'ok') {
                   4224:                 delete $accesshash{$entry};
                   4225:             }
                   4226:         } else {
1.811     albertel 4227:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4228:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4229:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4230:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4231:                 delete $accesshash{$entry};
                   4232:             }
1.185     www      4233:         }
1.191     harris41 4234:     }
1.352     www      4235: #
                   4236: # Roles
                   4237: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4238: #
1.800     albertel 4239:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4240:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4241: 	    split(/\:/,$entry);
                   4242:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4243:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4244:                 $rudom,$runame) eq 'ok') {
                   4245: 	    delete $userrolehash{$entry};
                   4246:         }
                   4247:     }
1.662     raeburn  4248: #
1.1334    raeburn  4249: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4250: #
                   4251:     my %domrolebuffer = ();
1.1000    raeburn  4252:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4253:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4254:         if ($domrolebuffer{$rudom}) {
                   4255:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4256:                       '='.&escape($domainrolehash{$entry});
                   4257:         } else {
                   4258:             $domrolebuffer{$rudom}.=&escape($entry).
                   4259:                       '='.&escape($domainrolehash{$entry});
                   4260:         }
                   4261:         delete $domainrolehash{$entry};
                   4262:     }
                   4263:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  4264: 	my %servers;
                   4265: 	if (defined(&domain($dom,'primary'))) {
                   4266: 	    my $primary=&domain($dom,'primary');
                   4267: 	    my $hostname=&hostname($primary);
                   4268: 	    $servers{$primary} = $hostname;
                   4269: 	} else { 
                   4270: 	    %servers = &get_servers($dom,'library');
                   4271: 	}
1.841     albertel 4272: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  4273: 	    if (&reply('domroleput:'.$dom.':'.
                   4274: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4275: 		last;
                   4276: 	    } else {  
1.841     albertel 4277: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4278: 	    }
1.662     raeburn  4279:         }
                   4280:     }
1.186     www      4281:     $dumpcount++;
1.157     www      4282: }
                   4283: 
                   4284: sub courselog {
                   4285:     my $what=shift;
1.158     www      4286:     $what=time.':'.$what;
1.620     albertel 4287:     unless ($env{'request.course.id'}) { return ''; }
                   4288:     $coursedombuf{$env{'request.course.id'}}=
                   4289:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4290:     $coursenumbuf{$env{'request.course.id'}}=
                   4291:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4292:     $coursehombuf{$env{'request.course.id'}}=
                   4293:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4294:     $coursedescrbuf{$env{'request.course.id'}}=
                   4295:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4296:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4297:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4298:     $courseownerbuf{$env{'request.course.id'}}=
                   4299:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4300:     $coursetypebuf{$env{'request.course.id'}}=
                   4301:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4302:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4303: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4304:     } else {
1.620     albertel 4305: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4306:     }
1.620     albertel 4307:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4308: 	&flushcourselogs();
                   4309:     }
1.158     www      4310: }
                   4311: 
                   4312: sub courseacclog {
                   4313:     my $fnsymb=shift;
1.620     albertel 4314:     unless ($env{'request.course.id'}) { return ''; }
                   4315:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4316:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4317:         $what.=':POST';
1.583     matthew  4318:         # FIXME: Probably ought to escape things....
1.800     albertel 4319: 	foreach my $key (keys(%env)) {
                   4320:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4321:                 my $formitem = $1;
                   4322:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4323:                     $what.=':'.$formitem.'='.$env{$key};
                   4324:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4325:                     $what.=':'.$formitem.'='.$env{$key};
                   4326:                 }
1.158     www      4327:             }
1.191     harris41 4328:         }
1.583     matthew  4329:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4330:         # FIXME: We should not be depending on a form parameter that someone
                   4331:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4332:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4333:             $what.= ':POST';
                   4334:             # FIXME: Probably ought to escape things....
                   4335:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4336:                                  'crsdiscuss') {
1.620     albertel 4337:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4338:             }
                   4339:         }
1.158     www      4340:     }
                   4341:     &courselog($what);
1.149     www      4342: }
                   4343: 
1.185     www      4344: sub countacc {
                   4345:     my $url=&declutter(shift);
1.458     matthew  4346:     return if (! defined($url) || $url eq '');
1.620     albertel 4347:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4348: #
                   4349: # Mark that this url was used in this course
                   4350: #
1.620     albertel 4351:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4352: #
                   4353: # Increase the access count for this resource in this child process
                   4354: #
1.281     www      4355:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4356:     $accesshash{$key}++;
1.185     www      4357: }
1.349     www      4358: 
1.361     www      4359: sub linklog {
                   4360:     my ($from,$to)=@_;
                   4361:     $from=&declutter($from);
                   4362:     $to=&declutter($to);
                   4363:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4364:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4365: }
1.1160    www      4366: 
                   4367: sub statslog {
                   4368:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4369:     if ($users<2) { return; }
                   4370:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4371:             'course'       => $env{'request.course.id'},
                   4372:             'sections'     => '"all"',
                   4373:             'num_students' => $users,
                   4374:             'part'         => $part,
                   4375:             'symb'         => $symb,
                   4376:             'mean_tries'   => $av_attempts,
                   4377:             'deg_of_diff'  => $degdiff});
                   4378:     foreach my $key (keys(%dynstore)) {
                   4379:         $accesshash{$key}=$dynstore{$key};
                   4380:     }
                   4381: }
1.361     www      4382:   
1.349     www      4383: sub userrolelog {
                   4384:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4385:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4386:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4387:        $userrolehash
                   4388:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4389:                     =$tend.':'.$tstart;
1.662     raeburn  4390:     }
1.1169    droeschl 4391:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4392:        $userrolehash
                   4393:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4394:                     =$tend.':'.$tstart;
                   4395:     }
1.1334    raeburn  4396:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4397:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4398:        $domainrolehash
                   4399:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4400:                     = $tend.':'.$tstart;
                   4401:     }
1.351     www      4402: }
                   4403: 
1.957     raeburn  4404: sub courserolelog {
                   4405:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4406:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4407:         my $cdom = $1;
                   4408:         my $cnum = $2;
                   4409:         my $sec = $3;
                   4410:         my $namespace = 'rolelog';
                   4411:         my %storehash = (
                   4412:                            role    => $trole,
                   4413:                            start   => $tstart,
                   4414:                            end     => $tend,
                   4415:                            selfenroll => $selfenroll,
                   4416:                            context    => $context,
                   4417:                         );
                   4418:         if ($trole eq 'gr') {
                   4419:             $namespace = 'groupslog';
                   4420:             $storehash{'group'} = $sec;
                   4421:         } else {
                   4422:             $storehash{'section'} = $sec;
                   4423:         }
1.1188    raeburn  4424:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4425:                    $domain,$cnum,$cdom);
1.1184    raeburn  4426:         if (($trole ne 'st') || ($sec ne '')) {
                   4427:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4428:         }
                   4429:     }
                   4430:     return;
                   4431: }
                   4432: 
1.1184    raeburn  4433: sub domainrolelog {
                   4434:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4435:     if ($area =~ m{^/($match_domain)/$}) {
                   4436:         my $cdom = $1;
                   4437:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4438:         my $namespace = 'rolelog';
                   4439:         my %storehash = (
                   4440:                            role    => $trole,
                   4441:                            start   => $tstart,
                   4442:                            end     => $tend,
                   4443:                            context => $context,
                   4444:                         );
1.1188    raeburn  4445:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4446:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4447:     }
                   4448:     return;
                   4449: 
                   4450: }
                   4451: 
                   4452: sub coauthorrolelog {
                   4453:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4454:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4455:         my $audom = $1;
                   4456:         my $auname = $2;
                   4457:         my $namespace = 'rolelog';
                   4458:         my %storehash = (
                   4459:                            role    => $trole,
                   4460:                            start   => $tstart,
                   4461:                            end     => $tend,
                   4462:                            context => $context,
                   4463:                         );
1.1188    raeburn  4464:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4465:                    $domain,$auname,$audom);
1.1184    raeburn  4466:     }
                   4467:     return;
                   4468: }
                   4469: 
1.351     www      4470: sub get_course_adv_roles {
1.948     raeburn  4471:     my ($cid,$codes) = @_;
1.620     albertel 4472:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4473:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4474:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4475:     my %nothide=();
1.800     albertel 4476:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4477:         if ($user !~ /:/) {
                   4478: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4479:         } else {
                   4480:             $nothide{$user}=1;
                   4481:         }
1.470     www      4482:     }
1.1219    raeburn  4483:     my @possdoms = ($coursehash{'domain'});
                   4484:     if ($coursehash{'checkforpriv'}) {
                   4485:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4486:     }
1.351     www      4487:     my %returnhash=();
                   4488:     my %dumphash=
                   4489:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4490:     my $now=time;
1.997     raeburn  4491:     my %privileged;
1.1000    raeburn  4492:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4493: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4494:         if (($tstart) && ($tstart<0)) { next; }
                   4495:         if (($tend) && ($tend<$now)) { next; }
                   4496:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4497:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4498: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4499:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4500:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4501: 	if ($role eq 'cr') { next; }
1.948     raeburn  4502:         if ($codes) {
                   4503:             if ($section) { $role .= ':'.$section; }
                   4504:             if ($returnhash{$role}) {
                   4505:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4506:             } else {
                   4507:                 $returnhash{$role}=$username.':'.$domain;
                   4508:             }
1.351     www      4509:         } else {
1.988     raeburn  4510:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4511:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4512:             if ($returnhash{$key}) {
                   4513: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4514:             } else {
                   4515:                 $returnhash{$key}=$username.':'.$domain;
                   4516:             }
1.351     www      4517:         }
1.948     raeburn  4518:     }
1.400     www      4519:     return %returnhash;
                   4520: }
                   4521: 
                   4522: sub get_my_roles {
1.937     raeburn  4523:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4524:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4525:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4526:     my (%dumphash,%nothide);
1.1086    raeburn  4527:     if ($context eq 'userroles') {
1.1166    raeburn  4528:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4529:     } else {
1.1219    raeburn  4530:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4531:         if ($hidepriv) {
                   4532:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4533:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4534:                 if ($user !~ /:/) {
                   4535:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4536:                 } else {
                   4537:                     $nothide{$user} = 1;
                   4538:                 }
                   4539:             }
                   4540:         }
1.858     raeburn  4541:     }
1.400     www      4542:     my %returnhash=();
                   4543:     my $now=time;
1.999     raeburn  4544:     my %privileged;
1.800     albertel 4545:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4546:         my ($role,$tend,$tstart);
                   4547:         if ($context eq 'userroles') {
1.1149    raeburn  4548:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4549: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4550:         } else {
                   4551:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4552:         }
1.400     www      4553:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4554:         my $status = 'active';
1.939     raeburn  4555:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4556:             $status = 'previous';
                   4557:         } 
                   4558:         if (($tstart) && ($now<$tstart)) {
                   4559:             $status = 'future';
                   4560:         }
                   4561:         if (ref($types) eq 'ARRAY') {
                   4562:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4563:                 next;
                   4564:             } 
                   4565:         } else {
                   4566:             if ($status ne 'active') {
                   4567:                 next;
                   4568:             }
                   4569:         }
1.867     raeburn  4570:         my ($rolecode,$username,$domain,$section,$area);
                   4571:         if ($context eq 'userroles') {
1.1186    raeburn  4572:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4573:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4574:         } else {
                   4575:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4576:         }
1.832     raeburn  4577:         if (ref($roledoms) eq 'ARRAY') {
                   4578:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4579:                 next;
                   4580:             }
                   4581:         }
                   4582:         if (ref($roles) eq 'ARRAY') {
                   4583:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4584:                 if ($role =~ /^cr\//) {
                   4585:                     if (!grep(/^cr$/,@{$roles})) {
                   4586:                         next;
                   4587:                     }
1.1104    raeburn  4588:                 } elsif ($role =~ /^gr\//) {
                   4589:                     if (!grep(/^gr$/,@{$roles})) {
                   4590:                         next;
                   4591:                     }
1.922     raeburn  4592:                 } else {
                   4593:                     next;
                   4594:                 }
1.832     raeburn  4595:             }
1.867     raeburn  4596:         }
1.937     raeburn  4597:         if ($hidepriv) {
1.1219    raeburn  4598:             my @privroles = ('dc','su');
1.999     raeburn  4599:             if ($context eq 'userroles') {
1.1219    raeburn  4600:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4601:             } else {
1.1219    raeburn  4602:                 my $possdoms = [$domain];
                   4603:                 if (ref($roledoms) eq 'ARRAY') {
                   4604:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4605:                 }
1.1219    raeburn  4606:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4607:                     if (!$nothide{$username.':'.$domain}) {
                   4608:                         next;
                   4609:                     }
                   4610:                 }
1.937     raeburn  4611:             }
                   4612:         }
1.933     raeburn  4613:         if ($withsec) {
                   4614:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4615:                 $tstart.':'.$tend;
                   4616:         } else {
                   4617:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4618:         }
1.832     raeburn  4619:     }
1.373     www      4620:     return %returnhash;
1.399     www      4621: }
                   4622: 
1.1333    raeburn  4623: sub get_all_adhocroles {
                   4624:     my ($dom) = @_;
                   4625:     my @roles_by_num = ();
                   4626:     my %domdefaults = &get_domain_defaults($dom);
                   4627:     my (%description,%access_in_dom,%access_info);
                   4628:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4629:         my $count = 0;
                   4630:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4631:         my %ordered;
                   4632:         foreach my $role (sort(keys(%domcurrent))) {
                   4633:             my ($order,$desc,$access_in_dom);
                   4634:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4635:                 $order = $domcurrent{$role}{'order'};
                   4636:                 $desc = $domcurrent{$role}{'desc'};
                   4637:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4638:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4639:             }
                   4640:             if ($order eq '') {
                   4641:                 $order = $count;
                   4642:             }
                   4643:             $ordered{$order} = $role;
                   4644:             if ($desc ne '') {
                   4645:                 $description{$role} = $desc;
                   4646:             } else {
                   4647:                 $description{$role}= $role;
                   4648:             }
                   4649:             $count++;
                   4650:         }
                   4651:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4652:             push(@roles_by_num,$ordered{$item});
                   4653:         }
                   4654:     }
                   4655:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4656: }
                   4657: 
1.1332    raeburn  4658: sub get_my_adhocroles {
1.1333    raeburn  4659:     my ($cid,$checkreg) = @_;
                   4660:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4661:     if ($env{'request.course.id'} eq $cid) {
                   4662:         $cdom = $env{'course.'.$cid.'.domain'};
                   4663:         $cnum = $env{'course.'.$cid.'.num'};
                   4664:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4665:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4666:         $cdom = $1;
                   4667:         $cnum = $2;
                   4668:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4669:                                      $cdom,$cnum);
                   4670:     }
                   4671:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4672:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4673:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4674:         if ($rosterhash{$user} ne '') {
                   4675:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4676:             return ([],{}) if ($type eq 'auto');
                   4677:         }
                   4678:     }
                   4679:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334    raeburn  4680:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  4681:             my $then=$env{'user.login.time'};
                   4682:             my $update=$env{'user.update.time'};
1.1335    raeburn  4683:             if (!$update) {
                   4684:                 $update = $then;
                   4685:             }
                   4686:             my @liveroles;
1.1334    raeburn  4687:             foreach my $role ('dh','da') {
                   4688:                 if ($env{"user.role.$role./$cdom/"}) {
1.1335    raeburn  4689:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334    raeburn  4690:                     my $limit = $update;
                   4691:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4692:                         $limit = $then;
                   4693:                     }
1.1335    raeburn  4694:                     my $activerole = 1;
                   4695:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4696:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4697:                     if ($activerole) {
                   4698:                         push(@liveroles,$role);
                   4699:                     }
1.1334    raeburn  4700:                 }
1.1332    raeburn  4701:             }
1.1335    raeburn  4702:             if (@liveroles) {
1.1332    raeburn  4703:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  4704:                     my ($accessref,$accessinfo,%access_in_dom);
                   4705:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4706:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4707:                         if (@{$roles_by_num}) {
1.1332    raeburn  4708:                             my %settings;
                   4709:                             if ($env{'request.course.id'} eq $cid) {
                   4710:                                 foreach my $envkey (keys(%env)) {
                   4711:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4712:                                         $settings{$1} = $env{$envkey};
                   4713:                                     }
                   4714:                                 }
                   4715:                             } else {
                   4716:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4717:                             }
                   4718:                             my %setincrs;
                   4719:                             if ($settings{'internal.adhocaccess'}) {
                   4720:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4721:                             }
                   4722:                             my @statuses;
                   4723:                             if ($env{'environment.inststatus'}) {
                   4724:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4725:                             }
                   4726:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  4727:                             if (ref($accessref) eq 'HASH') {
                   4728:                                 %access_in_dom = %{$accessref};
                   4729:                             }
                   4730:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  4731:                                 my ($curraccess,@okstatus,@personnel);
                   4732:                                 if ($setincrs{$role}) {
                   4733:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   4734:                                     if ($curraccess eq 'status') {
                   4735:                                         @okstatus = split(/\&/,$rest);
                   4736:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4737:                                         @personnel = split(/\&/,$rest);
                   4738:                                     }
                   4739:                                 } else {
                   4740:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  4741:                                     if (ref($accessinfo) eq 'HASH') {
                   4742:                                         if ($curraccess eq 'status') {
                   4743:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4744:                                                 @okstatus = @{$accessinfo->{$role}};
                   4745:                                             }
                   4746:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4747:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4748:                                                 @personnel = @{$accessinfo->{$role}};
                   4749:                                             }
1.1332    raeburn  4750:                                         }
                   4751:                                     }
                   4752:                                 }
                   4753:                                 if ($curraccess eq 'none') {
                   4754:                                     next;
                   4755:                                 } elsif ($curraccess eq 'all') {
                   4756:                                     push(@possroles,$role);
1.1336    raeburn  4757:                                 } elsif ($curraccess eq 'dh') {
1.1335    raeburn  4758:                                     if (grep(/^dh$/,@liveroles)) {
                   4759:                                         push(@possroles,$role);
                   4760:                                     } else {
                   4761:                                         next;
                   4762:                                     }
1.1336    raeburn  4763:                                 } elsif ($curraccess eq 'da') {
1.1335    raeburn  4764:                                     if (grep(/^da$/,@liveroles)) {
                   4765:                                         push(@possroles,$role);
                   4766:                                     } else {
                   4767:                                         next;
                   4768:                                     }
1.1332    raeburn  4769:                                 } elsif ($curraccess eq 'status') {
                   4770:                                     if (@okstatus) {
                   4771:                                         if (!@statuses) {
                   4772:                                             if (grep(/^default$/,@okstatus)) {
                   4773:                                                 push(@possroles,$role);
                   4774:                                             }
                   4775:                                         } else {
                   4776:                                             foreach my $status (@okstatus) {
                   4777:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   4778:                                                     push(@possroles,$role);
                   4779:                                                     last;
                   4780:                                                 }
                   4781:                                             }
                   4782:                                         }
                   4783:                                     }
                   4784:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4785:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   4786:                                         if ($curraccess eq 'exc') {
                   4787:                                             push(@possroles,$role);
                   4788:                                         }
                   4789:                                     } elsif ($curraccess eq 'inc') {
                   4790:                                         push(@possroles,$role);
                   4791:                                     }
                   4792:                                 }
                   4793:                             }
                   4794:                         }
                   4795:                     }
                   4796:                 }
                   4797:             }
                   4798:         }
                   4799:     }
1.1333    raeburn  4800:     unless (ref($description) eq 'HASH') {
                   4801:         if (ref($roles_by_num) eq 'ARRAY') {
                   4802:             my %desc;
                   4803:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   4804:             $description = \%desc;
                   4805:         } else {
                   4806:             $description = {};
                   4807:         }
                   4808:     }
                   4809:     return (\@possroles,$description);
1.1332    raeburn  4810: }
                   4811: 
1.399     www      4812: # ----------------------------------------------------- Frontpage Announcements
                   4813: #
                   4814: #
                   4815: 
                   4816: sub postannounce {
                   4817:     my ($server,$text)=@_;
1.844     albertel 4818:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4819:     unless ($text=~/\w/) { $text=''; }
                   4820:     return &reply('setannounce:'.&escape($text),$server);
                   4821: }
                   4822: 
                   4823: sub getannounce {
1.448     albertel 4824: 
                   4825:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4826: 	my $announcement='';
1.800     albertel 4827: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4828: 	close($fh);
1.399     www      4829: 	if ($announcement=~/\w/) { 
                   4830: 	    return 
                   4831:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4832:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4833: 	} else {
                   4834: 	    return '';
                   4835: 	}
                   4836:     } else {
                   4837: 	return '';
                   4838:     }
1.351     www      4839: }
1.353     www      4840: 
                   4841: # ---------------------------------------------------------- Course ID routines
                   4842: # Deal with domain's nohist_courseid.db files
                   4843: #
                   4844: 
                   4845: sub courseidput {
1.921     raeburn  4846:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4847:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4848:     my $outcome;
                   4849:     if ($caller eq 'timeonly') {
                   4850:         my $cids = '';
                   4851:         foreach my $item (keys(%$storehash)) {
                   4852:             $cids.=&escape($item).'&';
                   4853:         }
                   4854:         $cids=~s/\&$//;
                   4855:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4856:                           $coursehome);       
                   4857:     } else {
                   4858:         my $items = '';
                   4859:         foreach my $item (keys(%$storehash)) {
                   4860:             $items.= &escape($item).'='.
                   4861:                      &freeze_escape($$storehash{$item}).'&';
                   4862:         }
                   4863:         $items=~s/\&$//;
                   4864:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4865:                           $coursehome);
1.918     raeburn  4866:     }
                   4867:     if ($outcome eq 'unknown_cmd') {
                   4868:         my $what;
                   4869:         foreach my $cid (keys(%$storehash)) {
                   4870:             $what .= &escape($cid).'=';
1.921     raeburn  4871:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4872:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4873:             }
                   4874:             $what =~ s/\:$/&/;
                   4875:         }
                   4876:         $what =~ s/\&$//;  
                   4877:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4878:     } else {
                   4879:         return $outcome;
                   4880:     }
1.353     www      4881: }
                   4882: 
                   4883: sub courseiddump {
1.921     raeburn  4884:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4885:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4886:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  4887:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  4888:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4889:     my $as_hash = 1;
                   4890:     my %returnhash;
                   4891:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4892:     my %libserv = &all_library();
                   4893:     foreach my $tryserver (keys(%libserv)) {
                   4894:         if ( (  $hostidflag == 1 
                   4895: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4896: 	     || (!defined($hostidflag)) ) {
                   4897: 
1.918     raeburn  4898: 	    if (($domfilter eq '') ||
                   4899: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4900:                 my $rep;
                   4901:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4902:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4903:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   4904:                                 &escape($descfilter), &escape($instcodefilter), 
                   4905:                                 &escape($ownerfilter), &escape($coursefilter),
                   4906:                                 &escape($typefilter), &escape($regexp_ok), 
                   4907:                                 $as_hash, &escape($selfenrollonly), 
                   4908:                                 &escape($catfilter), $showhidden, $caller, 
                   4909:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   4910:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  4911:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   4912:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 4913:                 } else {
                   4914:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4915:                              $sincefilter.':'.&escape($descfilter).':'.
                   4916:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4917:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4918:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4919:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4920:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4921:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4922:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  4923:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   4924:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 4925:                 }
                   4926:                      
1.918     raeburn  4927:                 my @pairs=split(/\&/,$rep);
                   4928:                 foreach my $item (@pairs) {
                   4929:                     my ($key,$value)=split(/\=/,$item,2);
                   4930:                     $key = &unescape($key);
                   4931:                     next if ($key =~ /^error: 2 /);
                   4932:                     my $result = &thaw_unescape($value);
                   4933:                     if (ref($result) eq 'HASH') {
                   4934:                         $returnhash{$key}=$result;
                   4935:                     } else {
1.921     raeburn  4936:                         my @responses = split(/:/,$value);
                   4937:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4938:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4939:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4940:                         }
1.1008    raeburn  4941:                     }
1.353     www      4942:                 }
                   4943:             }
                   4944:         }
                   4945:     }
                   4946:     return %returnhash;
                   4947: }
                   4948: 
1.1055    raeburn  4949: sub courselastaccess {
                   4950:     my ($cdom,$cnum,$hostidref) = @_;
                   4951:     my %returnhash;
                   4952:     if ($cdom && $cnum) {
                   4953:         my $chome = &homeserver($cnum,$cdom);
                   4954:         if ($chome ne 'no_host') {
                   4955:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4956:             &extract_lastaccess(\%returnhash,$rep);
                   4957:         }
                   4958:     } else {
                   4959:         if (!$cdom) { $cdom=''; }
                   4960:         my %libserv = &all_library();
                   4961:         foreach my $tryserver (keys(%libserv)) {
                   4962:             if (ref($hostidref) eq 'ARRAY') {
                   4963:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4964:             } 
                   4965:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4966:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4967:                 &extract_lastaccess(\%returnhash,$rep);
                   4968:             }
                   4969:         }
                   4970:     }
                   4971:     return %returnhash;
                   4972: }
                   4973: 
                   4974: sub extract_lastaccess {
                   4975:     my ($returnhash,$rep) = @_;
                   4976:     if (ref($returnhash) eq 'HASH') {
                   4977:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4978:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4979:                  $rep eq '') {
                   4980:             my @pairs=split(/\&/,$rep);
                   4981:             foreach my $item (@pairs) {
                   4982:                 my ($key,$value)=split(/\=/,$item,2);
                   4983:                 $key = &unescape($key);
                   4984:                 next if ($key =~ /^error: 2 /);
                   4985:                 $returnhash->{$key} = &thaw_unescape($value);
                   4986:             }
                   4987:         }
                   4988:     }
                   4989:     return;
                   4990: }
                   4991: 
1.658     raeburn  4992: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4993: 
                   4994: sub dcmailput {
1.685     raeburn  4995:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4996:     my $status = &Apache::lonnet::critical(
1.740     www      4997:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4998:        &escape($message),$server);
1.662     raeburn  4999:     return $status;
                   5000: }
                   5001: 
1.658     raeburn  5002: sub dcmaildump {
                   5003:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5004:     my %returnhash=();
1.846     albertel 5005: 
                   5006:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5007:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5008:                                                          &escape($enddate).':';
                   5009: 	my @esc_senders=map { &escape($_)} @$senders;
                   5010: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5011: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5012:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5013:             if (($key) && ($value)) {
                   5014:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5015:             }
                   5016:         }
                   5017:     }
                   5018:     return %returnhash;
                   5019: }
1.662     raeburn  5020: # ---------------------------------------------------------- Domain roles
                   5021: 
                   5022: sub get_domain_roles {
                   5023:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5024:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5025:         $startdate = '.';
                   5026:     }
1.1018    raeburn  5027:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5028:         $enddate = '.';
                   5029:     }
1.922     raeburn  5030:     my $rolelist;
                   5031:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  5032:         $rolelist = join('&',@{$roles});
1.922     raeburn  5033:     }
1.662     raeburn  5034:     my %personnel = ();
1.841     albertel 5035: 
                   5036:     my %servers = &get_servers($dom,'library');
                   5037:     foreach my $tryserver (keys(%servers)) {
                   5038: 	%{$personnel{$tryserver}}=();
                   5039: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5040: 					    &escape($startdate).':'.
                   5041: 					    &escape($enddate).':'.
                   5042: 					    &escape($rolelist), $tryserver))) {
                   5043: 	    my ($key,$value) = split(/\=/,$line,2);
                   5044: 	    if (($key) && ($value)) {
                   5045: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5046: 	    }
                   5047: 	}
1.662     raeburn  5048:     }
                   5049:     return %personnel;
                   5050: }
1.658     raeburn  5051: 
1.1332    raeburn  5052: sub get_active_domroles {
                   5053:     my ($dom,$roles) = @_;
                   5054:     return () unless (ref($roles) eq 'ARRAY');
                   5055:     my $now = time;
                   5056:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5057:     my %domroles;
                   5058:     foreach my $server (keys(%dompersonnel)) {
                   5059:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5060:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5061:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5062:         }
                   5063:     }
                   5064:     return %domroles;
                   5065: }
                   5066: 
1.1057    www      5067: # ----------------------------------------------------------- Interval timing 
1.149     www      5068: 
1.1153    www      5069: {
                   5070: # Caches needed for speedup of navmaps
                   5071: # We don't want to cache this for very long at all (5 seconds at most)
                   5072: # 
                   5073: # The user for whom we cache
                   5074: my $cachedkey='';
                   5075: # The cached times for this user
                   5076: my %cachedtimes=();
                   5077: # When this was last done
1.1282    raeburn  5078: my $cachedtime='';
1.1153    www      5079: 
                   5080: sub load_all_first_access {
1.1308    raeburn  5081:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5082:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  5083:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5084:         (!$ignorecache)) {
1.1154    raeburn  5085:         return;
                   5086:     }
                   5087:     $cachedtime=time;
                   5088:     $cachedkey=$uname.':'.$udom;
                   5089:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5090: }
                   5091: 
1.504     albertel 5092: sub get_first_access {
1.1308    raeburn  5093:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5094:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5095:     if ($argsymb) { $symb=$argsymb; }
                   5096:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5097:     if ($argmap) { $map = $argmap; }
1.926     albertel 5098:     if ($type eq 'course') {
                   5099: 	$res='course';
                   5100:     } elsif ($type eq 'map') {
1.588     albertel 5101: 	$res=&symbread($map);
                   5102:     } else {
                   5103: 	$res=$symb;
                   5104:     }
1.1308    raeburn  5105:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5106:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5107: }
                   5108: 
                   5109: sub set_first_access {
1.1162    raeburn  5110:     my ($type,$interval)=@_;
1.790     albertel 5111:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5112:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5113:     if ($type eq 'course') {
                   5114: 	$res='course';
                   5115:     } elsif ($type eq 'map') {
1.588     albertel 5116: 	$res=&symbread($map);
                   5117:     } else {
                   5118: 	$res=$symb;
                   5119:     }
1.1153    www      5120:     $cachedkey='';
1.1162    raeburn  5121:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 5122:     if (!$firstaccess) {
1.1162    raeburn  5123:         my $start = time;
                   5124: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5125:                           $udom,$uname);
                   5126:         if ($putres eq 'ok') {
                   5127:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5128:                  $udom,$uname); 
                   5129:             &appenv(
                   5130:                      {
                   5131:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5132:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5133:                      }
                   5134:                   );
                   5135:         }
                   5136:         return $putres;
1.505     albertel 5137:     }
                   5138:     return 'already_set';
1.504     albertel 5139: }
1.1153    www      5140: }
1.1282    raeburn  5141: 
1.110     www      5142: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5143: 
                   5144: sub expirespread {
                   5145:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5146:     my $cid=$env{'request.course.id'}; 
1.110     www      5147:     if ($cid) {
                   5148:        my $now=time;
                   5149:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5150:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5151:                             $env{'course.'.$cid.'.num'}.
1.110     www      5152: 	        	    ':nohist_expirationdates:'.
                   5153:                             &escape($key).'='.$now,
1.620     albertel 5154:                             $env{'course.'.$cid.'.home'})
1.110     www      5155:     }
                   5156:     return 'ok';
1.14      www      5157: }
                   5158: 
1.109     www      5159: # ----------------------------------------------------- Devalidate Spreadsheets
                   5160: 
                   5161: sub devalidate {
1.325     www      5162:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5163:     my $cid=$env{'request.course.id'}; 
1.109     www      5164:     if ($cid) {
1.391     matthew  5165:         # delete the stored spreadsheets for
                   5166:         # - the student level sheet of this user in course's homespace
                   5167:         # - the assessment level sheet for this resource 
                   5168:         #   for this user in user's homespace
1.553     albertel 5169: 	# - current conditional state info
1.325     www      5170: 	my $key=$uname.':'.$udom.':';
1.109     www      5171:         my $status=
1.299     matthew  5172: 	    &del('nohist_calculatedsheets',
1.391     matthew  5173: 		 [$key.'studentcalc:'],
1.620     albertel 5174: 		 $env{'course.'.$cid.'.domain'},
                   5175: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5176: 		.' '.
                   5177: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5178: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5179:         unless ($status eq 'ok ok') {
                   5180:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5181:                     $uname.' at '.$udom.' for '.
1.109     www      5182: 		    $symb.': '.$status);
1.133     albertel 5183:         }
1.553     albertel 5184: 	&delenv('user.state.'.$cid);
1.109     www      5185:     }
                   5186: }
                   5187: 
1.265     albertel 5188: sub get_scalar {
                   5189:     my ($string,$end) = @_;
                   5190:     my $value;
                   5191:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5192: 	$value = $1;
                   5193:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5194: 	$value = $1;
                   5195:     }
                   5196:     return &unescape($value);
                   5197: }
                   5198: 
                   5199: sub array2str {
                   5200:   my (@array) = @_;
                   5201:   my $result=&arrayref2str(\@array);
                   5202:   $result=~s/^__ARRAY_REF__//;
                   5203:   $result=~s/__END_ARRAY_REF__$//;
                   5204:   return $result;
                   5205: }
                   5206: 
1.204     albertel 5207: sub arrayref2str {
                   5208:   my ($arrayref) = @_;
1.265     albertel 5209:   my $result='__ARRAY_REF__';
1.204     albertel 5210:   foreach my $elem (@$arrayref) {
1.265     albertel 5211:     if(ref($elem) eq 'ARRAY') {
                   5212:       $result.=&arrayref2str($elem).'&';
                   5213:     } elsif(ref($elem) eq 'HASH') {
                   5214:       $result.=&hashref2str($elem).'&';
                   5215:     } elsif(ref($elem)) {
                   5216:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5217:     } else {
                   5218:       $result.=&escape($elem).'&';
                   5219:     }
                   5220:   }
                   5221:   $result=~s/\&$//;
1.265     albertel 5222:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5223:   return $result;
                   5224: }
                   5225: 
1.168     albertel 5226: sub hash2str {
1.204     albertel 5227:   my (%hash) = @_;
                   5228:   my $result=&hashref2str(\%hash);
1.265     albertel 5229:   $result=~s/^__HASH_REF__//;
                   5230:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5231:   return $result;
                   5232: }
                   5233: 
                   5234: sub hashref2str {
                   5235:   my ($hashref)=@_;
1.265     albertel 5236:   my $result='__HASH_REF__';
1.800     albertel 5237:   foreach my $key (sort(keys(%$hashref))) {
                   5238:     if (ref($key) eq 'ARRAY') {
                   5239:       $result.=&arrayref2str($key).'=';
                   5240:     } elsif (ref($key) eq 'HASH') {
                   5241:       $result.=&hashref2str($key).'=';
                   5242:     } elsif (ref($key)) {
1.265     albertel 5243:       $result.='=';
1.800     albertel 5244:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5245:     } else {
1.1132    raeburn  5246: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5247:     }
                   5248: 
1.800     albertel 5249:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5250:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5251:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5252:       $result.=&hashref2str($hashref->{$key}).'&';
                   5253:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5254:        $result.='&';
1.800     albertel 5255:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5256:     } else {
1.800     albertel 5257:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5258:     }
                   5259:   }
1.168     albertel 5260:   $result=~s/\&$//;
1.265     albertel 5261:   $result .= '__END_HASH_REF__';
1.168     albertel 5262:   return $result;
                   5263: }
                   5264: 
                   5265: sub str2hash {
1.265     albertel 5266:     my ($string)=@_;
                   5267:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5268:     return %$hash;
                   5269: }
                   5270: 
                   5271: sub str2hashref {
1.168     albertel 5272:   my ($string) = @_;
1.265     albertel 5273: 
                   5274:   my %hash;
                   5275: 
                   5276:   if($string !~ /^__HASH_REF__/) {
                   5277:       if (! ($string eq '' || !defined($string))) {
                   5278: 	  $hash{'error'}='Not hash reference';
                   5279:       }
                   5280:       return (\%hash, $string);
                   5281:   }
                   5282: 
                   5283:   $string =~ s/^__HASH_REF__//;
                   5284: 
                   5285:   while($string !~ /^__END_HASH_REF__/) {
                   5286:       #key
                   5287:       my $key='';
                   5288:       if($string =~ /^__HASH_REF__/) {
                   5289:           ($key, $string)=&str2hashref($string);
                   5290:           if(defined($key->{'error'})) {
                   5291:               $hash{'error'}='Bad data';
                   5292:               return (\%hash, $string);
                   5293:           }
                   5294:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5295:           ($key, $string)=&str2arrayref($string);
                   5296:           if($key->[0] eq 'Array reference error') {
                   5297:               $hash{'error'}='Bad data';
                   5298:               return (\%hash, $string);
                   5299:           }
                   5300:       } else {
                   5301:           $string =~ s/^(.*?)=//;
1.267     albertel 5302: 	  $key=&unescape($1);
1.265     albertel 5303:       }
                   5304:       $string =~ s/^=//;
                   5305: 
                   5306:       #value
                   5307:       my $value='';
                   5308:       if($string =~ /^__HASH_REF__/) {
                   5309:           ($value, $string)=&str2hashref($string);
                   5310:           if(defined($value->{'error'})) {
                   5311:               $hash{'error'}='Bad data';
                   5312:               return (\%hash, $string);
                   5313:           }
                   5314:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5315:           ($value, $string)=&str2arrayref($string);
                   5316:           if($value->[0] eq 'Array reference error') {
                   5317:               $hash{'error'}='Bad data';
                   5318:               return (\%hash, $string);
                   5319:           }
                   5320:       } else {
                   5321: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5322:       }
                   5323:       $string =~ s/^&//;
                   5324: 
                   5325:       $hash{$key}=$value;
1.204     albertel 5326:   }
1.265     albertel 5327: 
                   5328:   $string =~ s/^__END_HASH_REF__//;
                   5329: 
                   5330:   return (\%hash, $string);
1.204     albertel 5331: }
                   5332: 
                   5333: sub str2array {
1.265     albertel 5334:     my ($string)=@_;
                   5335:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5336:     return @$array;
                   5337: }
                   5338: 
                   5339: sub str2arrayref {
1.204     albertel 5340:   my ($string) = @_;
1.265     albertel 5341:   my @array;
                   5342: 
                   5343:   if($string !~ /^__ARRAY_REF__/) {
                   5344:       if (! ($string eq '' || !defined($string))) {
                   5345: 	  $array[0]='Array reference error';
                   5346:       }
                   5347:       return (\@array, $string);
                   5348:   }
                   5349: 
                   5350:   $string =~ s/^__ARRAY_REF__//;
                   5351: 
                   5352:   while($string !~ /^__END_ARRAY_REF__/) {
                   5353:       my $value='';
                   5354:       if($string =~ /^__HASH_REF__/) {
                   5355:           ($value, $string)=&str2hashref($string);
                   5356:           if(defined($value->{'error'})) {
                   5357:               $array[0] ='Array reference error';
                   5358:               return (\@array, $string);
                   5359:           }
                   5360:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5361:           ($value, $string)=&str2arrayref($string);
                   5362:           if($value->[0] eq 'Array reference error') {
                   5363:               $array[0] ='Array reference error';
                   5364:               return (\@array, $string);
                   5365:           }
                   5366:       } else {
                   5367: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5368:       }
                   5369:       $string =~ s/^&//;
                   5370: 
                   5371:       push(@array, $value);
1.191     harris41 5372:   }
1.265     albertel 5373: 
                   5374:   $string =~ s/^__END_ARRAY_REF__//;
                   5375: 
                   5376:   return (\@array, $string);
1.168     albertel 5377: }
                   5378: 
1.167     albertel 5379: # -------------------------------------------------------------------Temp Store
                   5380: 
1.168     albertel 5381: sub tmpreset {
                   5382:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5383:   if (!$symb) {
                   5384:     $symb=&symbread();
1.620     albertel 5385:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5386:   }
                   5387:   $symb=escape($symb);
                   5388: 
1.620     albertel 5389:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5390:   $namespace=~s/\//\_/g;
                   5391:   $namespace=~s/\W//g;
                   5392: 
1.620     albertel 5393:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5394:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5395:   if ($domain eq 'public' && $stuname eq 'public') {
                   5396:       $stuname=$ENV{'REMOTE_ADDR'};
                   5397:   }
1.1117    foxr     5398:   my $path=LONCAPA::tempdir();
1.168     albertel 5399:   my %hash;
                   5400:   if (tie(%hash,'GDBM_File',
                   5401: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5402: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5403:     foreach my $key (keys(%hash)) {
1.180     albertel 5404:       if ($key=~ /:$symb/) {
1.168     albertel 5405: 	delete($hash{$key});
                   5406:       }
                   5407:     }
                   5408:   }
                   5409: }
                   5410: 
1.167     albertel 5411: sub tmpstore {
1.168     albertel 5412:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5413: 
                   5414:   if (!$symb) {
                   5415:     $symb=&symbread();
1.620     albertel 5416:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5417:   }
                   5418:   $symb=escape($symb);
                   5419: 
                   5420:   if (!$namespace) {
                   5421:     # I don't think we would ever want to store this for a course.
                   5422:     # it seems this will only be used if we don't have a course.
1.620     albertel 5423:     #$namespace=$env{'request.course.id'};
1.168     albertel 5424:     #if (!$namespace) {
1.620     albertel 5425:       $namespace=$env{'request.state'};
1.168     albertel 5426:     #}
                   5427:   }
                   5428:   $namespace=~s/\//\_/g;
                   5429:   $namespace=~s/\W//g;
1.620     albertel 5430:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5431:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5432:   if ($domain eq 'public' && $stuname eq 'public') {
                   5433:       $stuname=$ENV{'REMOTE_ADDR'};
                   5434:   }
1.168     albertel 5435:   my $now=time;
                   5436:   my %hash;
1.1117    foxr     5437:   my $path=LONCAPA::tempdir();
1.168     albertel 5438:   if (tie(%hash,'GDBM_File',
                   5439: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5440: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5441:     $hash{"version:$symb"}++;
                   5442:     my $version=$hash{"version:$symb"};
                   5443:     my $allkeys=''; 
                   5444:     foreach my $key (keys(%$storehash)) {
                   5445:       $allkeys.=$key.':';
1.591     albertel 5446:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5447:     }
                   5448:     $hash{"$version:$symb:timestamp"}=$now;
                   5449:     $allkeys.='timestamp';
                   5450:     $hash{"$version:keys:$symb"}=$allkeys;
                   5451:     if (untie(%hash)) {
                   5452:       return 'ok';
                   5453:     } else {
                   5454:       return "error:$!";
                   5455:     }
                   5456:   } else {
                   5457:     return "error:$!";
                   5458:   }
                   5459: }
1.167     albertel 5460: 
1.168     albertel 5461: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5462: 
1.168     albertel 5463: sub tmprestore {
                   5464:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5465: 
1.168     albertel 5466:   if (!$symb) {
                   5467:     $symb=&symbread();
1.620     albertel 5468:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5469:   }
                   5470:   $symb=escape($symb);
                   5471: 
1.620     albertel 5472:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5473: 
1.620     albertel 5474:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5475:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5476:   if ($domain eq 'public' && $stuname eq 'public') {
                   5477:       $stuname=$ENV{'REMOTE_ADDR'};
                   5478:   }
1.168     albertel 5479:   my %returnhash;
                   5480:   $namespace=~s/\//\_/g;
                   5481:   $namespace=~s/\W//g;
                   5482:   my %hash;
1.1117    foxr     5483:   my $path=LONCAPA::tempdir();
1.168     albertel 5484:   if (tie(%hash,'GDBM_File',
                   5485: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5486: 	  &GDBM_READER(),0640)) {
1.168     albertel 5487:     my $version=$hash{"version:$symb"};
                   5488:     $returnhash{'version'}=$version;
                   5489:     my $scope;
                   5490:     for ($scope=1;$scope<=$version;$scope++) {
                   5491:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5492:       my @keys=split(/:/,$vkeys);
                   5493:       my $key;
                   5494:       $returnhash{"$scope:keys"}=$vkeys;
                   5495:       foreach $key (@keys) {
1.591     albertel 5496: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5497: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5498:       }
                   5499:     }
1.168     albertel 5500:     if (!(untie(%hash))) {
                   5501:       return "error:$!";
                   5502:     }
                   5503:   } else {
                   5504:     return "error:$!";
                   5505:   }
                   5506:   return %returnhash;
1.167     albertel 5507: }
                   5508: 
1.9       www      5509: # ----------------------------------------------------------------------- Store
                   5510: 
                   5511: sub store {
1.1269    raeburn  5512:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5513:     my $home='';
                   5514: 
1.168     albertel 5515:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5516: 
1.213     www      5517:     $symb=&symbclean($symb);
1.122     albertel 5518:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5519: 
1.620     albertel 5520:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5521:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5522: 
                   5523:     &devalidate($symb,$stuname,$domain);
1.109     www      5524: 
                   5525:     $symb=escape($symb);
1.187     www      5526:     if (!$namespace) { 
1.620     albertel 5527:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5528:           return ''; 
                   5529:        } 
                   5530:     }
1.620     albertel 5531:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5532: 
                   5533:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5534:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5535: 
1.12      www      5536:     my $namevalue='';
1.800     albertel 5537:     foreach my $key (keys(%$storehash)) {
                   5538:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5539:     }
1.12      www      5540:     $namevalue=~s/\&$//;
1.187     www      5541:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  5542:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5543: }
                   5544: 
1.47      www      5545: # -------------------------------------------------------------- Critical Store
                   5546: 
                   5547: sub cstore {
1.1269    raeburn  5548:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5549:     my $home='';
                   5550: 
1.168     albertel 5551:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5552: 
1.213     www      5553:     $symb=&symbclean($symb);
1.122     albertel 5554:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5555: 
1.620     albertel 5556:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5557:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5558: 
                   5559:     &devalidate($symb,$stuname,$domain);
1.109     www      5560: 
                   5561:     $symb=escape($symb);
1.187     www      5562:     if (!$namespace) { 
1.620     albertel 5563:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5564:           return ''; 
                   5565:        } 
                   5566:     }
1.620     albertel 5567:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5568: 
                   5569:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5570:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5571: 
1.47      www      5572:     my $namevalue='';
1.800     albertel 5573:     foreach my $key (keys(%$storehash)) {
                   5574:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5575:     }
1.47      www      5576:     $namevalue=~s/\&$//;
1.187     www      5577:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5578:     return critical
1.1269    raeburn  5579:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5580: }
                   5581: 
1.9       www      5582: # --------------------------------------------------------------------- Restore
                   5583: 
                   5584: sub restore {
1.124     www      5585:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5586:     my $home='';
                   5587: 
1.168     albertel 5588:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5589: 
1.122     albertel 5590:     if (!$symb) {
1.1224    raeburn  5591:         return if ($namespace eq 'courserequests');
                   5592:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5593:     } else {
1.1224    raeburn  5594:         unless ($namespace eq 'courserequests') {
                   5595:             $symb=&escape(&symbclean($symb));
                   5596:         }
1.122     albertel 5597:     }
1.188     www      5598:     if (!$namespace) { 
1.620     albertel 5599:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5600:           return ''; 
                   5601:        } 
                   5602:     }
1.620     albertel 5603:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5604:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5605:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5606:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5607: 
1.12      www      5608:     my %returnhash=();
1.800     albertel 5609:     foreach my $line (split(/\&/,$answer)) {
                   5610: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5611:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5612:     }
1.75      www      5613:     my $version;
                   5614:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5615:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5616:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5617:        }
1.75      www      5618:     }
1.13      www      5619:     return %returnhash;
1.34      www      5620: }
                   5621: 
                   5622: # ---------------------------------------------------------- Course Description
1.1118    foxr     5623: #
                   5624: #  
1.34      www      5625: 
                   5626: sub coursedescription {
1.731     albertel 5627:     my ($courseid,$args)=@_;
1.34      www      5628:     $courseid=~s/^\///;
1.49      www      5629:     $courseid=~s/\_/\//g;
1.34      www      5630:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5631:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5632:     my $normalid=$cdomain.'_'.$cnum;
                   5633:     # need to always cache even if we get errors otherwise we keep 
                   5634:     # trying and trying and trying to get the course description.
                   5635:     my %envhash=();
                   5636:     my %returnhash=();
1.731     albertel 5637:     
                   5638:     my $expiretime=600;
                   5639:     if ($env{'request.course.id'} eq $normalid) {
                   5640: 	$expiretime=120;
                   5641:     }
                   5642: 
                   5643:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5644:     if (!$args->{'freshen_cache'}
                   5645: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5646: 	foreach my $key (keys(%env)) {
                   5647: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5648: 	    my ($setting) = $1;
                   5649: 	    $returnhash{$setting} = $env{$key};
                   5650: 	}
                   5651: 	return %returnhash;
                   5652:     }
                   5653: 
1.1118    foxr     5654:     # get the data again
                   5655: 
1.731     albertel 5656:     if (!$args->{'one_time'}) {
                   5657: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5658:     }
1.811     albertel 5659: 
1.34      www      5660:     if ($chome ne 'no_host') {
1.302     albertel 5661:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5662:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5663: 	   my $username = $env{'user.name'}; # Defult username
                   5664: 	   if(defined $args->{'user'}) {
                   5665: 	       $username = $args->{'user'};
                   5666: 	   }
1.129     albertel 5667:            $returnhash{'home'}= $chome;
                   5668: 	   $returnhash{'domain'} = $cdomain;
                   5669: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5670:            if (!defined($returnhash{'type'})) {
                   5671:                $returnhash{'type'} = 'Course';
                   5672:            }
1.130     albertel 5673:            while (my ($name,$value) = each %returnhash) {
1.53      www      5674:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5675:            }
1.270     www      5676:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5677:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5678: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5679:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5680:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5681:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5682:        }
                   5683:     }
1.731     albertel 5684:     if (!$args->{'one_time'}) {
1.949     raeburn  5685: 	&appenv(\%envhash);
1.731     albertel 5686:     }
1.302     albertel 5687:     return %returnhash;
1.461     www      5688: }
                   5689: 
1.1080    raeburn  5690: sub update_released_required {
                   5691:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5692:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5693:         $cid = $env{'request.course.id'};
                   5694:         $cdom = $env{'course.'.$cid.'.domain'};
                   5695:         $cnum = $env{'course.'.$cid.'.num'};
                   5696:         $chome = $env{'course.'.$cid.'.home'};
                   5697:     }
                   5698:     if ($needsrelease) {
                   5699:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5700:         my $needsupdate;
                   5701:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5702:             $needsupdate = 1;
                   5703:         } else {
                   5704:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5705:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5706:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5707:                 $needsupdate = 1;
                   5708:             }
                   5709:         }
                   5710:         if ($needsupdate) {
                   5711:             my %needshash = (
                   5712:                              'internal.releaserequired' => $needsrelease,
                   5713:                             );
                   5714:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5715:             if ($putresult eq 'ok') {
                   5716:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5717:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5718:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5719:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5720:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5721:                 }
                   5722:             }
                   5723:         }
                   5724:     }
                   5725:     return;
                   5726: }
                   5727: 
1.461     www      5728: # -------------------------------------------------See if a user is privileged
                   5729: 
                   5730: sub privileged {
1.1219    raeburn  5731:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5732:     my $now = time;
1.1219    raeburn  5733:     my $roles;
                   5734:     if (ref($possroles) eq 'ARRAY') {
                   5735:         $roles = $possroles; 
                   5736:     } else {
                   5737:         $roles = ['dc','su'];
                   5738:     }
                   5739:     if (ref($possdomains) eq 'ARRAY') {
                   5740:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5741:         foreach my $dom (@{$possdomains}) {
                   5742:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5743:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5744:                 foreach my $role (@{$roles}) {
                   5745:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5746:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5747:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5748:                             return 1 unless (($end && $end < $now) ||
                   5749:                                              ($start && $start > $now));
                   5750:                         }
                   5751:                     }
                   5752:                 }
                   5753:             }
                   5754:         }
                   5755:     } else {
                   5756:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5757:         my $now = time;
1.1170    droeschl 5758: 
1.1275    musolffc 5759:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5760:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5761:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5762:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5763:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5764:             }
1.1219    raeburn  5765:         }
                   5766:     }
                   5767:     return 0;
                   5768: }
1.1170    droeschl 5769: 
1.1219    raeburn  5770: sub privileged_by_domain {
                   5771:     my ($domains,$roles) = @_;
                   5772:     my %privileged = ();
                   5773:     my $cachetime = 60*60*24;
                   5774:     my $now = time;
                   5775:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5776:         return %privileged;
                   5777:     }
                   5778:     foreach my $dom (@{$domains}) {
                   5779:         next if (ref($privileged{$dom}) eq 'HASH');
                   5780:         my $needroles;
                   5781:         foreach my $role (@{$roles}) {
                   5782:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5783:             if (defined($cached)) {
                   5784:                 if (ref($result) eq 'HASH') {
                   5785:                     $privileged{$dom}{$role} = $result;
                   5786:                 }
                   5787:             } else {
                   5788:                 $needroles = 1;
                   5789:             }
                   5790:         }
                   5791:         if ($needroles) {
                   5792:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5793:             $privileged{$dom} = {};
                   5794:             foreach my $server (keys(%dompersonnel)) {
                   5795:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5796:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5797:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5798:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5799:                         next if ($end && $end < $now);
                   5800:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5801:                             $dompersonnel{$server}{$item};
                   5802:                     }
                   5803:                 }
                   5804:             }
                   5805:             if (ref($privileged{$dom}) eq 'HASH') {
                   5806:                 foreach my $role (@{$roles}) {
                   5807:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5808:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5809:                     } else {
                   5810:                         my %hash = ();
                   5811:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5812:                     }
                   5813:                 }
                   5814:             }
                   5815:         }
                   5816:     }
                   5817:     return %privileged;
1.9       www      5818: }
1.1       albertel 5819: 
1.103     harris41 5820: # -------------------------------------------------------- Get user privileges
1.11      www      5821: 
                   5822: sub rolesinit {
1.1169    droeschl 5823:     my ($domain, $username) = @_;
                   5824:     my %userroles = ('user.login.time' => time);
                   5825:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5826: 
                   5827:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5828:     # also, blocking can be triggered by an activating timer
                   5829:     # it's saved in the user's %env.
                   5830:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5831:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5832:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5833:         %timerintchk, %timerintenv);
                   5834: 
1.1162    raeburn  5835:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5836:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5837:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5838:     }
1.1169    droeschl 5839: 
1.1162    raeburn  5840:     foreach my $key (keys(%timerinterval)) {
                   5841:         my ($cid,$rest) = split(/\0/,$key);
                   5842:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5843:     }
1.1169    droeschl 5844: 
1.11      www      5845:     my %allroles=();
1.1162    raeburn  5846:     my %allgroups=();
1.11      www      5847: 
1.1274    raeburn  5848:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5849:         my $role = $rolesdump{$area};
                   5850:         $area =~ s/\_\w\w$//;
                   5851: 
                   5852:         my ($trole, $tend, $tstart, $group_privs);
                   5853: 
                   5854:         if ($role =~ /^cr/) {
                   5855:         # Custom role, defined by a user 
                   5856:         # e.g., user.role.cr/msu/smith/mynewrole
                   5857:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5858:                 $trole = $1;
                   5859:                 ($tend, $tstart) = split('_', $2);
                   5860:             } else {
                   5861:                 $trole = $role;
                   5862:             }
                   5863:         } elsif ($role =~ m|^gr/|) {
                   5864:         # Role of member in a group, defined within a course/community
                   5865:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5866:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5867:             next if $tstart eq '-1';
                   5868:             ($trole, $group_privs) = split(/\//, $trole);
                   5869:             $group_privs = &unescape($group_privs);
                   5870:         } else {
                   5871:         # Just a normal role, defined in roles.tab
                   5872:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5873:         }
                   5874: 
                   5875:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5876:                  $username);
                   5877:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5878: 
                   5879:         # role expired or not available yet?
                   5880:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5881:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5882: 
                   5883:         next if $area eq '' or $trole eq '';
                   5884: 
                   5885:         my $spec = "$trole.$area";
                   5886:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5887: 
                   5888:         if ($trole =~ /^cr\//) {
                   5889:         # Custom role, defined by a user
                   5890:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5891:         } elsif ($trole eq 'gr') {
                   5892:         # Role of a member in a group, defined within a course/community
                   5893:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5894:             next;
                   5895:         } else {
                   5896:         # Normal role, defined in roles.tab
                   5897:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5898:         }
                   5899: 
                   5900:         my $cid = $tdomain.'_'.$trest;
                   5901:         unless ($firstaccchk{$cid}) {
                   5902:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5903:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5904:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5905:                         $coursetimerstarts{$cid}{$item}; 
                   5906:                 }
                   5907:             }
                   5908:             $firstaccchk{$cid} = 1;
                   5909:         }
                   5910:         unless ($timerintchk{$cid}) {
                   5911:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5912:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5913:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5914:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5915:                 }
1.12      www      5916:             }
1.1169    droeschl 5917:             $timerintchk{$cid} = 1;
1.191     harris41 5918:         }
1.11      www      5919:     }
1.1169    droeschl 5920: 
1.1341    raeburn  5921:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   5922:                                                           \%allroles, \%allgroups);
1.1169    droeschl 5923:     $env{'user.adv'} = $userroles{'user.adv'};
1.1341    raeburn  5924:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 5925: 
1.1162    raeburn  5926:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5927: }
                   5928: 
1.567     raeburn  5929: sub set_arearole {
1.1215    raeburn  5930:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5931:     unless ($nolog) {
1.567     raeburn  5932: # log the associated role with the area
1.1215    raeburn  5933:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5934:     }
1.743     albertel 5935:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5936: }
                   5937: 
                   5938: sub custom_roleprivs {
                   5939:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5940:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  5941:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5942:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5943:         my ($rdummy,$roledef)=
                   5944:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5945:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5946:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5947:             if (defined($syspriv)) {
1.1043    raeburn  5948:                 if ($trest =~ /^$match_community$/) {
                   5949:                     $syspriv =~ s/bre\&S//; 
                   5950:                 }
1.567     raeburn  5951:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5952:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5953:             }
                   5954:             if ($tdomain ne '') {
                   5955:                 if (defined($dompriv)) {
                   5956:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5957:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5958:                 }
                   5959:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  5960:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   5961:                         my $rolename = $1;
                   5962:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   5963:                     }
1.567     raeburn  5964:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5965:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5966:                 }
                   5967:             }
                   5968:         }
                   5969:     }
                   5970: }
                   5971: 
1.1332    raeburn  5972: sub course_adhocrole_privs {
                   5973:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   5974:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   5975:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   5976:         my (%currprivs,%storeprivs);
                   5977:         foreach my $item (split(/:/,$coursepriv)) {
                   5978:             my ($priv,$restrict) = split(/\&/,$item);
                   5979:             $currprivs{$priv} = $restrict;
                   5980:         }
                   5981:         my (%possadd,%possremove,%full);
                   5982:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   5983:             my ($priv,$restrict)=split(/\&/,$item);
                   5984:             $full{$priv} = $restrict;
                   5985:         }
                   5986:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   5987:              next if ($item eq '');
                   5988:              my ($rule,$rest) = split(/=/,$item);
                   5989:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   5990:              foreach my $priv (split(/:/,$rest)) {
                   5991:                  if ($priv ne '') {
                   5992:                      if ($rule eq 'off') {
                   5993:                          $possremove{$priv} = 1;
                   5994:                      } else {
                   5995:                          $possadd{$priv} = 1;
                   5996:                      }
                   5997:                  }
                   5998:              }
                   5999:          }
                   6000:          foreach my $priv (sort(keys(%full))) {
                   6001:              if (exists($currprivs{$priv})) {
                   6002:                  unless (exists($possremove{$priv})) {
                   6003:                      $storeprivs{$priv} = $currprivs{$priv};
                   6004:                  }
                   6005:              } elsif (exists($possadd{$priv})) {
                   6006:                  $storeprivs{$priv} = $full{$priv};
                   6007:              }
                   6008:          }
                   6009:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6010:      }
                   6011:      return $coursepriv;
                   6012: }
                   6013: 
1.678     raeburn  6014: sub group_roleprivs {
                   6015:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6016:     my $access = 1;
                   6017:     my $now = time;
                   6018:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6019:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6020:     if ($access) {
1.811     albertel 6021:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6022:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6023:     }
                   6024: }
1.567     raeburn  6025: 
                   6026: sub standard_roleprivs {
                   6027:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6028:     if (defined($pr{$trole.':s'})) {
                   6029:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6030:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6031:     }
                   6032:     if ($tdomain ne '') {
                   6033:         if (defined($pr{$trole.':d'})) {
                   6034:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6035:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6036:         }
                   6037:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6038:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6039:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6040:         }
                   6041:     }
                   6042: }
                   6043: 
                   6044: sub set_userprivs {
1.1064    raeburn  6045:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6046:     my $author=0;
                   6047:     my $adv=0;
1.1341    raeburn  6048:     my $rar=0;
1.678     raeburn  6049:     my %grouproles = ();
                   6050:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6051:         my @groupkeys; 
1.1000    raeburn  6052:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6053:             push(@groupkeys,$role);
                   6054:         }
                   6055:         if (ref($groups_roles) eq 'HASH') {
                   6056:             foreach my $key (keys(%{$groups_roles})) {
                   6057:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6058:                     push(@groupkeys,$key);
                   6059:                 }
                   6060:             }
                   6061:         }
                   6062:         if (@groupkeys > 0) {
                   6063:             foreach my $role (@groupkeys) {
                   6064:                 my ($trole,$area,$sec,$extendedarea);
                   6065:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6066:                     $trole = $1;
                   6067:                     $area = $2;
                   6068:                     $sec = $3;
                   6069:                     $extendedarea = $area.$sec;
                   6070:                     if (exists($$allgroups{$area})) {
                   6071:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6072:                             my $spec = $trole.'.'.$extendedarea;
                   6073:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6074:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6075:                         }
1.678     raeburn  6076:                     }
                   6077:                 }
                   6078:             }
                   6079:         }
                   6080:     }
1.800     albertel 6081:     foreach my $group (keys(%grouproles)) {
                   6082:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6083:     }
1.800     albertel 6084:     foreach my $role (keys(%{$allroles})) {
                   6085:         my %thesepriv;
1.941     raeburn  6086:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6087:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6088:             if ($item ne '') {
                   6089:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6090:                 if ($restrictions eq '') {
                   6091:                     $thesepriv{$privilege}='F';
                   6092:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6093:                     $thesepriv{$privilege}.=$restrictions;
                   6094:                 }
                   6095:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341    raeburn  6096:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6097:             }
                   6098:         }
                   6099:         my $thesestr='';
1.1104    raeburn  6100:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6101: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6102: 	}
                   6103:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6104:     }
1.1341    raeburn  6105:     return ($author,$adv,$rar);
1.567     raeburn  6106: }
                   6107: 
1.994     raeburn  6108: sub role_status {
1.1104    raeburn  6109:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6110:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  6111:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6112:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6113:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  6114:             $$where = '/'.$two;
1.994     raeburn  6115:             $$trolecode=$$role.'.'.$$where;
                   6116:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6117:             $$tstatus='is';
1.1104    raeburn  6118:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6119:                 $$tstatus='future';
1.1034    raeburn  6120:                 if ($$tstart<$now) {
                   6121:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6122:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6123:                             my (%allroles,%allgroups,$group_privs,
                   6124:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6125:                             my %userroles = (
                   6126:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6127:                             );
1.1064    raeburn  6128:                             @rolecodes = ('cm'); 
1.1002    raeburn  6129:                             my $spec=$$role.'.'.$$where;
                   6130:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6131:                             if ($$role =~ /^cr\//) {
                   6132:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6133:                                 push(@rolecodes,'cr');
1.1002    raeburn  6134:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6135:                                 push(@rolecodes,$$role);
1.1002    raeburn  6136:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6137:                                                     $env{'user.name'});
1.1064    raeburn  6138:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6139:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6140:                                 $group_privs = &unescape($group_privs);
                   6141:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6142:                                 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  6143:                                 &get_groups_roles($tdomain,$trest,
                   6144:                                                   \%course_roles,\@rolecodes,
                   6145:                                                   \%groups_roles);
1.1002    raeburn  6146:                             } else {
1.1064    raeburn  6147:                                 push(@rolecodes,$$role);
1.1002    raeburn  6148:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6149:                             }
1.1341    raeburn  6150:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6151:                                                                    \%groups_roles);
1.1064    raeburn  6152:                             &appenv(\%userroles,\@rolecodes);
1.1342    raeburn  6153:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6154:                         }
                   6155:                     }
1.1034    raeburn  6156:                     $$tstatus = 'is';
1.1002    raeburn  6157:                 }
1.994     raeburn  6158:             }
                   6159:             if ($$tend) {
1.1104    raeburn  6160:                 if ($$tend<$update) {
1.994     raeburn  6161:                     $$tstatus='expired';
                   6162:                 } elsif ($$tend<$now) {
                   6163:                     $$tstatus='will_not';
                   6164:                 }
                   6165:             }
                   6166:         }
                   6167:     }
                   6168: }
                   6169: 
1.1104    raeburn  6170: sub get_groups_roles {
                   6171:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6172:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6173:                   (ref($rolecodes) eq 'ARRAY') && 
                   6174:                   (ref($groups_roles) eq 'HASH')); 
                   6175:     if (keys(%{$cdom_courseroles}) > 0) {
                   6176:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6177:         if ($cdom ne '' && $cnum ne '') {
                   6178:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6179:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6180:                     my $crsrole = $1;
                   6181:                     my $crssec = $2;
                   6182:                     if ($crsrole =~ /^cr/) {
                   6183:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6184:                             push(@{$rolecodes},'cr');
                   6185:                         }
                   6186:                     } else {
                   6187:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6188:                             push(@{$rolecodes},$crsrole);
                   6189:                         }
                   6190:                     }
                   6191:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6192:                     if ($crssec ne '') {
                   6193:                         $rolekey .= "/$crssec";
                   6194:                     }
                   6195:                     $rolekey .= './';
                   6196:                     $groups_roles->{$rolekey} = $rolecodes;
                   6197:                 }
                   6198:             }
                   6199:         }
                   6200:     }
                   6201:     return;
                   6202: }
                   6203: 
                   6204: sub delete_env_groupprivs {
                   6205:     my ($where,$courseroles,$possroles) = @_;
                   6206:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6207:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6208:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6209:         %{$courseroles->{$udom}} =
                   6210:             &get_my_roles('','','userroles',['active'],
                   6211:                           $possroles,[$udom],1);
                   6212:     }
                   6213:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6214:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6215:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6216:             my $area = '/'.$cdom.'/'.$cnum;
                   6217:             my $privkey = "user.priv.$crsrole.$area";
                   6218:             if ($crssec ne '') {
                   6219:                 $privkey .= '/'.$crssec;
                   6220:             }
                   6221:             $privkey .= ".$area/$group";
                   6222:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6223:         }
                   6224:     }
                   6225:     return;
                   6226: }
                   6227: 
1.994     raeburn  6228: sub check_adhoc_privs {
1.1329    raeburn  6229:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6230:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  6231:     if ($sec) {
                   6232:         $cckey .= '/'.$sec;
                   6233:     } 
1.1185    raeburn  6234:     my $setprivs;
1.994     raeburn  6235:     if ($env{$cckey}) {
                   6236:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6237:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6238:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  6239:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6240:             $setprivs = 1;
1.994     raeburn  6241:         }
                   6242:     } else {
1.1330    raeburn  6243:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6244:         $setprivs = 1;
1.994     raeburn  6245:     }
1.1185    raeburn  6246:     return $setprivs;
1.994     raeburn  6247: }
                   6248: 
                   6249: sub set_adhoc_privileges {
1.1326    raeburn  6250: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  6251:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6252:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  6253:     if ($sec ne '') {
                   6254:         $area .= '/'.$sec;
                   6255:     }
1.994     raeburn  6256:     my $spec = $role.'.'.$area;
                   6257:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  6258:                                   $env{'user.name'},1);
1.1326    raeburn  6259:     my %rolehash = ();
1.1332    raeburn  6260:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6261:         my $rolename = $1;
1.1326    raeburn  6262:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  6263:         my %domdef = &get_domain_defaults($dcdom);
                   6264:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6265:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6266:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6267:             }
                   6268:         }
1.1326    raeburn  6269:     } else {
                   6270:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6271:     }
1.1341    raeburn  6272:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6273:     &appenv(\%userroles,[$role,'cm']);
1.1342    raeburn  6274:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6275:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6276:         &appenv( {'request.role'        => $spec,
                   6277:                   'request.role.domain' => $dcdom,
1.1332    raeburn  6278:                   'request.course.sec'  => $sec,
1.1088    raeburn  6279:                  }
                   6280:                );
                   6281:         my $tadv=0;
                   6282:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6283:         &appenv({'request.role.adv'    => $tadv});
                   6284:     }
1.994     raeburn  6285: }
                   6286: 
1.12      www      6287: # --------------------------------------------------------------- get interface
                   6288: 
                   6289: sub get {
1.131     albertel 6290:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6291:    my $items='';
1.800     albertel 6292:    foreach my $item (@$storearr) {
                   6293:        $items.=&escape($item).'&';
1.191     harris41 6294:    }
1.12      www      6295:    $items=~s/\&$//;
1.620     albertel 6296:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6297:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6298:    my $uhome=&homeserver($uname,$udomain);
                   6299: 
1.133     albertel 6300:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6301:    my @pairs=split(/\&/,$rep);
1.273     albertel 6302:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6303:      return @pairs;
                   6304:    }
1.15      www      6305:    my %returnhash=();
1.42      www      6306:    my $i=0;
1.800     albertel 6307:    foreach my $item (@$storearr) {
                   6308:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6309:       $i++;
1.191     harris41 6310:    }
1.15      www      6311:    return %returnhash;
1.27      www      6312: }
                   6313: 
                   6314: # --------------------------------------------------------------- del interface
                   6315: 
                   6316: sub del {
1.133     albertel 6317:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6318:    my $items='';
1.800     albertel 6319:    foreach my $item (@$storearr) {
                   6320:        $items.=&escape($item).'&';
1.191     harris41 6321:    }
1.984     neumanie 6322: 
1.27      www      6323:    $items=~s/\&$//;
1.620     albertel 6324:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6325:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6326:    my $uhome=&homeserver($uname,$udomain);
                   6327:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6328: }
                   6329: 
                   6330: # -------------------------------------------------------------- dump interface
                   6331: 
1.1180    droeschl 6332: sub unserialize {
                   6333:     my ($rep, $escapedkeys) = @_;
                   6334: 
                   6335:     return {} if $rep =~ /^error/;
                   6336: 
                   6337:     my %returnhash=();
1.1252    raeburn  6338: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 6339: 	    my ($key, $value) = split(/=/, $item, 2);
                   6340: 	    $key = unescape($key) unless $escapedkeys;
                   6341: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  6342: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 6343: 	}
                   6344:     #return %returnhash;
                   6345:     return \%returnhash;
                   6346: }        
                   6347: 
                   6348: # see Lond::dump_with_regexp
                   6349: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6350: sub dump {
1.1180    droeschl 6351:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6352:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6353:     if (!$uname) { $uname=$env{'user.name'}; }
                   6354:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6355: 
1.1266    raeburn  6356:     if ($regexp) {
                   6357:         $regexp=&escape($regexp);
                   6358:     } else {
                   6359:         $regexp='.';
                   6360:     }
1.1180    droeschl 6361:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   6362:         # user is hosted on this machine
1.1266    raeburn  6363:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  6364:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 6365:         return %{unserialize($reply, $escapedkeys)};
                   6366:     }
1.1166    raeburn  6367:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6368:     my @pairs=split(/\&/,$rep);
                   6369:     my %returnhash=();
1.1098    foxr     6370:     if (!($rep =~ /^error/ )) {
                   6371: 	foreach my $item (@pairs) {
                   6372: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 6373:         $key = unescape($key) unless $escapedkeys;
                   6374:         #$key = &unescape($key);
1.1098    foxr     6375: 	    next if ($key =~ /^error: 2 /);
                   6376: 	    $returnhash{$key}=&thaw_unescape($value);
                   6377: 	}
1.755     albertel 6378:     }
                   6379:     return %returnhash;
1.407     www      6380: }
                   6381: 
1.1098    foxr     6382: 
1.717     albertel 6383: # --------------------------------------------------------- dumpstore interface
                   6384: 
                   6385: sub dumpstore {
                   6386:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 6387:    # same as dump but keys must be escaped. They may contain colon separated
                   6388:    # lists of values that may themself contain colons (e.g. symbs).
                   6389:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6390: }
                   6391: 
1.407     www      6392: # -------------------------------------------------------------- keys interface
                   6393: 
                   6394: sub getkeys {
                   6395:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6396:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6397:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6398:    my $uhome=&homeserver($uname,$udomain);
                   6399:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6400:    my @keyarray=();
1.800     albertel 6401:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6402:       next if ($key =~ /^error: 2 /);
1.800     albertel 6403:       push(@keyarray,&unescape($key));
1.407     www      6404:    }
                   6405:    return @keyarray;
1.318     matthew  6406: }
                   6407: 
1.319     matthew  6408: # --------------------------------------------------------------- currentdump
                   6409: sub currentdump {
1.328     matthew  6410:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6411:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6412:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6413:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6414:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 6415:    my $rep;
                   6416: 
                   6417:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6418:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   6419:                    $courseid)));
                   6420:    } else {
                   6421:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6422:    }
                   6423: 
1.318     matthew  6424:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6425:    #
1.318     matthew  6426:    my %returnhash=();
1.319     matthew  6427:    #
1.1343    raeburn  6428:    if ($rep eq 'unknown_cmd') {
1.319     matthew  6429:        # an old lond will not know currentdump
                   6430:        # Do a dump and make it look like a currentdump
1.822     albertel 6431:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6432:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6433:        my %hash = @tmp;
                   6434:        @tmp=();
1.424     matthew  6435:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6436:    } else {
                   6437:        my @pairs=split(/\&/,$rep);
1.800     albertel 6438:        foreach my $pair (@pairs) {
                   6439:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6440:            my ($symb,$param) = split(/:/,$key);
                   6441:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6442:                                                         &thaw_unescape($value);
1.319     matthew  6443:        }
1.191     harris41 6444:    }
1.12      www      6445:    return %returnhash;
1.424     matthew  6446: }
                   6447: 
                   6448: sub convert_dump_to_currentdump{
                   6449:     my %hash = %{shift()};
                   6450:     my %returnhash;
                   6451:     # Code ripped from lond, essentially.  The only difference
                   6452:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6453:     # we might run in to problems with parameter names =~ /^v\./
                   6454:     while (my ($key,$value) = each(%hash)) {
                   6455:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6456: 	$symb  = &unescape($symb);
                   6457: 	$param = &unescape($param);
1.424     matthew  6458:         next if ($v eq 'version' || $symb eq 'keys');
                   6459:         next if (exists($returnhash{$symb}) &&
                   6460:                  exists($returnhash{$symb}->{$param}) &&
                   6461:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6462:         $returnhash{$symb}->{$param}=$value;
                   6463:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6464:     }
                   6465:     #
                   6466:     # Remove all of the keys in the hashes which keep track of
                   6467:     # the version of the parameter.
                   6468:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6469:         # use a foreach because we are going to delete from the hash.
                   6470:         foreach my $key (keys(%$param_hash)) {
                   6471:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6472:         }
                   6473:     }
                   6474:     return \%returnhash;
1.12      www      6475: }
                   6476: 
1.627     albertel 6477: # ------------------------------------------------------ critical inc interface
                   6478: 
                   6479: sub cinc {
                   6480:     return &inc(@_,'critical');
                   6481: }
                   6482: 
1.449     matthew  6483: # --------------------------------------------------------------- inc interface
                   6484: 
                   6485: sub inc {
1.627     albertel 6486:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6487:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6488:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6489:     my $uhome=&homeserver($uname,$udomain);
                   6490:     my $items='';
                   6491:     if (! ref($store)) {
                   6492:         # got a single value, so use that instead
                   6493:         $items = &escape($store).'=&';
                   6494:     } elsif (ref($store) eq 'SCALAR') {
                   6495:         $items = &escape($$store).'=&';        
                   6496:     } elsif (ref($store) eq 'ARRAY') {
                   6497:         $items = join('=&',map {&escape($_);} @{$store});
                   6498:     } elsif (ref($store) eq 'HASH') {
                   6499:         while (my($key,$value) = each(%{$store})) {
                   6500:             $items.= &escape($key).'='.&escape($value).'&';
                   6501:         }
                   6502:     }
                   6503:     $items=~s/\&$//;
1.627     albertel 6504:     if ($critical) {
                   6505: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6506:     } else {
                   6507: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6508:     }
1.449     matthew  6509: }
                   6510: 
1.12      www      6511: # --------------------------------------------------------------- put interface
                   6512: 
                   6513: sub put {
1.134     albertel 6514:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6515:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6516:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6517:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6518:    my $items='';
1.800     albertel 6519:    foreach my $item (keys(%$storehash)) {
                   6520:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6521:    }
1.12      www      6522:    $items=~s/\&$//;
1.134     albertel 6523:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6524: }
                   6525: 
1.631     albertel 6526: # ------------------------------------------------------------ newput interface
                   6527: 
                   6528: sub newput {
                   6529:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6530:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6531:    if (!$uname) { $uname=$env{'user.name'}; }
                   6532:    my $uhome=&homeserver($uname,$udomain);
                   6533:    my $items='';
                   6534:    foreach my $key (keys(%$storehash)) {
                   6535:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6536:    }
                   6537:    $items=~s/\&$//;
                   6538:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6539: }
                   6540: 
                   6541: # ---------------------------------------------------------  putstore interface
                   6542: 
1.524     raeburn  6543: sub putstore {
1.1269    raeburn  6544:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6545:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6546:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6547:    my $uhome=&homeserver($uname,$udomain);
                   6548:    my $items='';
1.715     albertel 6549:    foreach my $key (keys(%$storehash)) {
                   6550:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6551:    }
1.715     albertel 6552:    $items=~s/\&$//;
1.716     albertel 6553:    my $esc_symb=&escape($symb);
                   6554:    my $esc_v=&escape($version);
1.715     albertel 6555:    my $reply =
1.716     albertel 6556:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6557: 	      $uhome);
1.1269    raeburn  6558:    if (($tolog) && ($reply eq 'ok')) {
                   6559:        my $namevalue='';
                   6560:        foreach my $key (keys(%{$storehash})) {
                   6561:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6562:        }
                   6563:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6564:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6565:                      '&version='.$esc_v.
                   6566:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6567:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6568:    }
1.715     albertel 6569:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6570:        # gfall back to way things use to be done
1.715     albertel 6571:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6572: 			    $uname);
1.524     raeburn  6573:    }
1.715     albertel 6574:    return $reply;
                   6575: }
                   6576: 
                   6577: sub old_putstore {
1.716     albertel 6578:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6579:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6580:     if (!$uname) { $uname=$env{'user.name'}; }
                   6581:     my $uhome=&homeserver($uname,$udomain);
                   6582:     my %newstorehash;
1.800     albertel 6583:     foreach my $item (keys(%$storehash)) {
                   6584: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6585: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6586:     }
                   6587:     my $items='';
                   6588:     my %allitems = ();
1.800     albertel 6589:     foreach my $item (keys(%newstorehash)) {
                   6590: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6591: 	    my $key = $1.':keys:'.$2;
                   6592: 	    $allitems{$key} .= $3.':';
                   6593: 	}
1.800     albertel 6594: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6595:     }
1.800     albertel 6596:     foreach my $item (keys(%allitems)) {
                   6597: 	$allitems{$item} =~ s/\:$//;
                   6598: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6599:     }
                   6600:     $items=~s/\&$//;
                   6601:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6602: }
                   6603: 
1.47      www      6604: # ------------------------------------------------------ critical put interface
                   6605: 
                   6606: sub cput {
1.134     albertel 6607:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6608:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6609:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6610:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6611:    my $items='';
1.800     albertel 6612:    foreach my $item (keys(%$storehash)) {
                   6613:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6614:    }
1.47      www      6615:    $items=~s/\&$//;
1.134     albertel 6616:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6617: }
                   6618: 
                   6619: # -------------------------------------------------------------- eget interface
                   6620: 
                   6621: sub eget {
1.133     albertel 6622:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6623:    my $items='';
1.800     albertel 6624:    foreach my $item (@$storearr) {
                   6625:        $items.=&escape($item).'&';
1.191     harris41 6626:    }
1.12      www      6627:    $items=~s/\&$//;
1.620     albertel 6628:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6629:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6630:    my $uhome=&homeserver($uname,$udomain);
                   6631:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6632:    my @pairs=split(/\&/,$rep);
                   6633:    my %returnhash=();
1.42      www      6634:    my $i=0;
1.800     albertel 6635:    foreach my $item (@$storearr) {
                   6636:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6637:       $i++;
1.191     harris41 6638:    }
1.12      www      6639:    return %returnhash;
                   6640: }
                   6641: 
1.667     albertel 6642: # ------------------------------------------------------------ tmpput interface
                   6643: sub tmpput {
1.802     raeburn  6644:     my ($storehash,$server,$context)=@_;
1.667     albertel 6645:     my $items='';
1.800     albertel 6646:     foreach my $item (keys(%$storehash)) {
                   6647: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6648:     }
                   6649:     $items=~s/\&$//;
1.802     raeburn  6650:     if (defined($context)) {
                   6651:         $items .= ':'.&escape($context);
                   6652:     }
1.667     albertel 6653:     return &reply("tmpput:$items",$server);
                   6654: }
                   6655: 
                   6656: # ------------------------------------------------------------ tmpget interface
                   6657: sub tmpget {
1.688     albertel 6658:     my ($token,$server)=@_;
                   6659:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6660:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6661:     my %returnhash;
1.1328    raeburn  6662:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6663:         return %returnhash;
                   6664:     }
1.667     albertel 6665:     foreach my $item (split(/\&/,$rep)) {
                   6666: 	my ($key,$value)=split(/=/,$item);
                   6667: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6668:     }
                   6669:     return %returnhash;
                   6670: }
                   6671: 
1.1113    raeburn  6672: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6673: sub tmpdel {
                   6674:     my ($token,$server)=@_;
                   6675:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6676:     return &reply("tmpdel:$token",$server);
                   6677: }
                   6678: 
1.1198    raeburn  6679: # ------------------------------------------------------------ get_timebased_id 
                   6680: 
                   6681: sub get_timebased_id {
                   6682:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6683:         $maxtries) = @_;
                   6684:     my ($newid,$error,$dellock);
                   6685:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   6686:         return ('','ok','invalid call to get suffix');
                   6687:     }
                   6688: 
                   6689: # set defaults for any optional args for which values were not supplied
                   6690:     if ($who eq '') {
                   6691:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6692:     }
                   6693:     if (!$locktries) {
                   6694:         $locktries = 3;
                   6695:     }
                   6696:     if (!$maxtries) {
                   6697:         $maxtries = 10;
                   6698:     }
                   6699:     
                   6700:     if (($cdom eq '') || ($cnum eq '')) {
                   6701:         if ($env{'request.course.id'}) {
                   6702:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6703:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6704:         }
                   6705:         if (($cdom eq '') || ($cnum eq '')) {
                   6706:             return ('','ok','call to get suffix not in course context');
                   6707:         }
                   6708:     }
                   6709: 
                   6710: # construct locking item
                   6711:     my $lockhash = {
                   6712:                       $prefix."\0".'locked_'.$keyid => $who,
                   6713:                    };
                   6714:     my $tries = 0;
                   6715: 
                   6716: # attempt to get lock on nohist_$namespace file
                   6717:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6718:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6719:         $tries ++;
                   6720:         sleep 1;
                   6721:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6722:     }
                   6723: 
                   6724: # attempt to get unique identifier, based on current timestamp
                   6725:     if ($gotlock eq 'ok') {
                   6726:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6727:         my $id = time;
                   6728:         $newid = $id;
1.1268    raeburn  6729:         if ($idtype eq 'addcode') {
                   6730:             $newid .= &sixnum_code();
                   6731:         }
1.1198    raeburn  6732:         my $idtries = 0;
                   6733:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6734:             if ($idtype eq 'concat') {
                   6735:                 $newid = $id.$idtries;
1.1268    raeburn  6736:             } elsif ($idtype eq 'addcode') {
                   6737:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6738:             } else {
                   6739:                 $newid ++;
                   6740:             }
                   6741:             $idtries ++;
                   6742:         }
                   6743:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6744:             my %new_item =  (
                   6745:                               $prefix."\0".$newid => $who,
                   6746:                             );
                   6747:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6748:                                                  $cdom,$cnum);
                   6749:             if ($putresult ne 'ok') {
                   6750:                 undef($newid);
                   6751:                 $error = 'error saving new item: '.$putresult;
                   6752:             }
                   6753:         } else {
1.1268    raeburn  6754:              undef($newid);
1.1198    raeburn  6755:              $error = ('error: no unique suffix available for the new item ');
                   6756:         }
                   6757: #  remove lock
                   6758:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6759:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6760:     } else {
                   6761:         $error = "error: could not obtain lockfile\n";
                   6762:         $dellock = 'ok';
1.1276    raeburn  6763:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6764:             $dellock = 'nolock';
                   6765:         }
1.1198    raeburn  6766:     }
                   6767:     return ($newid,$dellock,$error);
                   6768: }
                   6769: 
1.1268    raeburn  6770: sub sixnum_code {
                   6771:     my $code;
                   6772:     for (0..6) {
                   6773:         $code .= int( rand(9) );
                   6774:     }
                   6775:     return $code;
                   6776: }
                   6777: 
1.765     albertel 6778: # -------------------------------------------------- portfolio access checking
                   6779: 
                   6780: sub portfolio_access {
1.1270    raeburn  6781:     my ($requrl,$clientip) = @_;
1.765     albertel 6782:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  6783:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6784:     if ($result) {
                   6785:         my %setters;
                   6786:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6787:             my ($startblock,$endblock) =
                   6788:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6789:             if ($startblock && $endblock) {
                   6790:                 return 'B';
                   6791:             }
                   6792:         } else {
                   6793:             my ($startblock,$endblock) =
                   6794:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6795:             if ($startblock && $endblock) {
                   6796:                 return 'B';
                   6797:             }
                   6798:         }
                   6799:     }
1.765     albertel 6800:     if ($result eq 'ok') {
1.766     albertel 6801:        return 'F';
1.765     albertel 6802:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6803:        return 'A';
1.765     albertel 6804:     }
1.766     albertel 6805:     return '';
1.765     albertel 6806: }
                   6807: 
                   6808: sub get_portfolio_access {
1.1270    raeburn  6809:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6810: 
                   6811:     if (!ref($access_hash)) {
                   6812: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6813: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6814: 						   $file_name);
                   6815: 	$access_hash = $access_controls{$file_name};
                   6816:     }
                   6817: 
1.1270    raeburn  6818:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6819:     my $now = time;
                   6820:     if (ref($access_hash) eq 'HASH') {
                   6821:         foreach my $key (keys(%{$access_hash})) {
                   6822:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6823:             if ($start > $now) {
                   6824:                 next;
                   6825:             }
                   6826:             if ($end && $end<$now) {
                   6827:                 next;
                   6828:             }
                   6829:             if ($scope eq 'public') {
                   6830:                 $public = $key;
                   6831:                 last;
                   6832:             } elsif ($scope eq 'guest') {
                   6833:                 $guest = $key;
                   6834:             } elsif ($scope eq 'domains') {
                   6835:                 push(@domains,$key);
                   6836:             } elsif ($scope eq 'users') {
                   6837:                 push(@users,$key);
                   6838:             } elsif ($scope eq 'course') {
                   6839:                 push(@courses,$key);
                   6840:             } elsif ($scope eq 'group') {
                   6841:                 push(@groups,$key);
1.1270    raeburn  6842:             } elsif ($scope eq 'ip') {
                   6843:                 push(@ips,$key);
1.765     albertel 6844:             }
                   6845:         }
                   6846:         if ($public) {
                   6847:             return 'ok';
1.1270    raeburn  6848:         } elsif (@ips > 0) {
                   6849:             my $allowed;
                   6850:             foreach my $ipkey (@ips) {
                   6851:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6852:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6853:                         $allowed = 1;
                   6854:                         last; 
                   6855:                     }
                   6856:                 }
                   6857:             }
                   6858:             if ($allowed) {
                   6859:                 return 'ok';
                   6860:             }
1.765     albertel 6861:         }
                   6862:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6863:             if ($guest) {
                   6864:                 return $guest;
                   6865:             }
                   6866:         } else {
                   6867:             if (@domains > 0) {
                   6868:                 foreach my $domkey (@domains) {
                   6869:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6870:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6871:                             return 'ok';
                   6872:                         }
                   6873:                     }
                   6874:                 }
                   6875:             }
                   6876:             if (@users > 0) {
                   6877:                 foreach my $userkey (@users) {
1.865     raeburn  6878:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6879:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6880:                             if (ref($item) eq 'HASH') {
                   6881:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6882:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6883:                                     return 'ok';
                   6884:                                 }
                   6885:                             }
                   6886:                         }
                   6887:                     } 
1.765     albertel 6888:                 }
                   6889:             }
                   6890:             my %roleshash;
                   6891:             my @courses_and_groups = @courses;
                   6892:             push(@courses_and_groups,@groups); 
                   6893:             if (@courses_and_groups > 0) {
                   6894:                 my (%allgroups,%allroles); 
                   6895:                 my ($start,$end,$role,$sec,$group);
                   6896:                 foreach my $envkey (%env) {
1.1060    raeburn  6897:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6898:                         my $cid = $2.'_'.$3; 
                   6899:                         if ($1 eq 'gr') {
                   6900:                             $group = $4;
                   6901:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6902:                         } else {
                   6903:                             if ($4 eq '') {
                   6904:                                 $sec = 'none';
                   6905:                             } else {
                   6906:                                 $sec = $4;
                   6907:                             }
                   6908:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6909:                         }
1.811     albertel 6910:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6911:                         my $cid = $2.'_'.$3;
                   6912:                         if ($4 eq '') {
                   6913:                             $sec = 'none';
                   6914:                         } else {
                   6915:                             $sec = $4;
                   6916:                         }
                   6917:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6918:                     }
                   6919:                 }
                   6920:                 if (keys(%allroles) == 0) {
                   6921:                     return;
                   6922:                 }
                   6923:                 foreach my $key (@courses_and_groups) {
                   6924:                     my %content = %{$$access_hash{$key}};
                   6925:                     my $cnum = $content{'number'};
                   6926:                     my $cdom = $content{'domain'};
                   6927:                     my $cid = $cdom.'_'.$cnum;
                   6928:                     if (!exists($allroles{$cid})) {
                   6929:                         next;
                   6930:                     }    
                   6931:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6932:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6933:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6934:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6935:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6936:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6937:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6938:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6939:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6940:                                         if (grep/^all$/,@sections) {
                   6941:                                             return 'ok';
                   6942:                                         } else {
                   6943:                                             if (grep/^$sec$/,@sections) {
                   6944:                                                 return 'ok';
                   6945:                                             }
                   6946:                                         }
                   6947:                                     }
                   6948:                                 }
                   6949:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6950:                                     if (grep/^none$/,@groups) {
                   6951:                                         return 'ok';
                   6952:                                     }
                   6953:                                 } else {
                   6954:                                     if (grep/^all$/,@groups) {
                   6955:                                         return 'ok';
                   6956:                                     } 
                   6957:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6958:                                         if (grep/^$group$/,@groups) {
                   6959:                                             return 'ok';
                   6960:                                         }
                   6961:                                     }
                   6962:                                 } 
                   6963:                             }
                   6964:                         }
                   6965:                     }
                   6966:                 }
                   6967:             }
                   6968:             if ($guest) {
                   6969:                 return $guest;
                   6970:             }
                   6971:         }
                   6972:     }
                   6973:     return;
                   6974: }
                   6975: 
                   6976: sub course_group_datechecker {
                   6977:     my ($dates,$now,$status) = @_;
                   6978:     my ($start,$end) = split(/\./,$dates);
                   6979:     if (!$start && !$end) {
                   6980:         return 'ok';
                   6981:     }
                   6982:     if (grep/^active$/,@{$status}) {
                   6983:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6984:             return 'ok';
                   6985:         }
                   6986:     }
                   6987:     if (grep/^previous$/,@{$status}) {
                   6988:         if ($end > $now ) {
                   6989:             return 'ok';
                   6990:         }
                   6991:     }
                   6992:     if (grep/^future$/,@{$status}) {
                   6993:         if ($start > $now) {
                   6994:             return 'ok';
                   6995:         }
                   6996:     }
                   6997:     return; 
                   6998: }
                   6999: 
                   7000: sub parse_portfolio_url {
                   7001:     my ($url) = @_;
                   7002: 
                   7003:     my ($type,$udom,$unum,$group,$file_name);
                   7004:     
1.823     albertel 7005:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7006: 	$type = 1;
                   7007:         $udom = $1;
                   7008:         $unum = $2;
                   7009:         $file_name = $3;
1.823     albertel 7010:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7011: 	$type = 2;
                   7012:         $udom = $1;
                   7013:         $unum = $2;
                   7014:         $group = $3;
                   7015:         $file_name = $3.'/'.$4;
                   7016:     }
                   7017:     if (wantarray) {
                   7018: 	return ($type,$udom,$unum,$file_name,$group);
                   7019:     }
                   7020:     return $type;
                   7021: }
                   7022: 
                   7023: sub is_portfolio_url {
                   7024:     my ($url) = @_;
                   7025:     return scalar(&parse_portfolio_url($url));
                   7026: }
                   7027: 
1.798     raeburn  7028: sub is_portfolio_file {
                   7029:     my ($file) = @_;
1.820     raeburn  7030:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7031:         return 1;
                   7032:     }
                   7033:     return;
                   7034: }
                   7035: 
1.976     raeburn  7036: sub usertools_access {
1.1084    raeburn  7037:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7038:     my ($access,%tools);
                   7039:     if ($context eq '') {
                   7040:         $context = 'tools';
                   7041:     }
                   7042:     if ($context eq 'requestcourses') {
                   7043:         %tools = (
                   7044:                       official   => 1,
                   7045:                       unofficial => 1,
1.1006    raeburn  7046:                       community  => 1,
1.1246    raeburn  7047:                       textbook   => 1,
1.1305    raeburn  7048:                       placement  => 1,
1.985     raeburn  7049:                  );
1.1183    raeburn  7050:     } elsif ($context eq 'requestauthor') {
                   7051:         %tools = (
                   7052:                       requestauthor => 1,
                   7053:                  );
1.985     raeburn  7054:     } else {
                   7055:         %tools = (
                   7056:                       aboutme   => 1,
                   7057:                       blog      => 1,
1.1177    raeburn  7058:                       webdav    => 1,
1.985     raeburn  7059:                       portfolio => 1,
                   7060:                  );
                   7061:     }
1.976     raeburn  7062:     return if (!defined($tools{$tool}));
                   7063: 
1.1242    raeburn  7064:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7065:         $udom = $env{'user.domain'};
                   7066:         $uname = $env{'user.name'};
                   7067:     }
                   7068: 
1.978     raeburn  7069:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7070:         if ($action ne 'reload') {
1.985     raeburn  7071:             if ($context eq 'requestcourses') {
                   7072:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  7073:             } elsif ($context eq 'requestauthor') {
                   7074:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7075:             } else {
                   7076:                 return $env{'environment.availabletools.'.$tool};
                   7077:             }
                   7078:         }
1.976     raeburn  7079:     }
                   7080: 
1.1183    raeburn  7081:     my ($toolstatus,$inststatus,$envkey);
                   7082:     if ($context eq 'requestauthor') {
                   7083:         $envkey = $context; 
                   7084:     } else {
                   7085:         $envkey = $context.'.'.$tool;
                   7086:     }
1.976     raeburn  7087: 
1.985     raeburn  7088:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7089:          ($action ne 'reload')) {
1.1183    raeburn  7090:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7091:         $inststatus = $env{'environment.inststatus'};
                   7092:     } else {
1.1084    raeburn  7093:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  7094:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7095:             $inststatus = $userenvref->{'inststatus'};
                   7096:         } else {
1.1183    raeburn  7097:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7098:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7099:             $inststatus = $userenv{'inststatus'};
                   7100:         }
1.976     raeburn  7101:     }
                   7102: 
                   7103:     if ($toolstatus ne '') {
                   7104:         if ($toolstatus) {
                   7105:             $access = 1;
                   7106:         } else {
                   7107:             $access = 0;
                   7108:         }
                   7109:         return $access;
                   7110:     }
                   7111: 
1.1084    raeburn  7112:     my ($is_adv,%domdef);
                   7113:     if (ref($is_advref) eq 'HASH') {
                   7114:         $is_adv = $is_advref->{'is_adv'};
                   7115:     } else {
                   7116:         $is_adv = &is_advanced_user($udom,$uname);
                   7117:     }
                   7118:     if (ref($domdefref) eq 'HASH') {
                   7119:         %domdef = %{$domdefref};
                   7120:     } else {
                   7121:         %domdef = &get_domain_defaults($udom);
                   7122:     }
1.976     raeburn  7123:     if (ref($domdef{$tool}) eq 'HASH') {
                   7124:         if ($is_adv) {
                   7125:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7126:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7127:                     $access = 1;
                   7128:                 } else {
                   7129:                     $access = 0;
                   7130:                 }
                   7131:                 return $access;
                   7132:             }
                   7133:         }
                   7134:         if ($inststatus ne '') {
                   7135:             my ($hasaccess,$hasnoaccess);
                   7136:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7137:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7138:                     if ($domdef{$tool}{$affiliation}) {
                   7139:                         $hasaccess = 1;
                   7140:                     } else {
                   7141:                         $hasnoaccess = 1;
                   7142:                     }
                   7143:                 }
                   7144:             }
                   7145:             if ($hasaccess || $hasnoaccess) {
                   7146:                 if ($hasaccess) {
                   7147:                     $access = 1;
                   7148:                 } elsif ($hasnoaccess) {
                   7149:                     $access = 0; 
                   7150:                 }
                   7151:                 return $access;
                   7152:             }
                   7153:         } else {
                   7154:             if ($domdef{$tool}{'default'} ne '') {
                   7155:                 if ($domdef{$tool}{'default'}) {
                   7156:                     $access = 1;
                   7157:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7158:                     $access = 0;
                   7159:                 }
                   7160:                 return $access;
                   7161:             }
                   7162:         }
                   7163:     } else {
1.1177    raeburn  7164:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7165:             $access = 1;
                   7166:         } else {
                   7167:             $access = 0;
                   7168:         }
1.976     raeburn  7169:         return $access;
                   7170:     }
                   7171: }
                   7172: 
1.1050    raeburn  7173: sub is_course_owner {
                   7174:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7175:     if (($udom eq '') || ($uname eq '')) {
                   7176:         $udom = $env{'user.domain'};
                   7177:         $uname = $env{'user.name'};
                   7178:     }
                   7179:     unless (($udom eq '') || ($uname eq '')) {
                   7180:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7181:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7182:                 return 1;
                   7183:             } else {
                   7184:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7185:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7186:                     return 1;
                   7187:                 }
                   7188:             }
                   7189:         }
                   7190:     }
                   7191:     return;
                   7192: }
                   7193: 
1.976     raeburn  7194: sub is_advanced_user {
                   7195:     my ($udom,$uname) = @_;
1.1085    raeburn  7196:     if ($udom ne '' && $uname ne '') {
                   7197:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7198:             if (wantarray) {
                   7199:                 return ($env{'user.adv'},$env{'user.author'});
                   7200:             } else {
                   7201:                 return $env{'user.adv'};
                   7202:             }
1.1085    raeburn  7203:         }
                   7204:     }
1.976     raeburn  7205:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7206:     my %allroles;
1.1128    raeburn  7207:     my ($is_adv,$is_author);
1.976     raeburn  7208:     foreach my $role (keys(%roleshash)) {
                   7209:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7210:         my $area = '/'.$tdomain.'/'.$trest;
                   7211:         if ($sec ne '') {
                   7212:             $area .= '/'.$sec;
                   7213:         }
                   7214:         if (($area ne '') && ($trole ne '')) {
                   7215:             my $spec=$trole.'.'.$area;
                   7216:             if ($trole =~ /^cr\//) {
                   7217:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7218:             } elsif ($trole ne 'gr') {
                   7219:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7220:             }
1.1128    raeburn  7221:             if ($trole eq 'au') {
                   7222:                 $is_author = 1;
                   7223:             }
1.976     raeburn  7224:         }
                   7225:     }
                   7226:     foreach my $role (keys(%allroles)) {
                   7227:         last if ($is_adv);
                   7228:         foreach my $item (split(/:/,$allroles{$role})) {
                   7229:             if ($item ne '') {
                   7230:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7231:                 if ($privilege eq 'adv') {
                   7232:                     $is_adv = 1;
                   7233:                     last;
                   7234:                 }
                   7235:             }
                   7236:         }
                   7237:     }
1.1128    raeburn  7238:     if (wantarray) {
                   7239:         return ($is_adv,$is_author);
                   7240:     }
1.976     raeburn  7241:     return $is_adv;
                   7242: }
1.798     raeburn  7243: 
1.1035    raeburn  7244: sub check_can_request {
1.1036    raeburn  7245:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7246:     my $canreq = 0;
                   7247:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7248:     my @options = ('approval','validate','autolimit');
                   7249:     my $optregex = join('|',@options);
                   7250:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7251:         foreach my $type (@{$types}) {
                   7252:             if (&usertools_access($env{'user.name'},
                   7253:                                   $env{'user.domain'},
                   7254:                                   $type,undef,'requestcourses')) {
                   7255:                 $canreq ++;
1.1036    raeburn  7256:                 if (ref($request_domains) eq 'HASH') {
                   7257:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7258:                 }
1.1035    raeburn  7259:                 if ($dom eq $env{'user.domain'}) {
                   7260:                     $can_request->{$type} = 1;
                   7261:                 }
                   7262:             }
                   7263:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7264:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7265:                 if (@curr > 0) {
1.1036    raeburn  7266:                     foreach my $item (@curr) {
                   7267:                         if (ref($request_domains) eq 'HASH') {
                   7268:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7269:                             if ($otherdom ne '') {
                   7270:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7271:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7272:                                         push(@{$request_domains->{$type}},$otherdom);
                   7273:                                     }
                   7274:                                 } else {
                   7275:                                     push(@{$request_domains->{$type}},$otherdom);
                   7276:                                 }
                   7277:                             }
                   7278:                         }
                   7279:                     }
                   7280:                     unless($dom eq $env{'user.domain'}) {
                   7281:                         $canreq ++;
1.1035    raeburn  7282:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7283:                             $can_request->{$type} = 1;
                   7284:                         }
                   7285:                     }
                   7286:                 }
                   7287:             }
                   7288:         }
                   7289:     }
                   7290:     return $canreq;
                   7291: }
                   7292: 
1.341     www      7293: # ---------------------------------------------- Custom access rule evaluation
                   7294: 
                   7295: sub customaccess {
                   7296:     my ($priv,$uri)=@_;
1.807     albertel 7297:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7298:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7299:     $udom = &LONCAPA::clean_domain($udom);
                   7300:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7301:     my $access=0;
1.800     albertel 7302:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7303: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7304: 	if ($type eq 'user') {
                   7305: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7306: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7307: 		if ($tdom) {
                   7308: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7309: 		}
1.896     albertel 7310: 		if ($tuname) {
                   7311: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7312: 		}
                   7313: 		$access=($effect eq 'allow');
                   7314: 		last;
                   7315: 	    }
                   7316: 	} else {
                   7317: 	    if ($role) {
                   7318: 		if ($role ne $urole) { next; }
                   7319: 	    }
                   7320: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7321: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7322: 		if ($tdom) {
                   7323: 		    if ($tdom ne $udom) { next; }
                   7324: 		}
                   7325: 		if ($tcrs) {
                   7326: 		    if ($tcrs ne $ucrs) { next; }
                   7327: 		}
                   7328: 		if ($tsec) {
                   7329: 		    if ($tsec ne $usec) { next; }
                   7330: 		}
                   7331: 		$access=($effect eq 'allow');
                   7332: 		last;
                   7333: 	    }
                   7334: 	    if ($realm eq '' && $role eq '') {
                   7335: 		$access=($effect eq 'allow');
                   7336: 	    }
1.402     bowersj2 7337: 	}
1.341     www      7338:     }
                   7339:     return $access;
                   7340: }
                   7341: 
1.103     harris41 7342: # ------------------------------------------------- Check for a user privilege
1.12      www      7343: 
                   7344: sub allowed {
1.1281    raeburn  7345:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7346:     my $ver_orguri=$uri;
1.439     www      7347:     $uri=&deversion($uri);
1.152     www      7348:     my $orguri=$uri;
1.52      www      7349:     $uri=&declutter($uri);
1.809     raeburn  7350: 
1.810     raeburn  7351:     if ($priv eq 'evb') {
                   7352: # Evade communication block restrictions for specified role in a course
                   7353:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7354:             return $1;
                   7355:         } else {
                   7356:             return;
                   7357:         }
                   7358:     }
                   7359: 
1.620     albertel 7360:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7361: # Free bre access to adm and meta resources
1.1343    raeburn  7362:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
1.769     albertel 7363: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7364: 	&& ($priv eq 'bre')) {
1.14      www      7365: 	return 'F';
1.159     www      7366:     }
                   7367: 
1.545     banghart 7368: # Free bre access to user's own portfolio contents
1.714     raeburn  7369:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7370:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7371: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7372:         my %setters;
                   7373:         my ($startblock,$endblock) = 
                   7374:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7375:         if ($startblock && $endblock) {
                   7376:             return 'B';
                   7377:         } else {
                   7378:             return 'F';
                   7379:         }
1.545     banghart 7380:     }
                   7381: 
1.762     raeburn  7382: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7383:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7384:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7385:         if (exists($env{'request.course.id'})) {
                   7386:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7387:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7388:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7389:                 my $courseprivid=$env{'request.course.id'};
                   7390:                 $courseprivid=~s/\_/\//;
                   7391:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7392:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7393:                     return $1; 
1.762     raeburn  7394:                 } else {
                   7395:                     if ($env{'request.course.sec'}) {
                   7396:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7397:                     }
                   7398:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7399:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7400:                         return $2;
                   7401:                     }
1.714     raeburn  7402:                 }
                   7403:             }
                   7404:         }
                   7405:     }
                   7406: 
1.159     www      7407: # Free bre to public access
                   7408: 
                   7409:     if ($priv eq 'bre') {
1.238     www      7410:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7411: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7412:            return 'F'; 
                   7413:         }
1.238     www      7414:         if ($copyright eq 'priv') {
                   7415:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7416: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7417: 		return '';
                   7418:             }
                   7419:         }
                   7420:         if ($copyright eq 'domain') {
                   7421:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7422: 	    unless (($env{'user.domain'} eq $1) ||
                   7423:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7424: 		return '';
                   7425:             }
1.262     matthew  7426:         }
1.620     albertel 7427:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7428:             # Library role, so allow browsing of resources in this domain.
                   7429:             return 'F';
1.238     www      7430:         }
1.341     www      7431:         if ($copyright eq 'custom') {
                   7432: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7433:         }
1.14      www      7434:     }
1.264     matthew  7435:     # Domain coordinator is trying to create a course
1.620     albertel 7436:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7437:         # uri is the requested domain in this case.
                   7438:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7439:         # a role of dc for the domain in question.
1.620     albertel 7440:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7441:     }
1.29      www      7442: 
1.52      www      7443:     my $thisallowed='';
                   7444:     my $statecond=0;
                   7445:     my $courseprivid='';
                   7446: 
1.1039    raeburn  7447:     my $ownaccess;
1.1043    raeburn  7448:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7449:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7450:         if ($uri eq '') {
                   7451:             $ownaccess = 1;
                   7452:         } else {
                   7453:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7454:                 my $udom = $env{'user.domain'};
                   7455:                 my $uname = $env{'user.name'};
                   7456:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7457:                     $ownaccess = 1;
1.1040    raeburn  7458:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7459:                     unless ($uri =~ m{\.\./}) {
                   7460:                         $ownaccess = 1;
                   7461:                     }
                   7462:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7463:                     my $now = time;
                   7464:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7465:                         my $adom = $1;
                   7466:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7467:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7468:                                 my ($start,$end) = split('.',$env{$key});
                   7469:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7470:                                     $ownaccess = 1;
                   7471:                                     last;
                   7472:                                 }
                   7473:                             }
                   7474:                         }
                   7475:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7476:                         my $adom = $1;
                   7477:                         my $aname = $2;
1.1042    raeburn  7478:                         foreach my $role ('ca','aa') { 
                   7479:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7480:                                 my ($start,$end) =
                   7481:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7482:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7483:                                     $ownaccess = 1;
                   7484:                                     last;
                   7485:                                 }
1.1039    raeburn  7486:                             }
                   7487:                         }
                   7488:                     }
                   7489:                 }
                   7490:             }
                   7491:         }
                   7492:     }
                   7493: 
1.52      www      7494: # Course
                   7495: 
1.620     albertel 7496:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7497:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7498:             $thisallowed.=$1;
                   7499:         }
1.52      www      7500:     }
1.29      www      7501: 
1.52      www      7502: # Domain
                   7503: 
1.620     albertel 7504:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7505:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7506:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7507:             $thisallowed.=$1;
                   7508:         }
1.12      www      7509:     }
1.52      www      7510: 
1.1141    raeburn  7511: # User who is not author or co-author might still be able to edit
                   7512: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7513:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7514:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7515:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7516:             $thisallowed.=$1;
                   7517:         }
                   7518:     }
                   7519: 
1.52      www      7520: # Course: uri itself is a course
1.66      www      7521:     my $courseuri=$uri;
                   7522:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7523:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7524: 
1.620     albertel 7525:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7526:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7527:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7528:             $thisallowed.=$1;
                   7529:         }
1.12      www      7530:     }
1.29      www      7531: 
1.665     albertel 7532: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7533: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7534:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7535: 	$thisallowed='';
1.671     raeburn  7536:         my ($match)=&is_on_map($uri);
                   7537:         if ($match) {
                   7538:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7539:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  7540:                 my $value = $1;
                   7541:                 if ($noblockcheck) {
                   7542:                     $thisallowed.=$value;
1.1162    raeburn  7543:                 } else {
1.1281    raeburn  7544:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7545:                     if (@blockers > 0) {
                   7546:                         $thisallowed = 'B';
                   7547:                     } else {
                   7548:                         $thisallowed.=$value;
                   7549:                     }
1.1162    raeburn  7550:                 }
1.671     raeburn  7551:             }
                   7552:         } else {
1.705     albertel 7553:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7554:             if ($refuri) {
                   7555:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7556:                     $thisallowed='F';
1.671     raeburn  7557:                 } else {
                   7558:                     $refuri=&declutter($refuri);
                   7559:                     my ($match) = &is_on_map($refuri);
                   7560:                     if ($match) {
1.1281    raeburn  7561:                         if ($noblockcheck) {
                   7562:                             $thisallowed='F';
1.1162    raeburn  7563:                         } else {
1.1281    raeburn  7564:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7565:                             if (@blockers > 0) {
                   7566:                                 $thisallowed = 'B';
                   7567:                             } else {
                   7568:                                 $thisallowed='F';
                   7569:                             }
1.1162    raeburn  7570:                         }
1.671     raeburn  7571:                     }
1.669     raeburn  7572:                 }
1.671     raeburn  7573:             }
                   7574:         }
1.314     www      7575:     }
1.492     albertel 7576: 
1.766     albertel 7577:     if ($priv eq 'bre'
                   7578: 	&& $thisallowed ne 'F' 
                   7579: 	&& $thisallowed ne '2'
                   7580: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  7581: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7582:     }
1.1250    raeburn  7583: 
1.52      www      7584: # Full access at system, domain or course-wide level? Exit.
1.29      www      7585:     if ($thisallowed=~/F/) {
                   7586: 	return 'F';
                   7587:     }
                   7588: 
1.52      www      7589: # If this is generating or modifying users, exit with special codes
1.29      www      7590: 
1.643     www      7591:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7592: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7593: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7594: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7595: 	    unless ($auname) { return $thisallowed; }
                   7596: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7597: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7598: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7599: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7600: 	}
1.52      www      7601: 	return $thisallowed;
                   7602:     }
                   7603: #
1.103     harris41 7604: # Gathered so far: system, domain and course wide privileges
1.52      www      7605: #
                   7606: # Course: See if uri or referer is an individual resource that is part of 
                   7607: # the course
                   7608: 
1.620     albertel 7609:     if ($env{'request.course.id'}) {
1.232     www      7610: 
1.620     albertel 7611:        $courseprivid=$env{'request.course.id'};
                   7612:        if ($env{'request.course.sec'}) {
                   7613:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7614:        }
                   7615:        $courseprivid=~s/\_/\//;
                   7616:        my $checkreferer=1;
1.232     www      7617:        my ($match,$cond)=&is_on_map($uri);
                   7618:        if ($match) {
                   7619:            $statecond=$cond;
1.620     albertel 7620:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7621:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7622:                my $value = $1;
                   7623:                if ($priv eq 'bre') {
1.1281    raeburn  7624:                    if ($noblockcheck) {
                   7625:                        $thisallowed.=$value;
1.1162    raeburn  7626:                    } else {
1.1281    raeburn  7627:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7628:                        if (@blockers > 0) {
                   7629:                            $thisallowed = 'B';
                   7630:                        } else {
                   7631:                            $thisallowed.=$value;
                   7632:                        }
1.1162    raeburn  7633:                    }
                   7634:                } else {
                   7635:                    $thisallowed.=$value;
                   7636:                }
1.52      www      7637:                $checkreferer=0;
                   7638:            }
1.29      www      7639:        }
1.83      www      7640:        
1.148     www      7641:        if ($checkreferer) {
1.620     albertel 7642: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7643:             unless ($refuri) {
1.800     albertel 7644:                 foreach my $key (keys(%env)) {
                   7645: 		    if ($key=~/^httpref\..*\*/) {
                   7646: 			my $pattern=$key;
1.156     www      7647:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7648:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7649:                         $pattern=~s/\//\\\//g;
1.152     www      7650:                         if ($orguri=~/$pattern/) {
1.800     albertel 7651: 			    $refuri=$env{$key};
1.148     www      7652:                         }
                   7653:                     }
1.191     harris41 7654:                 }
1.148     www      7655:             }
1.232     www      7656: 
1.148     www      7657:          if ($refuri) { 
1.152     www      7658: 	  $refuri=&declutter($refuri);
1.232     www      7659:           my ($match,$cond)=&is_on_map($refuri);
                   7660:             if ($match) {
                   7661:               my $refstatecond=$cond;
1.620     albertel 7662:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7663:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7664:                   my $value = $1;
                   7665:                   if ($priv eq 'bre') {
1.1281    raeburn  7666:                       if ($noblockcheck) {
                   7667:                           $thisallowed.=$value;
1.1162    raeburn  7668:                       } else {
1.1281    raeburn  7669:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7670:                           if (@blockers > 0) {
                   7671:                               $thisallowed = 'B';
                   7672:                           } else {
                   7673:                               $thisallowed.=$value;
                   7674:                           }
1.1162    raeburn  7675:                       }
                   7676:                   } else {
                   7677:                       $thisallowed.=$value;
                   7678:                   }
1.53      www      7679:                   $uri=$refuri;
                   7680:                   $statecond=$refstatecond;
1.52      www      7681:               }
                   7682:           }
1.148     www      7683:         }
1.29      www      7684:        }
1.52      www      7685:    }
1.29      www      7686: 
1.52      www      7687: #
1.103     harris41 7688: # Gathered now: all privileges that could apply, and condition number
1.52      www      7689: # 
                   7690: #
                   7691: # Full or no access?
                   7692: #
1.29      www      7693: 
1.52      www      7694:     if ($thisallowed=~/F/) {
                   7695: 	return 'F';
                   7696:     }
1.29      www      7697: 
1.52      www      7698:     unless ($thisallowed) {
                   7699:         return '';
                   7700:     }
1.29      www      7701: 
1.52      www      7702: # Restrictions exist, deal with them
                   7703: #
                   7704: #   C:according to course preferences
                   7705: #   R:according to resource settings
                   7706: #   L:unless locked
                   7707: #   X:according to user session state
                   7708: #
                   7709: 
                   7710: # Possibly locked functionality, check all courses
1.54      www      7711: # Locks might take effect only after 10 minutes cache expiration for other
                   7712: # courses, and 2 minutes for current course
1.52      www      7713: 
                   7714:     my $envkey;
                   7715:     if ($thisallowed=~/L/) {
1.1000    raeburn  7716:         foreach $envkey (keys(%env)) {
1.54      www      7717:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7718:                my $courseid=$2;
                   7719:                my $roleid=$1.'.'.$2;
1.92      www      7720:                $courseid=~s/^\///;
1.54      www      7721:                my $expiretime=600;
1.620     albertel 7722:                if ($env{'request.role'} eq $roleid) {
1.54      www      7723: 		  $expiretime=120;
                   7724:                }
                   7725: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7726:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7727:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7728: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7729:                }
1.620     albertel 7730:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7731:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7732: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7733:                        &log($env{'user.domain'},$env{'user.name'},
                   7734:                             $env{'user.home'},
1.57      www      7735:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7736:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7737:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7738: 		       return '';
                   7739:                    }
                   7740:                }
1.620     albertel 7741:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7742:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7743: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7744:                        &log($env{'user.domain'},$env{'user.name'},
                   7745:                             $env{'user.home'},
1.57      www      7746:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7747:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7748:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7749: 		       return '';
                   7750:                    }
                   7751:                }
                   7752: 	   }
1.29      www      7753:        }
1.52      www      7754:     }
                   7755:    
                   7756: #
                   7757: # Rest of the restrictions depend on selected course
                   7758: #
                   7759: 
1.620     albertel 7760:     unless ($env{'request.course.id'}) {
1.766     albertel 7761: 	if ($thisallowed eq 'A') {
                   7762: 	    return 'A';
1.814     raeburn  7763:         } elsif ($thisallowed eq 'B') {
                   7764:             return 'B';
1.766     albertel 7765: 	} else {
                   7766: 	    return '1';
                   7767: 	}
1.52      www      7768:     }
1.29      www      7769: 
1.52      www      7770: #
                   7771: # Now user is definitely in a course
                   7772: #
1.53      www      7773: 
                   7774: 
                   7775: # Course preferences
                   7776: 
                   7777:    if ($thisallowed=~/C/) {
1.620     albertel 7778:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7779:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7780:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7781: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  7782: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7783: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7784: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7785: 			$env{'request.course.id'});
                   7786: 	   }
1.237     www      7787:            return '';
                   7788:        }
                   7789: 
1.620     albertel 7790:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7791: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  7792: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7793: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7794: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7795: 			$env{'request.course.id'});
                   7796: 	   }
1.54      www      7797:            return '';
                   7798:        }
1.53      www      7799:    }
                   7800: 
                   7801: # Resource preferences
                   7802: 
                   7803:    if ($thisallowed=~/R/) {
1.620     albertel 7804:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7805:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7806: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7807: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7808: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7809: 	   }
                   7810: 	   return '';
1.54      www      7811:        }
1.53      www      7812:    }
1.30      www      7813: 
1.246     www      7814: # Restricted by state or randomout?
1.30      www      7815: 
1.52      www      7816:    if ($thisallowed=~/X/) {
1.620     albertel 7817:       if ($env{'acc.randomout'}) {
1.579     albertel 7818: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7819:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7820:             return ''; 
                   7821:          }
1.247     www      7822:       }
                   7823:       if (&condval($statecond)) {
1.52      www      7824: 	 return '2';
                   7825:       } else {
                   7826:          return '';
                   7827:       }
                   7828:    }
1.30      www      7829: 
1.766     albertel 7830:     if ($thisallowed eq 'A') {
                   7831: 	return 'A';
1.814     raeburn  7832:     } elsif ($thisallowed eq 'B') {
                   7833:         return 'B';
1.766     albertel 7834:     }
1.52      www      7835:    return 'F';
1.232     www      7836: }
1.1162    raeburn  7837: 
1.1192    raeburn  7838: # ------------------------------------------- Check construction space access
                   7839: 
                   7840: sub constructaccess {
                   7841:     my ($url,$setpriv)=@_;
                   7842: 
                   7843: # We do not allow editing of previous versions of files
                   7844:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7845: 
                   7846: # Get username and domain from URL
                   7847:     my ($ownername,$ownerdomain,$ownerhome);
                   7848: 
                   7849:     ($ownerdomain,$ownername) =
1.1325    raeburn  7850:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  7851: 
                   7852: # The URL does not really point to any authorspace, forget it
                   7853:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7854: 
                   7855: # Now we need to see if the user has access to the authorspace of
                   7856: # $ownername at $ownerdomain
                   7857: 
                   7858:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7859: # Real author for this?
                   7860:        $ownerhome = $env{'user.home'};
                   7861:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7862:           return ($ownername,$ownerdomain,$ownerhome);
                   7863:        }
                   7864:     } else {
                   7865: # Co-author for this?
                   7866:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7867:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7868:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7869:             return ($ownername,$ownerdomain,$ownerhome);
                   7870:         }
1.1312    raeburn  7871:         if ($env{'request.course.id'}) {
                   7872:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   7873:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   7874:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   7875:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   7876:                     return ($ownername,$ownerdomain,$ownerhome);
                   7877:                 }
                   7878:             }
                   7879:         }
1.1192    raeburn  7880:     }
                   7881: 
                   7882: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7883: # we might as well leave
                   7884:    unless ($setpriv) { return ''; }
                   7885: 
                   7886: # Backdoor access?
                   7887:     my $allowed=&allowed('eco',$ownerdomain);
                   7888: # Nope
                   7889:     unless ($allowed) { return ''; }
                   7890: # Looks like we may have access, but could be locked by the owner of the construction space
                   7891:     if ($allowed eq 'U') {
                   7892:         my %blocked=&get('environment',['domcoord.author'],
                   7893:                          $ownerdomain,$ownername);
                   7894: # Is blocked by owner
                   7895:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7896:     }
                   7897:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7898: # Grant temporary access
                   7899:         my $then=$env{'user.login.time'};
1.1209    raeburn  7900:         my $update=$env{'user.update.time'};
1.1192    raeburn  7901:         if (!$update) { $update = $then; }
                   7902:         my $refresh=$env{'user.refresh.time'};
                   7903:         if (!$refresh) { $refresh = $update; }
                   7904:         my $now = time;
                   7905:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7906:                            $now,'ca','constructaccess');
                   7907:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7908:         return($ownername,$ownerdomain,$ownerhome);
                   7909:     }
                   7910: # No business here
                   7911:     return '';
                   7912: }
                   7913: 
1.1282    raeburn  7914: # ----------------------------------------------------------- Content Blocking
                   7915: 
                   7916: {
                   7917: # Caches for faster Course Contents display where content blocking
                   7918: # is in operation (i.e., interval param set) for timed quiz.
                   7919: #
                   7920: # User for whom data are being temporarily cached.
                   7921: my $cacheduser='';
                   7922: # Cached blockers for this user (a hash of blocking items). 
                   7923: my %cachedblockers=();
                   7924: # When the data were last cached.
                   7925: my $cachedlast='';
                   7926: 
                   7927: sub load_all_blockers {
                   7928:     my ($uname,$udom,$blocks)=@_;
                   7929:     if (($uname ne '') && ($udom ne '')) { 
                   7930:         if (($cacheduser eq $uname.':'.$udom) &&
                   7931:             (abs($cachedlast-time)<5)) {
                   7932:             return;
                   7933:         }
                   7934:     }
                   7935:     $cachedlast=time;
                   7936:     $cacheduser=$uname.':'.$udom;
                   7937:     %cachedblockers = &get_commblock_resources($blocks);
                   7938: }
                   7939: 
1.1162    raeburn  7940: sub get_comm_blocks {
                   7941:     my ($cdom,$cnum) = @_;
                   7942:     if ($cdom eq '' || $cnum eq '') {
                   7943:         return unless ($env{'request.course.id'});
                   7944:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7945:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7946:     }
                   7947:     my %commblocks;
                   7948:     my $hashid=$cdom.'_'.$cnum;
                   7949:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7950:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7951:         %commblocks = %{$blocksref};
                   7952:     } else {
                   7953:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7954:         my $cachetime = 600;
                   7955:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7956:     }
                   7957:     return %commblocks;
                   7958: }
                   7959: 
1.1282    raeburn  7960: sub get_commblock_resources {
                   7961:     my ($blocks) = @_;
                   7962:     my %blockers = ();
                   7963:     return %blockers unless ($env{'request.course.id'});
                   7964:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7965:     my %commblocks;
                   7966:     if (ref($blocks) eq 'HASH') {
                   7967:         %commblocks = %{$blocks};
                   7968:     } else {
                   7969:         %commblocks = &get_comm_blocks();
                   7970:     }
1.1282    raeburn  7971:     return %blockers unless (keys(%commblocks) > 0); 
                   7972:     my $navmap = Apache::lonnavmaps::navmap->new();
                   7973:     return %blockers unless (ref($navmap));
1.1162    raeburn  7974:     my $now = time;
                   7975:     foreach my $block (keys(%commblocks)) {
                   7976:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7977:             my ($start,$end) = ($1,$2);
                   7978:             if ($start <= $now && $end >= $now) {
                   7979:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7980:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7981:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  7982:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7983:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  7984:                             }
                   7985:                         }
                   7986:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  7987:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7988:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  7989:                             }
                   7990:                         }
                   7991:                     }
                   7992:                 }
                   7993:             }
                   7994:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7995:             my $item = $1;
1.1163    raeburn  7996:             my @to_test;
1.1162    raeburn  7997:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7998:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  7999:                     my @interval;
                   8000:                     my $type = 'map';
                   8001:                     if ($item eq 'course') {
                   8002:                         $type = 'course';
                   8003:                         @interval=&EXT("resource.0.interval");
                   8004:                     } else {
                   8005:                         if ($item =~ /___\d+___/) {
                   8006:                             $type = 'resource';
                   8007:                             @interval=&EXT("resource.0.interval",$item);
                   8008:                             if (ref($navmap)) {                        
                   8009:                                 my $res = $navmap->getBySymb($item); 
                   8010:                                 push(@to_test,$res);
                   8011:                             }
1.1162    raeburn  8012:                         } else {
1.1282    raeburn  8013:                             my $mapsymb = &symbread($item,1);
                   8014:                             if ($mapsymb) {
                   8015:                                 if (ref($navmap)) {
                   8016:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8017:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8018:                                     foreach my $res (@to_test) {
                   8019:                                         my $symb = $res->symb();
                   8020:                                         next if ($symb eq $mapsymb);
                   8021:                                         if ($symb ne '') {
                   8022:                                             @interval=&EXT("resource.0.interval",$symb);
                   8023:                                             if ($interval[1] eq 'map') {
                   8024:                                                 last;
1.1162    raeburn  8025:                                             }
                   8026:                                         }
                   8027:                                     }
                   8028:                                 }
                   8029:                             }
                   8030:                         }
1.1282    raeburn  8031:                     }
1.1310    raeburn  8032:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  8033:                         my $timelimit = $1; 
1.1282    raeburn  8034:                         my $first_access;
                   8035:                         if ($type eq 'resource') {
                   8036:                             $first_access=&get_first_access($interval[1],$item);
                   8037:                         } elsif ($type eq 'map') {
                   8038:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8039:                         } else {
                   8040:                             $first_access=&get_first_access($interval[1]);
                   8041:                         }
                   8042:                         if ($first_access) {
1.1292    raeburn  8043:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  8044:                             if ($timesup > $now) {
                   8045:                                 my $activeblock;
                   8046:                                 foreach my $res (@to_test) {
1.1283    raeburn  8047:                                     if ($res->answerable()) {
1.1282    raeburn  8048:                                         $activeblock = 1;
                   8049:                                         last;
                   8050:                                     }
                   8051:                                 }
                   8052:                                 if ($activeblock) {
                   8053:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8054:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8055:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8056:                                          }
                   8057:                                     }
                   8058:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8059:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8060:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8061:                                         }
1.1162    raeburn  8062:                                     }
                   8063:                                 }
                   8064:                             }
                   8065:                         }
                   8066:                     }
                   8067:                 }
                   8068:             }
                   8069:         }
                   8070:     }
1.1282    raeburn  8071:     return %blockers;
1.1162    raeburn  8072: }
                   8073: 
1.1282    raeburn  8074: sub has_comm_blocking {
                   8075:     my ($priv,$symb,$uri,$blocks) = @_;
                   8076:     my @blockers;
                   8077:     return unless ($env{'request.course.id'});
                   8078:     return unless ($priv eq 'bre');
                   8079:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8080:     return if ($env{'request.state'} eq 'construct');
                   8081:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8082:     return unless (keys(%cachedblockers) > 0);
                   8083:     my (%possibles,@symbs);
                   8084:     if (!$symb) {
                   8085:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8086:     }
1.1282    raeburn  8087:     if ($symb) {
                   8088:         @symbs = ($symb);
                   8089:     } elsif (keys(%possibles)) { 
                   8090:         @symbs = keys(%possibles);
                   8091:     }
                   8092:     my $noblock;
                   8093:     foreach my $symb (@symbs) {
                   8094:         last if ($noblock);
                   8095:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8096:         foreach my $block (keys(%cachedblockers)) {
                   8097:             if ($block =~ /^firstaccess____(.+)$/) {
                   8098:                 my $item = $1;
                   8099:                 if (($item eq $map) || ($item eq $symb)) {
                   8100:                     $noblock = 1;
                   8101:                     last;
                   8102:                 }
                   8103:             }
                   8104:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8105:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8106:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8107:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8108:                             push(@blockers,$block);
                   8109:                         }
                   8110:                     }
                   8111:                 }
1.1162    raeburn  8112:             }
1.1282    raeburn  8113:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8114:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8115:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8116:                         push(@blockers,$block);
                   8117:                     }
                   8118:                 }
1.1162    raeburn  8119:             }
                   8120:         }
                   8121:     }
1.1282    raeburn  8122:     return if ($noblock);
                   8123:     return @blockers;
                   8124: }
1.1162    raeburn  8125: }
                   8126: 
1.1282    raeburn  8127: # -------------------------------- Deversion and split uri into path an filename   
                   8128: 
1.1133    foxr     8129: #
1.1282    raeburn  8130: #   Removes the version from a URI and
1.1133    foxr     8131: #   splits it in to its filename and path to the filename.
                   8132: #   Seems like File::Basename could have done this more clearly.
                   8133: #   Parameters:
                   8134: #      $uri   - input URI
                   8135: #   Returns:
                   8136: #     Two element list consisting of 
                   8137: #     $pathname  - the URI up to and excluding the trailing /
                   8138: #     $filename  - The part of the URI following the last /
                   8139: #  NOTE:
                   8140: #    Another realization of this is simply:
                   8141: #    use File::Basename;
                   8142: #    ...
                   8143: #    $uri = shift;
                   8144: #    $filename = basename($uri);
                   8145: #    $path     = dirname($uri);
                   8146: #    return ($filename, $path);
                   8147: #
                   8148: #     The implementation below is probably faster however.
                   8149: #
1.710     albertel 8150: sub split_uri_for_cond {
                   8151:     my $uri=&deversion(&declutter(shift));
                   8152:     my @uriparts=split(/\//,$uri);
                   8153:     my $filename=pop(@uriparts);
                   8154:     my $pathname=join('/',@uriparts);
                   8155:     return ($pathname,$filename);
                   8156: }
1.232     www      8157: # --------------------------------------------------- Is a resource on the map?
                   8158: 
                   8159: sub is_on_map {
1.710     albertel 8160:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8161:     #Trying to find the conditional for the file
1.620     albertel 8162:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8163: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8164:     if ($match) {
1.289     bowersj2 8165: 	return (1,$1);
                   8166:     } else {
1.434     www      8167: 	return (0,0);
1.289     bowersj2 8168:     }
1.12      www      8169: }
                   8170: 
1.427     www      8171: # --------------------------------------------------------- Get symb from alias
                   8172: 
                   8173: sub get_symb_from_alias {
                   8174:     my $symb=shift;
                   8175:     my ($map,$resid,$url)=&decode_symb($symb);
                   8176: # Already is a symb
                   8177:     if ($url) { return $symb; }
                   8178: # Must be an alias
                   8179:     my $aliassymb='';
                   8180:     my %bighash;
1.620     albertel 8181:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8182:                             &GDBM_READER(),0640)) {
                   8183:         my $rid=$bighash{'mapalias_'.$symb};
                   8184: 	if ($rid) {
                   8185: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8186: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8187: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8188: 	}
                   8189:         untie %bighash;
                   8190:     }
                   8191:     return $aliassymb;
                   8192: }
                   8193: 
1.12      www      8194: # ----------------------------------------------------------------- Define Role
                   8195: 
                   8196: sub definerole {
                   8197:   if (allowed('mcr','/')) {
1.1326    raeburn  8198:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8199:     foreach my $role (split(':',$sysrole)) {
                   8200: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8201:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8202:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8203: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8204:                return "refused:s:$crole&$cqual"; 
                   8205:             }
                   8206:         }
1.191     harris41 8207:     }
1.800     albertel 8208:     foreach my $role (split(':',$domrole)) {
                   8209: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8210:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8211:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8212: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8213:                return "refused:d:$crole&$cqual"; 
                   8214:             }
                   8215:         }
1.191     harris41 8216:     }
1.800     albertel 8217:     foreach my $role (split(':',$courole)) {
                   8218: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8219:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8220:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8221: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8222:                return "refused:c:$crole&$cqual"; 
                   8223:             }
                   8224:         }
1.191     harris41 8225:     }
1.1326    raeburn  8226:     my $uhome;
                   8227:     if (($uname ne '') && ($udom ne '')) {
                   8228:         $uhome = &homeserver($uname,$udom);
                   8229:         return $uhome if ($uhome eq 'no_host');
                   8230:     } else {
                   8231:         $uname = $env{'user.name'};
                   8232:         $udom = $env{'user.domain'};
                   8233:         $uhome = $env{'user.home'};
                   8234:     }
1.620     albertel 8235:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  8236:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8237:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  8238:     return reply($command,$uhome);
1.12      www      8239:   } else {
                   8240:     return 'refused';
                   8241:   }
1.105     harris41 8242: }
                   8243: 
                   8244: # ---------------- Make a metadata query against the network of library servers
                   8245: 
                   8246: sub metadata_query {
1.1237    raeburn  8247:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8248:     my %rhash;
1.845     albertel 8249:     my %libserv = &all_library();
1.244     matthew  8250:     my @server_list = (defined($server_array) ? @$server_array
                   8251:                                               : keys(%libserv) );
                   8252:     for my $server (@server_list) {
1.1237    raeburn  8253:         my $domains = ''; 
                   8254:         if (ref($domains_hash) eq 'HASH') {
                   8255:             $domains = $domains_hash->{$server}; 
                   8256:         }
1.118     harris41 8257: 	unless ($custom or $customshow) {
1.1237    raeburn  8258: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8259: 	    $rhash{$server}=$reply;
                   8260: 	}
                   8261: 	else {
                   8262: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  8263: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8264: 			     $server);
                   8265: 	    $rhash{$server}=$reply;
                   8266: 	}
1.112     harris41 8267:     }
1.118     harris41 8268:     return \%rhash;
1.240     www      8269: }
                   8270: 
                   8271: # ----------------------------------------- Send log queries and wait for reply
                   8272: 
                   8273: sub log_query {
                   8274:     my ($uname,$udom,$query,%filters)=@_;
                   8275:     my $uhome=&homeserver($uname,$udom);
                   8276:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8277:     my $uhost=&hostname($uhome);
1.800     albertel 8278:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8279:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8280:                        $uhome);
1.479     albertel 8281:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8282:     return get_query_reply($queryid);
                   8283: }
                   8284: 
1.818     raeburn  8285: # -------------------------- Update MySQL table for portfolio file
                   8286: 
                   8287: sub update_portfolio_table {
1.821     raeburn  8288:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8289:     if ($group ne '') {
                   8290:         $file_name =~s /^\Q$group\E//;
                   8291:     }
1.818     raeburn  8292:     my $homeserver = &homeserver($uname,$udom);
                   8293:     my $queryid=
1.821     raeburn  8294:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8295:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8296:     my $reply = &get_query_reply($queryid);
                   8297:     return $reply;
                   8298: }
                   8299: 
1.899     raeburn  8300: # -------------------------- Update MySQL allusers table
                   8301: 
                   8302: sub update_allusers_table {
                   8303:     my ($uname,$udom,$names) = @_;
                   8304:     my $homeserver = &homeserver($uname,$udom);
                   8305:     my $queryid=
                   8306:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8307:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8308:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8309:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8310:                'generation='.&escape($names->{'generation'}).'%%'.
                   8311:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8312:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8313:     return;
1.899     raeburn  8314: }
                   8315: 
1.508     raeburn  8316: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8317: 
                   8318: sub fetch_enrollment_query {
1.511     raeburn  8319:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  8320:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8321:     my $maxtries = 1;
1.508     raeburn  8322:     if ($context eq 'automated') {
                   8323:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  8324:         $sleep = 2;
                   8325:         $loopmax = 100;
1.547     raeburn  8326:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8327:     } else {
                   8328:         $homeserver = &homeserver($cnum,$dom);
                   8329:     }
1.838     albertel 8330:     my $host=&hostname($homeserver);
1.506     raeburn  8331:     my $cmd = '';
1.1000    raeburn  8332:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8333:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8334:     }
                   8335:     $cmd =~ s/%%$//;
                   8336:     $cmd = &escape($cmd);
                   8337:     my $query = 'fetchenrollment';
1.620     albertel 8338:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8339:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8340:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8341:         return 'error: '.$queryid;
                   8342:     }
1.1317    raeburn  8343:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8344:     my $tries = 1;
                   8345:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  8346:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8347:         $tries ++;
                   8348:     }
1.526     raeburn  8349:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8350:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8351:     } else {
1.901     albertel 8352:         my @responses = split(/:/,$reply);
1.1322    raeburn  8353:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8354:             foreach my $line (@responses) {
                   8355:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8356:                 $$replyref{$key} = $value;
                   8357:             }
                   8358:         } else {
1.1117    foxr     8359:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8360:             foreach my $line (@responses) {
                   8361:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8362:                 $$replyref{$key} = $value;
                   8363:                 if ($value > 0) {
1.800     albertel 8364:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8365:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8366:                         my $destname = $pathname.'/'.$filename;
                   8367:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8368:                         if ($xml_classlist =~ /^error/) {
                   8369:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8370:                         } else {
1.506     raeburn  8371:                             if ( open(FILE,">$destname") ) {
                   8372:                                 print FILE &unescape($xml_classlist);
                   8373:                                 close(FILE);
1.526     raeburn  8374:                             } else {
                   8375:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8376:                             }
                   8377:                         }
                   8378:                     }
                   8379:                 }
                   8380:             }
                   8381:         }
                   8382:         return 'ok';
                   8383:     }
                   8384:     return 'error';
                   8385: }
                   8386: 
1.242     www      8387: sub get_query_reply {
1.1317    raeburn  8388:     my ($queryid,$sleep,$loopmax) = @_;;
                   8389:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8390:         $sleep = 0.2;
                   8391:     }
                   8392:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8393:         $loopmax = 100;
                   8394:     }
1.1117    foxr     8395:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8396:     my $reply='';
1.1317    raeburn  8397:     for (1..$loopmax) {
                   8398: 	sleep($sleep);
1.240     www      8399:         if (-e $replyfile.'.end') {
1.448     albertel 8400: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 8401: 		$reply = join('',<$fh>);
                   8402: 		close($fh);
1.240     www      8403: 	   } else { return 'error: reply_file_error'; }
1.242     www      8404:            return &unescape($reply);
                   8405: 	}
1.240     www      8406:     }
1.242     www      8407:     return 'timeout:'.$queryid;
1.240     www      8408: }
                   8409: 
                   8410: sub courselog_query {
1.241     www      8411: #
                   8412: # possible filters:
                   8413: # url: url or symb
                   8414: # username
                   8415: # domain
                   8416: # action: view, submit, grade
                   8417: # start: timestamp
                   8418: # end: timestamp
                   8419: #
1.240     www      8420:     my (%filters)=@_;
1.620     albertel 8421:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8422:     if ($filters{'url'}) {
                   8423: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8424:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8425:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8426:     }
1.620     albertel 8427:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8428:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8429:     return &log_query($cname,$cdom,'courselog',%filters);
                   8430: }
                   8431: 
                   8432: sub userlog_query {
1.858     raeburn  8433: #
                   8434: # possible filters:
                   8435: # action: log check role
                   8436: # start: timestamp
                   8437: # end: timestamp
                   8438: #
1.240     www      8439:     my ($uname,$udom,%filters)=@_;
                   8440:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8441: }
                   8442: 
1.506     raeburn  8443: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8444: 
                   8445: sub auto_run {
1.508     raeburn  8446:     my ($cnum,$cdom) = @_;
1.876     raeburn  8447:     my $response = 0;
                   8448:     my $settings;
                   8449:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8450:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8451:         $settings = $domconfig{'autoenroll'};
                   8452:         if ($settings->{'run'} eq '1') {
                   8453:             $response = 1;
                   8454:         }
                   8455:     } else {
1.934     raeburn  8456:         my $homeserver;
                   8457:         if (&is_course($cdom,$cnum)) {
                   8458:             $homeserver = &homeserver($cnum,$cdom);
                   8459:         } else {
                   8460:             $homeserver = &domain($cdom,'primary');
                   8461:         }
                   8462:         if ($homeserver ne 'no_host') {
                   8463:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8464:         }
1.876     raeburn  8465:     }
1.506     raeburn  8466:     return $response;
                   8467: }
1.776     albertel 8468: 
1.506     raeburn  8469: sub auto_get_sections {
1.508     raeburn  8470:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8471:     my $homeserver;
                   8472:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8473:         $homeserver = &homeserver($cnum,$cdom);
                   8474:     }
                   8475:     if (!defined($homeserver)) { 
                   8476:         if ($cdom =~ /^$match_domain$/) {
                   8477:             $homeserver = &domain($cdom,'primary');
                   8478:         }
                   8479:     }
                   8480:     my @secs;
                   8481:     if (defined($homeserver)) {
                   8482:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8483:         unless ($response eq 'refused') {
                   8484:             @secs = split(/:/,$response);
                   8485:         }
1.506     raeburn  8486:     }
                   8487:     return @secs;
                   8488: }
1.776     albertel 8489: 
1.506     raeburn  8490: sub auto_new_course {
1.1099    raeburn  8491:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8492:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8493:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8494:     return $response;
                   8495: }
1.776     albertel 8496: 
1.506     raeburn  8497: sub auto_validate_courseID {
1.508     raeburn  8498:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8499:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8500:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8501:     return $response;
                   8502: }
1.776     albertel 8503: 
1.1007    raeburn  8504: sub auto_validate_instcode {
1.1020    raeburn  8505:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8506:     my ($homeserver,$response);
                   8507:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8508:         $homeserver = &homeserver($cnum,$cdom);
                   8509:     }
                   8510:     if (!defined($homeserver)) {
                   8511:         if ($cdom =~ /^$match_domain$/) {
                   8512:             $homeserver = &domain($cdom,'primary');
                   8513:         }
                   8514:     }
1.1065    raeburn  8515:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8516:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  8517:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8518:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8519: }
                   8520: 
1.506     raeburn  8521: sub auto_create_password {
1.873     raeburn  8522:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8523:     my ($homeserver,$response);
1.506     raeburn  8524:     my $create_passwd = 0;
                   8525:     my $authchk = '';
1.873     raeburn  8526:     if ($udom =~ /^$match_domain$/) {
                   8527:         $homeserver = &domain($udom,'primary');
                   8528:     }
                   8529:     if ($homeserver eq '') {
                   8530:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8531:             $homeserver = &homeserver($cnum,$cdom);
                   8532:         }
                   8533:     }
                   8534:     if ($homeserver eq '') {
                   8535:         $authchk = 'nodomain';
1.506     raeburn  8536:     } else {
1.873     raeburn  8537:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8538:         if ($response eq 'refused') {
                   8539:             $authchk = 'refused';
                   8540:         } else {
1.901     albertel 8541:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8542:         }
1.506     raeburn  8543:     }
                   8544:     return ($authparam,$create_passwd,$authchk);
                   8545: }
                   8546: 
1.706     raeburn  8547: sub auto_photo_permission {
                   8548:     my ($cnum,$cdom,$students) = @_;
                   8549:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8550:     my ($outcome,$perm_reqd,$conditions) = 
                   8551: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8552:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8553: 	return (undef,undef);
                   8554:     }
1.706     raeburn  8555:     return ($outcome,$perm_reqd,$conditions);
                   8556: }
                   8557: 
                   8558: sub auto_checkphotos {
                   8559:     my ($uname,$udom,$pid) = @_;
                   8560:     my $homeserver = &homeserver($uname,$udom);
                   8561:     my ($result,$resulttype);
                   8562:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8563: 				   &escape($uname).':'.&escape($pid),
                   8564: 				   $homeserver));
1.709     albertel 8565:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8566: 	return (undef,undef);
                   8567:     }
1.706     raeburn  8568:     if ($outcome) {
                   8569:         ($result,$resulttype) = split(/:/,$outcome);
                   8570:     } 
                   8571:     return ($result,$resulttype);
                   8572: }
                   8573: 
                   8574: sub auto_photochoice {
                   8575:     my ($cnum,$cdom) = @_;
                   8576:     my $homeserver = &homeserver($cnum,$cdom);
                   8577:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8578: 						       &escape($cdom),
                   8579: 						       $homeserver)));
1.709     albertel 8580:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8581: 	return (undef,undef);
                   8582:     }
1.706     raeburn  8583:     return ($update,$comment);
                   8584: }
                   8585: 
                   8586: sub auto_photoupdate {
                   8587:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8588:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8589:     my $host=&hostname($homeserver);
1.706     raeburn  8590:     my $cmd = '';
                   8591:     my $maxtries = 1;
1.800     albertel 8592:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8593:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8594:     }
                   8595:     $cmd =~ s/%%$//;
                   8596:     $cmd = &escape($cmd);
                   8597:     my $query = 'institutionalphotos';
                   8598:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8599:     unless ($queryid=~/^\Q$host\E\_/) {
                   8600:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8601:         return 'error: '.$queryid;
                   8602:     }
                   8603:     my $reply = &get_query_reply($queryid);
                   8604:     my $tries = 1;
                   8605:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8606:         $reply = &get_query_reply($queryid);
                   8607:         $tries ++;
                   8608:     }
                   8609:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8610:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8611:     } else {
                   8612:         my @responses = split(/:/,$reply);
                   8613:         my $outcome = shift(@responses); 
                   8614:         foreach my $item (@responses) {
                   8615:             my ($key,$value) = split(/=/,$item);
                   8616:             $$photo{$key} = $value;
                   8617:         }
                   8618:         return $outcome;
                   8619:     }
                   8620:     return 'error';
                   8621: }
                   8622: 
1.521     raeburn  8623: sub auto_instcode_format {
1.793     albertel 8624:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8625: 	$cat_order) = @_;
1.521     raeburn  8626:     my $courses = '';
1.772     raeburn  8627:     my @homeservers;
1.521     raeburn  8628:     if ($caller eq 'global') {
1.841     albertel 8629: 	my %servers = &get_servers($codedom,'library');
                   8630: 	foreach my $tryserver (keys(%servers)) {
                   8631: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8632: 		push(@homeservers,$tryserver);
                   8633: 	    }
1.584     raeburn  8634:         }
1.1022    raeburn  8635:     } elsif ($caller eq 'requests') {
                   8636:         if ($codedom =~ /^$match_domain$/) {
                   8637:             my $chome = &domain($codedom,'primary');
                   8638:             unless ($chome eq 'no_host') {
                   8639:                 push(@homeservers,$chome);
                   8640:             }
                   8641:         }
1.521     raeburn  8642:     } else {
1.772     raeburn  8643:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8644:     }
1.793     albertel 8645:     foreach my $code (keys(%{$instcodes})) {
                   8646:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8647:     }
                   8648:     chop($courses);
1.772     raeburn  8649:     my $ok_response = 0;
                   8650:     my $response;
                   8651:     while (@homeservers > 0 && $ok_response == 0) {
                   8652:         my $server = shift(@homeservers); 
                   8653:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8654:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8655:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8656: 		split(/:/,$response);
1.772     raeburn  8657:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8658:             push(@{$codetitles},&str2array($codetitles_str));
                   8659:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8660:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8661:             $ok_response = 1;
                   8662:         }
                   8663:     }
                   8664:     if ($ok_response) {
1.521     raeburn  8665:         return 'ok';
1.772     raeburn  8666:     } else {
                   8667:         return $response;
1.521     raeburn  8668:     }
                   8669: }
                   8670: 
1.792     raeburn  8671: sub auto_instcode_defaults {
                   8672:     my ($domain,$returnhash,$code_order) = @_;
                   8673:     my @homeservers;
1.841     albertel 8674: 
                   8675:     my %servers = &get_servers($domain,'library');
                   8676:     foreach my $tryserver (keys(%servers)) {
                   8677: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8678: 	    push(@homeservers,$tryserver);
                   8679: 	}
1.792     raeburn  8680:     }
1.841     albertel 8681: 
1.792     raeburn  8682:     my $response;
1.841     albertel 8683:     foreach my $server (@homeservers) {
1.792     raeburn  8684:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8685:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8686: 	
                   8687: 	foreach my $pair (split(/\&/,$response)) {
                   8688: 	    my ($name,$value)=split(/\=/,$pair);
                   8689: 	    if ($name eq 'code_order') {
                   8690: 		@{$code_order} = split(/\&/,&unescape($value));
                   8691: 	    } else {
                   8692: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8693: 	    }
                   8694: 	}
                   8695: 	return 'ok';
1.792     raeburn  8696:     }
1.841     albertel 8697: 
                   8698:     return $response;
1.1003    raeburn  8699: }
                   8700: 
                   8701: sub auto_possible_instcodes {
1.1007    raeburn  8702:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8703:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8704:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8705:         return;
                   8706:     }
1.1003    raeburn  8707:     my (@homeservers,$uhome);
                   8708:     if (defined(&domain($domain,'primary'))) {
                   8709:         $uhome=&domain($domain,'primary');
                   8710:         push(@homeservers,&domain($domain,'primary'));
                   8711:     } else {
                   8712:         my %servers = &get_servers($domain,'library');
                   8713:         foreach my $tryserver (keys(%servers)) {
                   8714:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8715:                 push(@homeservers,$tryserver);
                   8716:             }
                   8717:         }
                   8718:     }
                   8719:     my $response;
                   8720:     foreach my $server (@homeservers) {
                   8721:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8722:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8723:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8724:             split(':',$response);
                   8725:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8726:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8727:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8728:             my ($name,$value)=split('=',$item);
                   8729:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8730:         }
                   8731:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8732:             my ($name,$value)=split('=',$item);
                   8733:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8734:         }
                   8735:         return 'ok';
                   8736:     }
                   8737:     return $response;
                   8738: }
1.792     raeburn  8739: 
1.1010    raeburn  8740: sub auto_courserequest_checks {
                   8741:     my ($dom) = @_;
1.1020    raeburn  8742:     my ($homeserver,%validations);
                   8743:     if ($dom =~ /^$match_domain$/) {
                   8744:         $homeserver = &domain($dom,'primary');
                   8745:     }
                   8746:     unless ($homeserver eq 'no_host') {
                   8747:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8748:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8749:             my @items = split(/&/,$response);
                   8750:             foreach my $item (@items) {
                   8751:                 my ($key,$value) = split('=',$item);
                   8752:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8753:             }
                   8754:         }
                   8755:     }
1.1010    raeburn  8756:     return %validations; 
                   8757: }
                   8758: 
1.1020    raeburn  8759: sub auto_courserequest_validation {
1.1255    raeburn  8760:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8761:     my ($homeserver,$response);
                   8762:     if ($dom =~ /^$match_domain$/) {
                   8763:         $homeserver = &domain($dom,'primary');
                   8764:     }
1.1255    raeburn  8765:     unless ($homeserver eq 'no_host') {
                   8766:         my $customdata;
                   8767:         if (ref($custominfo) eq 'HASH') {
                   8768:             $customdata = &freeze_escape($custominfo);
                   8769:         }
1.1020    raeburn  8770:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8771:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  8772:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8773:                                     $customdata,$homeserver));
1.1020    raeburn  8774:     }
                   8775:     return $response;
                   8776: }
                   8777: 
1.777     albertel 8778: sub auto_validate_class_sec {
1.918     raeburn  8779:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8780:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8781:     my $ownerlist;
                   8782:     if (ref($owners) eq 'ARRAY') {
                   8783:         $ownerlist = join(',',@{$owners});
                   8784:     } else {
                   8785:         $ownerlist = $owners;
                   8786:     }
1.773     raeburn  8787:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8788:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8789:     return $response;
                   8790: }
                   8791: 
1.1248    raeburn  8792: sub auto_crsreq_update {
                   8793:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  8794:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  8795:     my ($homeserver,%crsreqresponse);
                   8796:     if ($cdom =~ /^$match_domain$/) {
                   8797:         $homeserver = &domain($cdom,'primary');
                   8798:     }
                   8799:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8800:         my $info;
                   8801:         if (ref($inbound) eq 'HASH') {
                   8802:             $info = &freeze_escape($inbound);
                   8803:         }
                   8804:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8805:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8806:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  8807:                             &escape($title).':'.&escape($code).':'.
                   8808:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   8809:                             $homeserver);
1.1248    raeburn  8810:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8811:             my @items = split(/&/,$response);
                   8812:             foreach my $item (@items) {
                   8813:                 my ($key,$value) = split('=',$item);
                   8814:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8815:             }
                   8816:         }
                   8817:     }
                   8818:     return \%crsreqresponse;
                   8819: }
                   8820: 
1.1305    raeburn  8821: sub auto_export_grades {
1.1309    raeburn  8822:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8823:     my ($homeserver,%exportresponse);
                   8824:     if ($cdom =~ /^$match_domain$/) {
                   8825:         $homeserver = &domain($cdom,'primary');
                   8826:     }
                   8827:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8828:         my $info;
                   8829:         if (ref($inforef) eq 'HASH') {
                   8830:             $info = &freeze_escape($inforef);
                   8831:         }
                   8832:         if (ref($gradesref) eq 'HASH') {
                   8833:             my $grades = &freeze_escape($gradesref);
                   8834:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   8835:                                 $info.':'.$grades,$homeserver);
                   8836:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   8837:                 my @items = split(/&/,$response);
                   8838:                 foreach my $item (@items) {
                   8839:                     my ($key,$value) = split('=',$item);
                   8840:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   8841:                 }
                   8842:             }
                   8843:         }
                   8844:     }
                   8845:     return \%exportresponse;
1.1305    raeburn  8846: }
                   8847: 
1.1287    raeburn  8848: sub check_instcode_cloning {
                   8849:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8850:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8851:         return;
                   8852:     }
                   8853:     my $canclone;
                   8854:     if (@{$code_order} > 0) {
                   8855:         my $instcoderegexp ='^';
                   8856:         my @clonecodes = split(/\&/,$cloner);
                   8857:         foreach my $item (@{$code_order}) {
                   8858:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8859:                 foreach my $pair (@clonecodes) {
                   8860:                     my ($key,$val) = split(/\=/,$pair,2);
                   8861:                     $val = &unescape($val);
                   8862:                     if ($key eq $item) {
                   8863:                         $instcoderegexp .= '('.$val.')';
                   8864:                         last;
                   8865:                     }
                   8866:                 }
                   8867:             } else {
                   8868:                 $instcoderegexp .= $codedefaults->{$item};
                   8869:             }
                   8870:         }
                   8871:         $instcoderegexp .= '$';
                   8872:         my (@from,@to);
                   8873:         eval {
                   8874:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8875:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8876:         };
                   8877:         if ((@from > 0) && (@to > 0)) {
                   8878:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8879:             if (!@diffs) {
                   8880:                 $canclone = 1;
                   8881:             }
                   8882:         }
                   8883:     }
                   8884:     return $canclone;
                   8885: }
                   8886: 
                   8887: sub default_instcode_cloning {
                   8888:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8889:     my (%codedefaults,@code_order,$canclone);
                   8890:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8891:         %codedefaults = %{$codedefaultsref};
                   8892:         @code_order = @{$codeorderref};
                   8893:     } elsif ($clonedom) {
                   8894:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8895:     }
                   8896:     if (($domdefclone) && (@code_order)) {
                   8897:         my @clonecodes = split(/\+/,$domdefclone);
                   8898:         my $instcoderegexp ='^';
                   8899:         foreach my $item (@code_order) {
                   8900:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8901:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8902:             } else {
                   8903:                 $instcoderegexp .= $codedefaults{$item};
                   8904:             }
                   8905:         }
                   8906:         $instcoderegexp .= '$';
                   8907:         my (@from,@to);
                   8908:         eval {
                   8909:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8910:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8911:         };
                   8912:         if ((@from > 0) && (@to > 0)) {
                   8913:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8914:             if (!@diffs) {
                   8915:                 $canclone = 1;
                   8916:             }
                   8917:         }
                   8918:     }
                   8919:     return $canclone;
                   8920: }
                   8921: 
1.679     raeburn  8922: # ------------------------------------------------------- Course Group routines
                   8923: 
                   8924: sub get_coursegroups {
1.809     raeburn  8925:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8926:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8927: }
                   8928: 
1.679     raeburn  8929: sub modify_coursegroup {
                   8930:     my ($cdom,$cnum,$groupsettings) = @_;
                   8931:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8932: }
                   8933: 
1.809     raeburn  8934: sub toggle_coursegroup_status {
                   8935:     my ($cdom,$cnum,$group,$action) = @_;
                   8936:     my ($from_namespace,$to_namespace);
                   8937:     if ($action eq 'delete') {
                   8938:         $from_namespace = 'coursegroups';
                   8939:         $to_namespace = 'deleted_groups';
                   8940:     } else {
                   8941:         $from_namespace = 'deleted_groups';
                   8942:         $to_namespace = 'coursegroups';
                   8943:     }
                   8944:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8945:     if (my $tmp = &error(%curr_group)) {
                   8946:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8947:         return ('read error',$tmp);
                   8948:     } else {
                   8949:         my %savedsettings = %curr_group; 
1.809     raeburn  8950:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8951:         my $deloutcome;
                   8952:         if ($result eq 'ok') {
1.809     raeburn  8953:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8954:         } else {
                   8955:             return ('write error',$result);
                   8956:         }
                   8957:         if ($deloutcome eq 'ok') {
                   8958:             return 'ok';
                   8959:         } else {
                   8960:             return ('delete error',$deloutcome);
                   8961:         }
                   8962:     }
                   8963: }
                   8964: 
1.679     raeburn  8965: sub modify_group_roles {
1.957     raeburn  8966:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8967:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8968:     my $role = 'gr/'.&escape($userprivs);
                   8969:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8970:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8971:     if ($result eq 'ok') {
                   8972:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8973:     }
1.679     raeburn  8974:     return $result;
                   8975: }
                   8976: 
                   8977: sub modify_coursegroup_membership {
                   8978:     my ($cdom,$cnum,$membership) = @_;
                   8979:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8980:     return $result;
                   8981: }
                   8982: 
1.682     raeburn  8983: sub get_active_groups {
                   8984:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8985:     my $now = time;
                   8986:     my %groups = ();
                   8987:     foreach my $key (keys(%env)) {
1.811     albertel 8988:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8989:             my ($start,$end) = split(/\./,$env{$key});
                   8990:             if (($end!=0) && ($end<$now)) { next; }
                   8991:             if (($start!=0) && ($start>$now)) { next; }
                   8992:             if ($1 eq $cdom && $2 eq $cnum) {
                   8993:                 $groups{$3} = $env{$key} ;
                   8994:             }
                   8995:         }
                   8996:     }
                   8997:     return %groups;
                   8998: }
                   8999: 
1.683     raeburn  9000: sub get_group_membership {
                   9001:     my ($cdom,$cnum,$group) = @_;
                   9002:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9003: }
                   9004: 
                   9005: sub get_users_groups {
                   9006:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9007:     my @usersgroups;
1.683     raeburn  9008:     my $cachetime=1800;
                   9009: 
                   9010:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9011:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9012:     if (defined($cached)) {
1.734     albertel 9013:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9014:     } else {  
                   9015:         $grouplist = '';
1.816     raeburn  9016:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9017:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9018:         my $access_end = $env{'course.'.$courseid.
                   9019:                               '.default_enrollment_end_date'};
                   9020:         my $now = time;
                   9021:         foreach my $key (keys(%roleshash)) {
                   9022:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9023:                 my $group = $1;
                   9024:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9025:                     my $start = $2;
                   9026:                     my $end = $1;
                   9027:                     if ($start == -1) { next; } # deleted from group
                   9028:                     if (($start!=0) && ($start>$now)) { next; }
                   9029:                     if (($end!=0) && ($end<$now)) {
                   9030:                         if ($access_end && $access_end < $now) {
                   9031:                             if ($access_end - $end < 86400) {
                   9032:                                 push(@usersgroups,$group);
1.733     raeburn  9033:                             }
                   9034:                         }
1.817     raeburn  9035:                         next;
1.733     raeburn  9036:                     }
1.817     raeburn  9037:                     push(@usersgroups,$group);
1.683     raeburn  9038:                 }
                   9039:             }
                   9040:         }
1.817     raeburn  9041:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9042:         $grouplist = join(':',@usersgroups);
                   9043:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9044:     }
1.733     raeburn  9045:     return @usersgroups;
1.683     raeburn  9046: }
                   9047: 
                   9048: sub devalidate_getgroups_cache {
                   9049:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9050:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9051: 
1.683     raeburn  9052:     my $hashid="$udom:$uname:$courseid";
                   9053:     &devalidate_cache_new('getgroups',$hashid);
                   9054: }
                   9055: 
1.12      www      9056: # ------------------------------------------------------------------ Plain Text
                   9057: 
                   9058: sub plaintext {
1.988     raeburn  9059:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9060:     if ($short =~ m{^cr/}) {
1.758     albertel 9061: 	return (split('/',$short))[-1];
                   9062:     }
1.742     raeburn  9063:     if (!defined($cid)) {
                   9064:         $cid = $env{'request.course.id'};
                   9065:     }
                   9066:     my %rolenames = (
1.1008    raeburn  9067:                       Course    => 'std',
                   9068:                       Community => 'alt1',
1.1305    raeburn  9069:                       Placement => 'std',
1.742     raeburn  9070:                     );
1.1037    raeburn  9071:     if ($cid ne '') {
                   9072:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9073:             unless ($forcedefault) {
                   9074:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9075:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9076:                 return &Apache::lonlocal::mt($roletext);
                   9077:             }
                   9078:         }
                   9079:     }
                   9080:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9081:         (defined($rolenames{$type})) && 
                   9082:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9083:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9084:     } elsif ($cid ne '') {
                   9085:         my $crstype = $env{'course.'.$cid.'.type'};
                   9086:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9087:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9088:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9089:         }
1.742     raeburn  9090:     }
1.1037    raeburn  9091:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9092: }
                   9093: 
                   9094: # ----------------------------------------------------------------- Assign Role
                   9095: 
                   9096: sub assignrole {
1.957     raeburn  9097:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9098:         $context)=@_;
1.21      www      9099:     my $mrole;
                   9100:     if ($role =~ /^cr\//) {
1.393     www      9101:         my $cwosec=$url;
1.811     albertel 9102:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9103: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9104:            my $refused = 1;
                   9105:            if ($context eq 'requestcourses') {
                   9106:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9107:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9108:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9109:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9110:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9111:                            if ($crsenv{'internal.courseowner'} eq
                   9112:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9113:                                $refused = '';
                   9114:                            }
                   9115:                        }
                   9116:                    }
                   9117:                }
                   9118:            }
                   9119:            if ($refused) {
                   9120:                &logthis('Refused custom assignrole: '.
                   9121:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9122:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9123:                return 'refused';
                   9124:            }
1.104     www      9125:         }
1.21      www      9126:         $mrole='cr';
1.678     raeburn  9127:     } elsif ($role =~ /^gr\//) {
                   9128:         my $cwogrp=$url;
1.811     albertel 9129:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9130:         unless (&allowed('mdg',$cwogrp)) {
                   9131:             &logthis('Refused group assignrole: '.
                   9132:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9133:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9134:             return 'refused';
                   9135:         }
                   9136:         $mrole='gr';
1.21      www      9137:     } else {
1.82      www      9138:         my $cwosec=$url;
1.811     albertel 9139:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9140:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9141:             my $refused;
                   9142:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9143:                 if (!(&allowed('c'.$role,$url))) {
                   9144:                     $refused = 1;
                   9145:                 }
                   9146:             } else {
                   9147:                 $refused = 1;
                   9148:             }
1.947     raeburn  9149:             if ($refused) {
1.1045    raeburn  9150:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9151:                 if (!$selfenroll && $context eq 'course') {
                   9152:                     my %crsenv;
                   9153:                     if ($role eq 'cc' || $role eq 'co') {
                   9154:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9155:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9156:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9157:                                 if ($crsenv{'internal.courseowner'} eq 
                   9158:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9159:                                     $refused = '';
                   9160:                                 }
                   9161:                             }
                   9162:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9163:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9164:                                 if ($crsenv{'internal.courseowner'} eq 
                   9165:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9166:                                     $refused = '';
                   9167:                                 }
                   9168:                             }
                   9169:                         }
                   9170:                     }
                   9171:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9172:                     $refused = '';
1.1017    raeburn  9173:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9174:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9175:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9176:                         my $wrongcc;
                   9177:                         if ($cnum =~ /^$match_community$/) {
                   9178:                             $wrongcc = 1 if ($role eq 'cc');
                   9179:                         } else {
                   9180:                             $wrongcc = 1 if ($role eq 'co');
                   9181:                         }
                   9182:                         unless ($wrongcc) {
                   9183:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9184:                             if ($crsenv{'internal.courseowner'} eq 
                   9185:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9186:                                 $refused = '';
                   9187:                             }
1.1017    raeburn  9188:                         }
                   9189:                     }
1.1183    raeburn  9190:                 } elsif ($context eq 'requestauthor') {
                   9191:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   9192:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9193:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9194:                             $refused = '';
                   9195:                         } else {
                   9196:                             my %domdefaults = &get_domain_defaults($udom);
                   9197:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9198:                                 my $checkbystatus;
                   9199:                                 if ($env{'user.adv'}) { 
                   9200:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9201:                                     if ($disposition eq 'automatic') {
                   9202:                                         $refused = '';
                   9203:                                     } elsif ($disposition eq '') {
                   9204:                                         $checkbystatus = 1;
                   9205:                                     } 
                   9206:                                 } else {
                   9207:                                     $checkbystatus = 1;
                   9208:                                 }
                   9209:                                 if ($checkbystatus) {
                   9210:                                     if ($env{'environment.inststatus'}) {
                   9211:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9212:                                         foreach my $type (@inststatuses) {
                   9213:                                             if (($type ne '') &&
                   9214:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9215:                                                 $refused = '';
                   9216:                                             }
                   9217:                                         }
                   9218:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9219:                                         $refused = '';
                   9220:                                     }
                   9221:                                 }
                   9222:                             }
                   9223:                         }
                   9224:                     }
1.1017    raeburn  9225:                 }
                   9226:                 if ($refused) {
1.947     raeburn  9227:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9228:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9229: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9230:                     return 'refused';
                   9231:                 }
1.932     raeburn  9232:             }
1.1131    raeburn  9233:         } elsif ($role eq 'au') {
                   9234:             if ($url ne '/'.$udom.'/') {
                   9235:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9236:                          ' to assign author role for '.$uname.':'.$udom.
                   9237:                          ' in domain: '.$url.' refused (wrong domain).');
                   9238:                 return 'refused';
                   9239:             }
1.104     www      9240:         }
1.21      www      9241:         $mrole=$role;
                   9242:     }
1.620     albertel 9243:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9244:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9245:     if ($end) { $command.='_'.$end; }
1.21      www      9246:     if ($start) {
                   9247: 	if ($end) { 
1.81      www      9248:            $command.='_'.$start; 
1.21      www      9249:         } else {
1.81      www      9250:            $command.='_0_'.$start;
1.21      www      9251:         }
                   9252:     }
1.739     raeburn  9253:     my $origstart = $start;
                   9254:     my $origend = $end;
1.957     raeburn  9255:     my $delflag;
1.357     www      9256: # actually delete
                   9257:     if ($deleteflag) {
1.373     www      9258: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9259: # modify command to delete the role
1.620     albertel 9260:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9261:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9262: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9263: # set start and finish to negative values for userrolelog
                   9264:            $start=-1;
                   9265:            $end=-1;
1.957     raeburn  9266:            $delflag = 1;
1.357     www      9267:         }
                   9268:     }
                   9269: # send command
1.349     www      9270:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9271: # log new user role if status is ok
1.349     www      9272:     if ($answer eq 'ok') {
1.663     raeburn  9273: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  9274:         if (($role eq 'cc') || ($role eq 'in') ||
                   9275:             ($role eq 'ep') || ($role eq 'ad') ||
                   9276:             ($role eq 'ta') || ($role eq 'st') ||
                   9277:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9278:             ($role eq 'co')) {
1.1200    raeburn  9279: # for course roles, perform group memberships changes triggered by role change.
                   9280:             unless ($role =~ /^gr/) {
                   9281:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9282:                                                  $origstart,$selfenroll,$context);
                   9283:             }
1.1184    raeburn  9284:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9285:                            $selfenroll,$context);
                   9286:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334    raeburn  9287:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9288:                  ($role eq 'da')) {
1.1184    raeburn  9289:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9290:                            $context);
                   9291:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9292:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9293:                              $context); 
                   9294:         }
1.1053    raeburn  9295:         if ($role eq 'cc') {
                   9296:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9297:         }
1.349     www      9298:     }
                   9299:     return $answer;
1.169     harris41 9300: }
                   9301: 
1.1053    raeburn  9302: sub autoupdate_coowners {
                   9303:     my ($url,$end,$start,$uname,$udom) = @_;
                   9304:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9305:     if (($cdom ne '') && ($cnum ne '')) {
                   9306:         my $now = time;
                   9307:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9308:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9309:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9310:             my $instcode = $coursehash{'internal.coursecode'};
                   9311:             if ($instcode ne '') {
1.1056    raeburn  9312:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9313:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9314:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9315:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9316:                         if ($result eq 'valid') {
                   9317:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9318:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9319:                                     push(@newcoowners,$coowner);
                   9320:                                 }
                   9321:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9322:                                     push(@newcoowners,$uname.':'.$udom);
                   9323:                                 }
                   9324:                                 @newcoowners = sort(@newcoowners);
                   9325:                             } else {
                   9326:                                 push(@newcoowners,$uname.':'.$udom);
                   9327:                             }
                   9328:                         } else {
                   9329:                             if ($coursehash{'internal.co-owners'}) {
                   9330:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9331:                                     unless ($coowner eq $uname.':'.$udom) {
                   9332:                                         push(@newcoowners,$coowner);
                   9333:                                     }
                   9334:                                 }
                   9335:                                 unless (@newcoowners > 0) {
                   9336:                                     $delcoowners = 1;
                   9337:                                     $coowners = '';
                   9338:                                 }
                   9339:                             }
                   9340:                         }
                   9341:                         if (@newcoowners || $delcoowners) {
                   9342:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9343:                                             $delcoowners,@newcoowners);
                   9344:                         }
                   9345:                     }
                   9346:                 }
                   9347:             }
                   9348:         }
                   9349:     }
                   9350: }
                   9351: 
                   9352: sub store_coowners {
                   9353:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9354:     my $cid = $cdom.'_'.$cnum;
                   9355:     my ($coowners,$delresult,$putresult);
                   9356:     if (@newcoowners) {
                   9357:         $coowners = join(',',@newcoowners);
                   9358:         my %coownershash = (
                   9359:                             'internal.co-owners' => $coowners,
                   9360:                            );
                   9361:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9362:         if ($putresult eq 'ok') {
                   9363:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9364:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9365:             }
                   9366:         }
                   9367:     }
                   9368:     if ($delcoowners) {
                   9369:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9370:         if ($delresult eq 'ok') {
                   9371:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9372:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9373:             }
                   9374:         }
                   9375:     }
                   9376:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9377:         my %crsinfo =
                   9378:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9379:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9380:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9381:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9382:         }
                   9383:     }
                   9384: }
                   9385: 
1.169     harris41 9386: # -------------------------------------------------- Modify user authentication
1.197     www      9387: # Overrides without validation
                   9388: 
1.169     harris41 9389: sub modifyuserauth {
                   9390:     my ($udom,$uname,$umode,$upass)=@_;
                   9391:     my $uhome=&homeserver($uname,$udom);
1.197     www      9392:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9393:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9394:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9395:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9396:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9397: 		     &escape($upass),$uhome);
1.620     albertel 9398:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9399:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9400:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9401:     &log($udom,,$uname,$uhome,
1.620     albertel 9402:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9403:                                      $env{'user.name'}.', '.$umode.
1.197     www      9404:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9405:     unless ($reply eq 'ok') {
1.197     www      9406:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9407: 	return 'error: '.$reply;
                   9408:     }   
1.170     harris41 9409:     return 'ok';
1.80      www      9410: }
                   9411: 
1.81      www      9412: # --------------------------------------------------------------- Modify a user
1.80      www      9413: 
1.81      www      9414: sub modifyuser {
1.206     matthew  9415:     my ($udom,    $uname, $uid,
                   9416:         $umode,   $upass, $first,
                   9417:         $middle,  $last,  $gene,
1.1058    raeburn  9418:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9419:     $udom= &LONCAPA::clean_domain($udom);
                   9420:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9421:     my $showcandelete = 'none';
                   9422:     if (ref($candelete) eq 'ARRAY') {
                   9423:         if (@{$candelete} > 0) {
                   9424:             $showcandelete = join(', ',@{$candelete});
                   9425:         }
                   9426:     }
1.81      www      9427:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9428:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9429: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9430:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9431:                                      ' desiredhome not specified'). 
1.620     albertel 9432:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9433:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9434:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9435:     my $newuser;
                   9436:     if ($uhome eq 'no_host') {
                   9437:         $newuser = 1;
                   9438:     }
1.80      www      9439: # ----------------------------------------------------------------- Create User
1.406     albertel 9440:     if (($uhome eq 'no_host') && 
                   9441: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9442:         my $unhome='';
1.844     albertel 9443:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9444:             $unhome = $desiredhome;
1.620     albertel 9445: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9446: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9447:         } else { # load balancing routine for determining $unhome
1.81      www      9448:             my $loadm=10000000;
1.841     albertel 9449: 	    my %servers = &get_servers($udom,'library');
                   9450: 	    foreach my $tryserver (keys(%servers)) {
                   9451: 		my $answer=reply('load',$tryserver);
                   9452: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9453: 		    $loadm=$answer;
                   9454: 		    $unhome=$tryserver;
                   9455: 		}
1.80      www      9456: 	    }
                   9457:         }
                   9458:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9459: 	    return 'error: unable to find a home server for '.$uname.
                   9460:                    ' in domain '.$udom;
1.80      www      9461:         }
                   9462:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9463:                          &escape($upass),$unhome);
                   9464: 	unless ($reply eq 'ok') {
                   9465:             return 'error: '.$reply;
                   9466:         }   
1.230     stredwic 9467:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9468:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9469: 	    return 'error: unable verify users home machine.';
1.80      www      9470:         }
1.209     matthew  9471:     }   # End of creation of new user
1.80      www      9472: # ---------------------------------------------------------------------- Add ID
                   9473:     if ($uid) {
                   9474:        $uid=~tr/A-Z/a-z/;
                   9475:        my %uidhash=&idrget($udom,$uname);
1.196     www      9476:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9477:          && (!$forceid)) {
1.80      www      9478: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9479: 	      return 'error: user id "'.$uid.'" does not match '.
                   9480:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9481:           }
                   9482:        } else {
1.1300    raeburn  9483: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      9484:        }
                   9485:     }
                   9486: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9487:     my @tmp=&get('environment',
1.899     raeburn  9488: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9489:                     'permanentemail','inststatus'],
1.134     albertel 9490: 		   $udom,$uname);
1.1075    raeburn  9491:     my (%names,%oldnames);
1.313     matthew  9492:     if ($tmp[0] =~ m/^error:.*/) { 
                   9493:         %names=(); 
                   9494:     } else {
                   9495:         %names = @tmp;
1.1075    raeburn  9496:         %oldnames = %names;
1.313     matthew  9497:     }
1.388     www      9498: #
1.1058    raeburn  9499: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9500: # of users did not contain them), do not overwrite existing values
                   9501: # unless field is in $candelete array ref.  
                   9502: #
                   9503: 
                   9504:     my @fields = ('firstname','middlename','lastname','generation',
                   9505:                   'permanentemail','id');
                   9506:     my %newvalues;
                   9507:     if (ref($candelete) eq 'ARRAY') {
                   9508:         foreach my $field (@fields) {
                   9509:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9510:                 if ($field eq 'firstname') {
                   9511:                     $names{$field} = $first;
                   9512:                 } elsif ($field eq 'middlename') {
                   9513:                     $names{$field} = $middle;
                   9514:                 } elsif ($field eq 'lastname') {
                   9515:                     $names{$field} = $last;
                   9516:                 } elsif ($field eq 'generation') { 
                   9517:                     $names{$field} = $gene;
                   9518:                 } elsif ($field eq 'permanentemail') {
                   9519:                     $names{$field} = $email;
                   9520:                 } elsif ($field eq 'id') {
                   9521:                     $names{$field}  = $uid;
                   9522:                 }
                   9523:             }
                   9524:         }
                   9525:     }
1.388     www      9526:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9527:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9528:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9529:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9530:     if ($email) {
                   9531:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9532:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9533:     }
1.899     raeburn  9534:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9535:     if (defined($inststatus)) {
                   9536:         $names{'inststatus'} = '';
                   9537:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9538:         if (ref($usertypes) eq 'HASH') {
                   9539:             my @okstatuses; 
                   9540:             foreach my $item (split(/:/,$inststatus)) {
                   9541:                 if (defined($usertypes->{$item})) {
                   9542:                     push(@okstatuses,$item);  
                   9543:                 }
                   9544:             }
                   9545:             if (@okstatuses) {
                   9546:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9547:             }
                   9548:         }
                   9549:     }
1.1075    raeburn  9550:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9551:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9552:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9553:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9554:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9555:     } else {
                   9556:         $logmsg .= ' during self creation';
                   9557:     }
1.1075    raeburn  9558:     my $changed;
                   9559:     if ($newuser) {
                   9560:         $changed = 1;
                   9561:     } else {
                   9562:         foreach my $field (@fields) {
                   9563:             if ($names{$field} ne $oldnames{$field}) {
                   9564:                 $changed = 1;
                   9565:                 last;
                   9566:             }
                   9567:         }
                   9568:     }
                   9569:     unless ($changed) {
                   9570:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9571:         &logthis($logmsg);
                   9572:         return 'ok';
                   9573:     }
                   9574:     my $reply = &put('environment', \%names, $udom,$uname);
                   9575:     if ($reply ne 'ok') { 
                   9576:         return 'error: '.$reply;
                   9577:     }
1.1087    raeburn  9578:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9579:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9580:     }
1.1075    raeburn  9581:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9582:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9583:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9584:     &logthis($logmsg);
1.134     albertel 9585:     return 'ok';
1.80      www      9586: }
                   9587: 
1.81      www      9588: # -------------------------------------------------------------- Modify student
1.80      www      9589: 
1.81      www      9590: sub modifystudent {
                   9591:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9592:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  9593:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9594:     if (!$cid) {
1.620     albertel 9595: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9596: 	    return 'not_in_class';
                   9597: 	}
1.80      www      9598:     }
                   9599: # --------------------------------------------------------------- Make the user
1.81      www      9600:     my $reply=&modifyuser
1.209     matthew  9601: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9602:          $desiredhome,$email,$inststatus);
1.80      www      9603:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9604:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  9605:     # student's environment
1.297     matthew  9606:     $uid = undef if (!$forceid);
1.455     albertel 9607:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  9608:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  9609:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9610:     return $reply;
                   9611: }
                   9612: 
                   9613: sub modify_student_enrollment {
1.1216    raeburn  9614:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  9615:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9616:     my ($cdom,$cnum,$chome);
                   9617:     if (!$cid) {
1.620     albertel 9618: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9619: 	    return 'not_in_class';
                   9620: 	}
1.620     albertel 9621: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9622: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9623:     } else {
                   9624: 	($cdom,$cnum)=split(/_/,$cid);
                   9625:     }
1.620     albertel 9626:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9627:     if (!$chome) {
1.457     raeburn  9628: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9629:     }
1.455     albertel 9630:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9631:     # Make sure the user exists
1.81      www      9632:     my $uhome=&homeserver($uname,$udom);
                   9633:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9634: 	return 'error: no such user';
                   9635:     }
1.297     matthew  9636:     # Get student data if we were not given enough information
                   9637:     if (!defined($first)  || $first  eq '' || 
                   9638:         !defined($last)   || $last   eq '' || 
                   9639:         !defined($uid)    || $uid    eq '' || 
                   9640:         !defined($middle) || $middle eq '' || 
                   9641:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9642:         # They did not supply us with enough data to enroll the student, so
                   9643:         # we need to pick up more information.
1.297     matthew  9644:         my %tmp = &get('environment',
1.294     matthew  9645:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9646:                        ,$udom,$uname);
                   9647: 
1.800     albertel 9648:         #foreach my $key (keys(%tmp)) {
                   9649:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9650:         #}
1.294     matthew  9651:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9652:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9653:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9654:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9655:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9656:     }
1.556     albertel 9657:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9658:     my $user = "$uname:$udom";
                   9659:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9660:     my $reply=cput('classlist',
1.1148    raeburn  9661: 		   {$user => 
1.1314    raeburn  9662: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9663: 		   $cdom,$cnum);
1.1148    raeburn  9664:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9665:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9666:     } else { 
1.81      www      9667: 	return 'error: '.$reply;
                   9668:     }
1.297     matthew  9669:     # Add student role to user
1.83      www      9670:     my $uurl='/'.$cid;
1.81      www      9671:     $uurl=~s/\_/\//g;
                   9672:     if ($usec) {
                   9673: 	$uurl.='/'.$usec;
                   9674:     }
1.1148    raeburn  9675:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9676:                              $selfenroll,$context);
                   9677:     if ($result ne 'ok') {
                   9678:         if ($old_entry{$user} ne '') {
                   9679:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9680:         } else {
                   9681:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9682:         }
                   9683:     }
                   9684:     return $result; 
1.21      www      9685: }
                   9686: 
1.556     albertel 9687: sub format_name {
                   9688:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9689:     my $name;
                   9690:     if ($first ne 'lastname') {
                   9691: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9692:     } else {
                   9693: 	if ($lastname=~/\S/) {
                   9694: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9695: 	    $name=~s/\s+,/,/;
                   9696: 	} else {
                   9697: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9698: 	}
                   9699:     }
                   9700:     $name=~s/^\s+//;
                   9701:     $name=~s/\s+$//;
                   9702:     $name=~s/\s+/ /g;
                   9703:     return $name;
                   9704: }
                   9705: 
1.84      www      9706: # ------------------------------------------------- Write to course preferences
                   9707: 
                   9708: sub writecoursepref {
                   9709:     my ($courseid,%prefs)=@_;
                   9710:     $courseid=~s/^\///;
                   9711:     $courseid=~s/\_/\//g;
                   9712:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9713:     my $chome=homeserver($cnum,$cdomain);
                   9714:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9715: 	return 'error: no such course';
                   9716:     }
                   9717:     my $cstring='';
1.800     albertel 9718:     foreach my $pref (keys(%prefs)) {
                   9719: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9720:     }
1.84      www      9721:     $cstring=~s/\&$//;
                   9722:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9723: }
                   9724: 
                   9725: # ---------------------------------------------------------- Make/modify course
                   9726: 
                   9727: sub createcourse {
1.741     raeburn  9728:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9729:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9730:     $url=&declutter($url);
                   9731:     my $cid='';
1.1028    raeburn  9732:     if ($context eq 'requestcourses') {
                   9733:         my $can_create = 0;
                   9734:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9735:         if ($udom eq $ownerdom) {
                   9736:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9737:                                   $context)) {
                   9738:                 $can_create = 1;
                   9739:             }
                   9740:         } else {
                   9741:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9742:                                            $category);
                   9743:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9744:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9745:                 if (@curr > 0) {
                   9746:                     my @options = qw(approval validate autolimit);
                   9747:                     my $optregex = join('|',@options);
                   9748:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9749:                         $can_create = 1;
                   9750:                     }
                   9751:                 }
                   9752:             }
                   9753:         }
                   9754:         if ($can_create) {
                   9755:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9756:                 unless (&allowed('ccc',$udom)) {
                   9757:                     return 'refused'; 
                   9758:                 }
1.1017    raeburn  9759:             }
                   9760:         } else {
                   9761:             return 'refused';
                   9762:         }
1.1028    raeburn  9763:     } elsif (!&allowed('ccc',$udom)) {
                   9764:         return 'refused';
1.84      www      9765:     }
1.1011    raeburn  9766: # --------------------------------------------------------------- Get Unique ID
                   9767:     my $uname;
                   9768:     if ($cnum =~ /^$match_courseid$/) {
                   9769:         my $chome=&homeserver($cnum,$udom,'true');
                   9770:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9771:             $uname = $cnum;
                   9772:         } else {
1.1038    raeburn  9773:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9774:         }
                   9775:     } else {
1.1038    raeburn  9776:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9777:     }
                   9778:     return $uname if ($uname =~ /^error/);
                   9779: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9780:     if (!defined($course_server)) {
                   9781:         if (defined(&domain($udom,'primary'))) {
                   9782:             $course_server = &domain($udom,'primary');
                   9783:         } else {
                   9784:             $course_server = $env{'user.home'}; 
                   9785:         }
                   9786:     }
                   9787:     my %host_servers =
                   9788:         &Apache::lonnet::get_servers($udom,'library');
                   9789:     unless ($host_servers{$course_server}) {
                   9790:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9791:     }
1.84      www      9792: # ------------------------------------------------------------- Make the course
                   9793:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9794:                       $course_server);
1.84      www      9795:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9796:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9797:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9798: 	return 'error: no such course';
                   9799:     }
1.271     www      9800: # ----------------------------------------------------------------- Course made
1.516     raeburn  9801: # log existence
1.1029    raeburn  9802:     my $now = time;
1.918     raeburn  9803:     my $newcourse = {
                   9804:                     $udom.'_'.$uname => {
1.921     raeburn  9805:                                      description => $description,
                   9806:                                      inst_code   => $inst_code,
                   9807:                                      owner       => $course_owner,
                   9808:                                      type        => $crstype,
1.1029    raeburn  9809:                                      creator     => $env{'user.name'}.':'.
                   9810:                                                     $env{'user.domain'},
                   9811:                                      created     => $now,
                   9812:                                      context     => $context,
1.918     raeburn  9813:                                                 },
                   9814:                     };
1.921     raeburn  9815:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9816: # set toplevel url
1.271     www      9817:     my $topurl=$url;
                   9818:     unless ($nonstandard) {
                   9819: # ------------------------------------------ For standard courses, make top url
                   9820:         my $mapurl=&clutter($url);
1.278     www      9821:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9822:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9823: <map>
                   9824: <resource id="1" type="start"></resource>
                   9825: <resource id="2" src="$mapurl"></resource>
                   9826: <resource id="3" type="finish"></resource>
                   9827: <link index="1" from="1" to="2"></link>
                   9828: <link index="2" from="2" to="3"></link>
                   9829: </map>
                   9830: ENDINITMAP
                   9831:         $topurl=&declutter(
1.638     albertel 9832:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9833:                           );
                   9834:     }
                   9835: # ----------------------------------------------------------- Write preferences
1.84      www      9836:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9837:                      ('description'              => $description,
                   9838:                       'url'                      => $topurl,
                   9839:                       'internal.creator'         => $env{'user.name'}.':'.
                   9840:                                                     $env{'user.domain'},
                   9841:                       'internal.created'         => $now,
                   9842:                       'internal.creationcontext' => $context)
                   9843:                     );
1.84      www      9844:     return '/'.$udom.'/'.$uname;
                   9845: }
                   9846: 
1.1011    raeburn  9847: # ------------------------------------------------------------------- Create ID
                   9848: sub generate_coursenum {
1.1038    raeburn  9849:     my ($udom,$crstype) = @_;
1.1011    raeburn  9850:     my $domdesc = &domain($udom);
                   9851:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9852:     my $first;
                   9853:     if ($crstype eq 'Community') {
                   9854:         $first = '0';
                   9855:     } else {
                   9856:         $first = int(1+rand(9)); 
                   9857:     } 
                   9858:     my $uname=$first.
1.1011    raeburn  9859:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9860:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9861:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9862: # ----------------------------------------------- Make sure that does not exist
                   9863:     my $uhome=&homeserver($uname,$udom,'true');
                   9864:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9865:         if ($crstype eq 'Community') {
                   9866:             $first = '0';
                   9867:         } else {
                   9868:             $first = int(1+rand(9));
                   9869:         }
                   9870:         $uname=$first.
1.1011    raeburn  9871:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9872:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9873:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9874:         $uhome=&homeserver($uname,$udom,'true');
                   9875:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9876:             return 'error: unable to generate unique course-ID';
                   9877:         }
                   9878:     }
                   9879:     return $uname;
                   9880: }
                   9881: 
1.813     albertel 9882: sub is_course {
1.1167    droeschl 9883:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9884:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   9885: 
                   9886:     return unless $cdom and $cnum;
                   9887: 
                   9888:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   9889:         '.');
                   9890: 
1.1219    raeburn  9891:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 9892:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9893: }
                   9894: 
1.1015    raeburn  9895: sub store_userdata {
                   9896:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9897:     my $result;
1.1016    raeburn  9898:     if ($datakey ne '') {
1.1013    raeburn  9899:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9900:             if ($udom eq '' || $uname eq '') {
                   9901:                 $udom = $env{'user.domain'};
                   9902:                 $uname = $env{'user.name'};
                   9903:             }
                   9904:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9905:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9906:                 $result = 'error: no_host';
                   9907:             } else {
                   9908:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9909:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9910: 
                   9911:                 my $namevalue='';
                   9912:                 foreach my $key (keys(%{$storehash})) {
                   9913:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9914:                 }
                   9915:                 $namevalue=~s/\&$//;
1.1224    raeburn  9916:                 unless ($namespace eq 'courserequests') {
                   9917:                     $datakey = &escape($datakey);
                   9918:                 }
1.1105    raeburn  9919:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9920:                                   $namevalue,$uhome);
1.1013    raeburn  9921:             }
                   9922:         } else {
                   9923:             $result = 'error: data to store was not a hash reference'; 
                   9924:         }
                   9925:     } else {
                   9926:         $result= 'error: invalid requestkey'; 
                   9927:     }
                   9928:     return $result;
                   9929: }
                   9930: 
1.21      www      9931: # ---------------------------------------------------------- Assign Custom Role
                   9932: 
                   9933: sub assigncustomrole {
1.957     raeburn  9934:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9935:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9936:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9937: }
                   9938: 
                   9939: # ----------------------------------------------------------------- Revoke Role
                   9940: 
                   9941: sub revokerole {
1.957     raeburn  9942:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9943:     my $now=time;
1.965     raeburn  9944:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9945: }
                   9946: 
                   9947: # ---------------------------------------------------------- Revoke Custom Role
                   9948: 
                   9949: sub revokecustomrole {
1.957     raeburn  9950:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9951:     my $now=time;
1.357     www      9952:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9953:            $deleteflag,$selfenroll,$context);
1.17      www      9954: }
                   9955: 
1.533     banghart 9956: # ------------------------------------------------------------ Disk usage
1.535     albertel 9957: sub diskusage {
1.955     raeburn  9958:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9959:     $directorypath =~ s/\/$//;
                   9960:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9961:                        .&escape($getpropath).':'.&escape($uname).':'
                   9962:                        .&escape($udom),homeserver($uname,$udom));
                   9963:     if ($listing eq 'unknown_cmd') {
                   9964:         if ($getpropath) {
                   9965:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9966:         }
                   9967:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9968:     }
1.514     albertel 9969:     return $listing;
1.512     banghart 9970: }
                   9971: 
1.566     banghart 9972: sub is_locked {
1.1096    raeburn  9973:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9974:     my @check;
                   9975:     my $is_locked;
1.1093    raeburn  9976:     push (@check,$file_name);
1.613     albertel 9977:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9978: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9979:     my ($tmp)=keys(%locked);
                   9980:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9981:     
1.566     banghart 9982:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9983:         $is_locked = 'false';
                   9984:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9985:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9986:                $is_locked = 'true';
1.1096    raeburn  9987:                if (ref($which) eq 'ARRAY') {
                   9988:                    push(@{$which},$entry);
                   9989:                } else {
                   9990:                    last;
                   9991:                }
1.745     raeburn  9992:            }
                   9993:        }
1.566     banghart 9994:     } else {
                   9995:         $is_locked = 'false';
                   9996:     }
1.1093    raeburn  9997:     return $is_locked;
1.566     banghart 9998: }
                   9999: 
1.759     albertel 10000: sub declutter_portfile {
                   10001:     my ($file) = @_;
1.833     albertel 10002:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10003:     return $file;
                   10004: }
                   10005: 
1.559     banghart 10006: # ------------------------------------------------------------- Mark as Read Only
                   10007: 
                   10008: sub mark_as_readonly {
                   10009:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10010:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10011:     my ($tmp)=keys(%current_permissions);
                   10012:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10013:     foreach my $file (@{$files}) {
1.759     albertel 10014: 	$file = &declutter_portfile($file);
1.561     banghart 10015:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10016:     }
1.613     albertel 10017:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10018:     return;
                   10019: }
                   10020: 
1.572     banghart 10021: # ------------------------------------------------------------Save Selected Files
                   10022: 
                   10023: sub save_selected_files {
                   10024:     my ($user, $path, @files) = @_;
                   10025:     my $filename = $user."savedfiles";
1.573     banghart 10026:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 10027:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 10028:     foreach my $file (@files) {
1.620     albertel 10029:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10030:     }
                   10031:     foreach my $file (@other_files) {
1.574     banghart 10032:         print (OUT $file."\n");
1.572     banghart 10033:     }
1.574     banghart 10034:     close (OUT);
1.572     banghart 10035:     return 'ok';
                   10036: }
                   10037: 
1.574     banghart 10038: sub clear_selected_files {
                   10039:     my ($user) = @_;
                   10040:     my $filename = $user."savedfiles";
1.1117    foxr     10041:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 10042:     print (OUT undef);
                   10043:     close (OUT);
                   10044:     return ("ok");    
                   10045: }
                   10046: 
1.572     banghart 10047: sub files_in_path {
                   10048:     my ($user, $path) = @_;
                   10049:     my $filename = $user."savedfiles";
                   10050:     my %return_files;
1.1117    foxr     10051:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 10052:     while (my $line_in = <IN>) {
1.574     banghart 10053:         chomp ($line_in);
                   10054:         my @paths_and_file = split (m!/!, $line_in);
                   10055:         my $file_part = pop (@paths_and_file);
                   10056:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10057:         $path_part.='/';
                   10058:         my $path_and_file = $path_part.$file_part;
                   10059:         if ($path_part eq $path) {
                   10060:             $return_files{$file_part}= 'selected';
                   10061:         }
                   10062:     }
1.574     banghart 10063:     close (IN);
                   10064:     return (\%return_files);
1.572     banghart 10065: }
                   10066: 
                   10067: # called in portfolio select mode, to show files selected NOT in current directory
                   10068: sub files_not_in_path {
                   10069:     my ($user, $path) = @_;
                   10070:     my $filename = $user."savedfiles";
                   10071:     my @return_files;
                   10072:     my $path_part;
1.1117    foxr     10073:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 10074:     while (my $line = <IN>) {
1.572     banghart 10075:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10076:         my @paths_and_file = split(m|/|, $line);
                   10077:         my $file_part = pop(@paths_and_file);
                   10078:         chomp($file_part);
                   10079:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10080:         $path_part .= '/';
                   10081:         my $path_and_file = $path_part.$file_part;
                   10082:         if ($path_part ne $path) {
1.800     albertel 10083:             push(@return_files, ($path_and_file));
1.572     banghart 10084:         }
                   10085:     }
1.800     albertel 10086:     close(OUT);
1.574     banghart 10087:     return (@return_files);
1.572     banghart 10088: }
                   10089: 
1.1273    raeburn  10090: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   10091:  
                   10092: sub portfiles_versioning {
                   10093:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   10094:     my $portfolio_root = '/userfiles/portfolio';
                   10095:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   10096:     foreach my $file (@{$portfiles}) {
                   10097:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   10098:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   10099:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   10100:         my $getpropath = 1;
                   10101:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   10102:                                              $stu_name,$getpropath);
                   10103:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   10104:         my $new_answer = 
                   10105:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   10106:         if ($new_answer ne 'problem getting file') {
                   10107:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   10108:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   10109:                               [$symb,$env{'request.course.id'},'graded']);
                   10110:         }
                   10111:     }
                   10112: }
                   10113: 
                   10114: sub get_next_version {
                   10115:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   10116:     my $version;
                   10117:     if (ref($dir_list) eq 'ARRAY') {
                   10118:         foreach my $row (@{$dir_list}) {
                   10119:             my ($file) = split(/\&/,$row,2);
                   10120:             my ($file_name,$file_version,$file_ext) =
                   10121:                 &file_name_version_ext($file);
                   10122:             if (($file_name eq $answer_name) &&
                   10123:                 ($file_ext eq $answer_ext)) {
                   10124:                      # gets here if filename and extension match,
                   10125:                      # regardless of version
                   10126:                 if ($file_version ne '') {
                   10127:                     # a versioned file is found  so save it for later
                   10128:                     if ($file_version > $version) {
                   10129:                         $version = $file_version;
                   10130:                     }
                   10131:                 }
                   10132:             }
                   10133:         }
                   10134:     }
                   10135:     $version ++;
                   10136:     return($version);
                   10137: }
                   10138: 
                   10139: sub version_selected_portfile {
                   10140:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   10141:     my ($answer_name,$answer_ver,$answer_ext) =
                   10142:         &file_name_version_ext($file_name);
                   10143:     my $new_answer;
                   10144:     $env{'form.copy'} =
                   10145:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   10146:     if($env{'form.copy'} eq '-1') {
                   10147:         $new_answer = 'problem getting file';
                   10148:     } else {
                   10149:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   10150:         my $copy_result = 
                   10151:             &finishuserfileupload($stu_name,$domain,'copy',
                   10152:                                   '/portfolio'.$directory.$new_answer);
                   10153:     }
                   10154:     undef($env{'form.copy'});
                   10155:     return ($new_answer);
                   10156: }
                   10157: 
                   10158: sub file_name_version_ext {
                   10159:     my ($file)=@_;
                   10160:     my @file_parts = split(/\./, $file);
                   10161:     my ($name,$version,$ext);
                   10162:     if (@file_parts > 1) {
                   10163:         $ext=pop(@file_parts);
                   10164:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   10165:             $version=pop(@file_parts);
                   10166:         }
                   10167:         $name=join('.',@file_parts);
                   10168:     } else {
                   10169:         $name=join('.',@file_parts);
                   10170:     }
                   10171:     return($name,$version,$ext);
                   10172: }
                   10173: 
1.745     raeburn  10174: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10175: 
1.745     raeburn  10176: sub get_portfile_permissions {
                   10177:     my ($domain,$user) = @_;
1.613     albertel 10178:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10179:     my ($tmp)=keys(%current_permissions);
                   10180:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10181:     return \%current_permissions;
                   10182: }
                   10183: 
                   10184: #---------------------------------------------Get portfolio file access controls
                   10185: 
1.749     raeburn  10186: sub get_access_controls {
1.745     raeburn  10187:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10188:     my %access;
                   10189:     my $real_file = $file;
                   10190:     $file =~ s/\.meta$//;
1.745     raeburn  10191:     if (defined($file)) {
1.749     raeburn  10192:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10193:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10194:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10195:             }
                   10196:         }
1.745     raeburn  10197:     } else {
1.749     raeburn  10198:         foreach my $key (keys(%{$current_permissions})) {
                   10199:             if ($key =~ /\0accesscontrol$/) {
                   10200:                 if (defined($group)) {
                   10201:                     if ($key !~ m-^\Q$group\E/-) {
                   10202:                         next;
                   10203:                     }
                   10204:                 }
                   10205:                 my ($fullpath) = split(/\0/,$key);
                   10206:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10207:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10208:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10209:                     }
                   10210:                 }
                   10211:             }
                   10212:         }
                   10213:     }
                   10214:     return %access;
                   10215: }
                   10216: 
                   10217: sub modify_access_controls {
                   10218:     my ($file_name,$changes,$domain,$user)=@_;
                   10219:     my ($outcome,$deloutcome);
                   10220:     my %store_permissions;
                   10221:     my %new_values;
                   10222:     my %new_control;
                   10223:     my %translation;
                   10224:     my @deletions = ();
                   10225:     my $now = time;
                   10226:     if (exists($$changes{'activate'})) {
                   10227:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10228:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10229:             my $numnew = scalar(@newitems);
                   10230:             for (my $i=0; $i<$numnew; $i++) {
                   10231:                 my $newkey = $newitems[$i];
                   10232:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10233:                 if ($newkey =~ /^\d+:/) { 
                   10234:                     $newkey =~ s/^(\d+)/$newid/;
                   10235:                     $translation{$1} = $newid;
                   10236:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10237:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10238:                     $translation{$1} = $newid;
                   10239:                 }
1.749     raeburn  10240:                 $new_values{$file_name."\0".$newkey} = 
                   10241:                                           $$changes{'activate'}{$newitems[$i]};
                   10242:                 $new_control{$newkey} = $now;
                   10243:             }
                   10244:         }
                   10245:     }
                   10246:     my %todelete;
                   10247:     my %changed_items;
                   10248:     foreach my $action ('delete','update') {
                   10249:         if (exists($$changes{$action})) {
                   10250:             if (ref($$changes{$action}) eq 'HASH') {
                   10251:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10252:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10253:                     if ($action eq 'delete') { 
                   10254:                         $todelete{$itemnum} = 1;
                   10255:                     } else {
                   10256:                         $changed_items{$itemnum} = $key;
                   10257:                     }
                   10258:                 }
1.745     raeburn  10259:             }
                   10260:         }
1.749     raeburn  10261:     }
                   10262:     # get lock on access controls for file.
                   10263:     my $lockhash = {
                   10264:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10265:                                                        ':'.$env{'user.domain'},
                   10266:                    }; 
                   10267:     my $tries = 0;
                   10268:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10269:    
1.1288    damieng  10270:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10271:         $tries ++;
1.1289    damieng  10272:         sleep(0.1);
1.749     raeburn  10273:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10274:     }
                   10275:     if ($gotlock eq 'ok') {
                   10276:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10277:         my ($tmp)=keys(%curr_permissions);
                   10278:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10279:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10280:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10281:             if (ref($curr_controls) eq 'HASH') {
                   10282:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10283:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10284:                     if (defined($todelete{$itemnum})) {
                   10285:                         push(@deletions,$file_name."\0".$control_item);
                   10286:                     } else {
                   10287:                         if (defined($changed_items{$itemnum})) {
                   10288:                             $new_control{$changed_items{$itemnum}} = $now;
                   10289:                             push(@deletions,$file_name."\0".$control_item);
                   10290:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10291:                         } else {
                   10292:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10293:                         }
                   10294:                     }
1.745     raeburn  10295:                 }
                   10296:             }
                   10297:         }
1.970     raeburn  10298:         my ($group);
                   10299:         if (&is_course($domain,$user)) {
                   10300:             ($group,my $file) = split(/\//,$file_name,2);
                   10301:         }
1.749     raeburn  10302:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10303:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10304:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10305:         #  remove lock
                   10306:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10307:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10308:         my $sqlresult =
1.970     raeburn  10309:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10310:                                     $group);
1.749     raeburn  10311:     } else {
                   10312:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10313:     }
1.749     raeburn  10314:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10315: }
                   10316: 
1.827     raeburn  10317: sub make_public_indefinitely {
1.1271    raeburn  10318:     my (@requrl) = @_;
                   10319:     return &automated_portfile_access('public',\@requrl);
                   10320: }
                   10321: 
                   10322: sub automated_portfile_access {
                   10323:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  10324:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   10325:         return 'invalid';
                   10326:     }
1.1271    raeburn  10327:     my %urls;
                   10328:     if (ref($addsref) eq 'ARRAY') {
                   10329:         foreach my $requrl (@{$addsref}) {
                   10330:             if (&is_portfolio_url($requrl)) {
                   10331:                 unless (exists($urls{$requrl})) {
                   10332:                     $urls{$requrl} = 'add';
                   10333:                 }
                   10334:             }
                   10335:         }
                   10336:     }
                   10337:     if (ref($delsref) eq 'ARRAY') {
                   10338:         foreach my $requrl (@{$delsref}) { 
                   10339:             if (&is_portfolio_url($requrl)) {
                   10340:                 unless (exists($urls{$requrl})) {
                   10341:                     $urls{$requrl} = 'delete'; 
                   10342:                 }
                   10343:             }
                   10344:         }
                   10345:     }
                   10346:     unless (keys(%urls)) {
                   10347:         return 'invalid';
                   10348:     }
                   10349:     my $ip;
                   10350:     if ($accesstype eq 'ip') {
                   10351:         if (ref($info) eq 'HASH') {
                   10352:             if ($info->{'ip'} ne '') {
                   10353:                 $ip = $info->{'ip'};
                   10354:             }
                   10355:         }
                   10356:         if ($ip eq '') {
                   10357:             return 'invalid';
                   10358:         }
                   10359:     }
                   10360:     my $errors;
1.827     raeburn  10361:     my $now = time;
1.1271    raeburn  10362:     my %current_perms;
                   10363:     foreach my $requrl (sort(keys(%urls))) {
                   10364:         my $action;
                   10365:         if ($urls{$requrl} eq 'add') {
                   10366:             $action = 'activate';
                   10367:         } else {
                   10368:             $action = 'none';
                   10369:         }
                   10370:         my $aclnum = 0;
1.827     raeburn  10371:         my (undef,$udom,$unum,$file_name,$group) =
                   10372:             &parse_portfolio_url($requrl);
1.1271    raeburn  10373:         unless (exists($current_perms{$unum.':'.$udom})) {
                   10374:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   10375:         }
                   10376:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  10377:                                                    $group,$file_name);
                   10378:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10379:             my ($num,$scope,$end,$start) = 
                   10380:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  10381:             if ($scope eq $accesstype) {
                   10382:                 if (($start <= $now) && ($end == 0)) {
                   10383:                     if ($accesstype eq 'ip') {
                   10384:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   10385:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   10386:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   10387:                                     if ($urls{$requrl} eq 'add') {
                   10388:                                         $action = 'none';
                   10389:                                         last;
                   10390:                                     } else {
                   10391:                                         $action = 'delete';
                   10392:                                         $aclnum = $num;
                   10393:                                         last;
                   10394:                                     }
                   10395:                                 }
                   10396:                             }
                   10397:                         }
                   10398:                     } elsif ($accesstype eq 'public') {
                   10399:                         if ($urls{$requrl} eq 'add') {
                   10400:                             $action = 'none';
                   10401:                             last;
                   10402:                         } else {
                   10403:                             $action = 'delete';
                   10404:                             $aclnum = $num;
                   10405:                             last;
                   10406:                         }
                   10407:                     }
                   10408:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  10409:                     $action = 'update';
                   10410:                     $aclnum = $num;
1.1271    raeburn  10411:                     last;
1.827     raeburn  10412:                 }
                   10413:             }
                   10414:         }
                   10415:         if ($action eq 'none') {
1.1271    raeburn  10416:             next;
1.827     raeburn  10417:         } else {
                   10418:             my %changes;
                   10419:             my $newend = 0;
                   10420:             my $newstart = $now;
1.1271    raeburn  10421:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  10422:             $changes{$action}{$newkey} = {
1.1271    raeburn  10423:                 type => $accesstype,
1.827     raeburn  10424:                 time => {
                   10425:                     start => $newstart,
                   10426:                     end   => $newend,
                   10427:                 },
                   10428:             };
1.1271    raeburn  10429:             if ($accesstype eq 'ip') {
                   10430:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   10431:             }
1.827     raeburn  10432:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10433:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  10434:             unless ($outcome eq 'ok') {
                   10435:                 $errors .= $outcome.' ';
                   10436:             }
1.827     raeburn  10437:         }
1.1271    raeburn  10438:     }
                   10439:     if ($errors) {
                   10440:         $errors =~ s/\s$//;
                   10441:         return $errors;
1.827     raeburn  10442:     } else {
1.1271    raeburn  10443:         return 'ok';
1.827     raeburn  10444:     }
                   10445: }
                   10446: 
1.745     raeburn  10447: #------------------------------------------------------Get Marked as Read Only
                   10448: 
                   10449: sub get_marked_as_readonly {
                   10450:     my ($domain,$user,$what,$group) = @_;
                   10451:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10452:     my @readonly_files;
1.629     banghart 10453:     my $cmp1=$what;
                   10454:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10455:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10456:         if (defined($group)) {
                   10457:             if ($file_name !~ m-^\Q$group\E/-) {
                   10458:                 next;
                   10459:             }
                   10460:         }
1.561     banghart 10461:         if (ref($value) eq "ARRAY"){
                   10462:             foreach my $stored_what (@{$value}) {
1.629     banghart 10463:                 my $cmp2=$stored_what;
1.759     albertel 10464:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10465:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10466:                 }
1.629     banghart 10467:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10468:                     push(@readonly_files, $file_name);
1.745     raeburn  10469:                     last;
1.563     banghart 10470:                 } elsif (!defined($what)) {
                   10471:                     push(@readonly_files, $file_name);
1.745     raeburn  10472:                     last;
1.561     banghart 10473:                 }
                   10474:             }
1.745     raeburn  10475:         }
1.561     banghart 10476:     }
                   10477:     return @readonly_files;
                   10478: }
1.577     banghart 10479: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10480: 
1.577     banghart 10481: sub get_marked_as_readonly_hash {
1.745     raeburn  10482:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10483:     my %readonly_files;
1.745     raeburn  10484:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10485:         if (defined($group)) {
                   10486:             if ($file_name !~ m-^\Q$group\E/-) {
                   10487:                 next;
                   10488:             }
                   10489:         }
1.577     banghart 10490:         if (ref($value) eq "ARRAY"){
                   10491:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10492:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10493:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10494:                         if ($lock_descriptor eq 'graded') {
                   10495:                             $readonly_files{$file_name} = 'graded';
                   10496:                         } elsif ($lock_descriptor eq 'handback') {
                   10497:                             $readonly_files{$file_name} = 'handback';
                   10498:                         } else {
                   10499:                             if (!exists($readonly_files{$file_name})) {
                   10500:                                 $readonly_files{$file_name} = 'locked';
                   10501:                             }
                   10502:                         }
1.745     raeburn  10503:                     }
1.750     banghart 10504:                 } 
1.577     banghart 10505:             }
                   10506:         } 
                   10507:     }
                   10508:     return %readonly_files;
                   10509: }
1.559     banghart 10510: # ------------------------------------------------------------ Unmark as Read Only
                   10511: 
                   10512: sub unmark_as_readonly {
1.629     banghart 10513:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10514:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10515:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10516:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10517:     my $symb_crs = $what;
                   10518:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10519:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10520:     my ($tmp)=keys(%current_permissions);
                   10521:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10522:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10523:     foreach my $file (@readonly_files) {
1.759     albertel 10524: 	my $clean_file = &declutter_portfile($file);
                   10525: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10526: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10527:         my @new_locks;
                   10528:         my @del_keys;
                   10529:         if (ref($current_locks) eq "ARRAY"){
                   10530:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10531:                 my $compare=$locker;
1.749     raeburn  10532:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10533:                     $compare=join('',@{$locker});
1.746     raeburn  10534:                     if ($compare ne $symb_crs) {
                   10535:                         push(@new_locks, $locker);
                   10536:                     }
1.563     banghart 10537:                 }
                   10538:             }
1.650     albertel 10539:             if (scalar(@new_locks) > 0) {
1.563     banghart 10540:                 $current_permissions{$file} = \@new_locks;
                   10541:             } else {
                   10542:                 push(@del_keys, $file);
1.613     albertel 10543:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10544:                 delete($current_permissions{$file});
1.563     banghart 10545:             }
                   10546:         }
1.561     banghart 10547:     }
1.613     albertel 10548:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10549:     return;
                   10550: }
1.512     banghart 10551: 
1.17      www      10552: # ------------------------------------------------------------ Directory lister
                   10553: 
                   10554: sub dirlist {
1.955     raeburn  10555:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10556:     $uri=~s/^\///;
                   10557:     $uri=~s/\/$//;
1.253     stredwic 10558:     my ($udom, $uname);
1.955     raeburn  10559:     if ($getuserdir) {
1.253     stredwic 10560:         $udom = $userdomain;
                   10561:         $uname = $username;
1.955     raeburn  10562:     } else {
                   10563:         (undef,$udom,$uname)=split(/\//,$uri);
                   10564:         if(defined($userdomain)) {
                   10565:             $udom = $userdomain;
                   10566:         }
                   10567:         if(defined($username)) {
                   10568:             $uname = $username;
                   10569:         }
1.253     stredwic 10570:     }
1.955     raeburn  10571:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10572: 
1.955     raeburn  10573:     $dirRoot = $perlvar{'lonDocRoot'};
                   10574:     if (defined($getpropath)) {
                   10575:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10576:         $dirRoot =~ s/\/$//;
1.955     raeburn  10577:     } elsif (defined($getuserdir)) {
                   10578:         my $subdir=$uname.'__';
                   10579:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10580:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10581:                    ."/$udom/$subdir/$uname";
                   10582:     } elsif (defined($alternateRoot)) {
                   10583:         $dirRoot = $alternateRoot;
1.751     banghart 10584:     }
1.253     stredwic 10585: 
                   10586:     if($udom) {
                   10587:         if($uname) {
1.1135    raeburn  10588:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10589:             if ($uhome eq 'no_host') {
                   10590:                 return ([],'no_host');
                   10591:             }
1.955     raeburn  10592:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10593:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10594:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10595:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10596:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10597:             } else {
                   10598:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10599:             }
1.605     matthew  10600:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10601:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10602:                 @listing_results = split(/:/,$listing);
                   10603:             } else {
                   10604:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10605:             }
1.1135    raeburn  10606:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10607:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10608:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10609:                 return ([],$listing);
                   10610:             } else {
                   10611:                 return (\@listing_results);
1.1135    raeburn  10612:             }
1.955     raeburn  10613:         } elsif(!$alternateRoot) {
1.1136    raeburn  10614:             my (%allusers,%listerror);
1.841     albertel 10615: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10616:  	    foreach my $tryserver (keys(%servers)) {
                   10617:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10618:                                   &escape($udom),$tryserver);
                   10619:                 if ($listing eq 'unknown_cmd') {
                   10620: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10621: 				      $udom, $tryserver);
                   10622:                 } else {
                   10623:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10624:                 }
1.841     albertel 10625: 		if ($listing eq 'unknown_cmd') {
                   10626: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10627: 				      $udom, $tryserver);
                   10628: 		    @listing_results = split(/:/,$listing);
                   10629: 		} else {
                   10630: 		    @listing_results =
                   10631: 			map { &unescape($_); } split(/:/,$listing);
                   10632: 		}
1.1136    raeburn  10633:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10634:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10635:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10636:                     $listerror{$tryserver} = $listing;
                   10637:                 } else {
1.841     albertel 10638: 		    foreach my $line (@listing_results) {
                   10639: 			my ($entry) = split(/&/,$line,2);
                   10640: 			$allusers{$entry} = 1;
                   10641: 		    }
                   10642: 		}
1.253     stredwic 10643:             }
1.1136    raeburn  10644:             my @alluserslist=();
1.800     albertel 10645:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10646:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10647:             }
1.1318    droeschl 10648: 
                   10649:             if (!%listerror) {
                   10650:                 # no errors
                   10651:                 return (\@alluserslist);
                   10652:             } elsif (scalar(keys(%servers)) == 1) {
                   10653:                 # one library server, one error 
                   10654:                 my ($key) = keys(%listerror);
                   10655:                 return (\@alluserslist, $listerror{$key});
                   10656:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10657:                 # con_lost indicates that we might miss data from at least one
                   10658:                 # library server
                   10659:                 return (\@alluserslist, 'con_lost');
                   10660:             } else {
                   10661:                 # multiple library servers and no con_lost -> data should be
                   10662:                 # complete. 
                   10663:                 return (\@alluserslist);
                   10664:             }
                   10665: 
1.253     stredwic 10666:         } else {
1.1136    raeburn  10667:             return ([],'missing username');
1.253     stredwic 10668:         }
1.955     raeburn  10669:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10670:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10671:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10672:         return (\@all_domains);
1.955     raeburn  10673:     } else {
1.1136    raeburn  10674:         return ([],'missing domain');
1.275     stredwic 10675:     }
                   10676: }
                   10677: 
                   10678: # --------------------------------------------- GetFileTimestamp
                   10679: # This function utilizes dirlist and returns the date stamp for
                   10680: # when it was last modified.  It will also return an error of -1
                   10681: # if an error occurs
                   10682: 
                   10683: sub GetFileTimestamp {
1.955     raeburn  10684:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10685:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10686:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10687:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10688:                                     undef,$getuserdir);
                   10689:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10690:         return -1;
                   10691:     }
                   10692:     if (ref($fileref) eq 'ARRAY') {
                   10693:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10694:         # @stats contains first the filename, then the stat output
                   10695:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10696:     } else {
                   10697:         return -1;
1.253     stredwic 10698:     }
1.26      www      10699: }
                   10700: 
1.712     albertel 10701: sub stat_file {
                   10702:     my ($uri) = @_;
1.787     albertel 10703:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10704: 
1.955     raeburn  10705:     my ($udom,$uname,$file);
1.712     albertel 10706:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10707: 	($udom,$uname,$file) =
1.811     albertel 10708: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10709: 	$file = 'userfiles/'.$file;
                   10710:     }
                   10711:     if ($uri =~ m-^/res/-) {
                   10712: 	($udom,$uname) = 
1.807     albertel 10713: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10714: 	$file = $uri;
                   10715:     }
                   10716: 
                   10717:     if (!$udom || !$uname || !$file) {
                   10718: 	# unable to handle the uri
                   10719: 	return ();
                   10720:     }
1.956     raeburn  10721:     my $getpropath;
                   10722:     if ($file =~ /^userfiles\//) {
                   10723:         $getpropath = 1;
                   10724:     }
1.1136    raeburn  10725:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10726:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10727:         return ();
                   10728:     } else {
                   10729:         if (ref($listref) eq 'ARRAY') {
                   10730:             my @stats = split('&',$listref->[0]);
                   10731: 	    shift(@stats); #filename is first
                   10732: 	    return @stats;
                   10733:         }
1.712     albertel 10734:     }
                   10735:     return ();
                   10736: }
                   10737: 
1.1313    raeburn  10738: # --------------------------------------------------------- recursedirs
                   10739: # Recursive function to traverse either a specific user's Authoring Space
                   10740: # or corresponding Published Resource Space, and populate the hash ref:
                   10741: # $dirhashref with URLs of all directories, and if $filehashref hash
                   10742: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   10743: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   10744: # files in Authoring Space.
                   10745: #
                   10746: # Inputs:
                   10747: #
                   10748: # $is_home - true if current server is home server for user's space
                   10749: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   10750: # $docroot - Document root (i.e., /home/httpd/html
                   10751: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   10752: # $relpath - Current path (relative to top level).
                   10753: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   10754: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   10755: #
                   10756: # Returns: nothing
                   10757: #
                   10758: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   10759: #
                   10760: # Currently used by interface/londocs.pm to create linked select boxes for
                   10761: # directory and filename to import a Course "Author" resource into a course, and
                   10762: # also to create linked select boxes for Authoring Space and Directory to choose
                   10763: # save location for creation of a new "standard" problem from the Course Editor.
                   10764: #
                   10765: 
                   10766: sub recursedirs {
                   10767:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   10768:     return unless (ref($dirhashref) eq 'HASH');
                   10769:     my $currpath = $docroot.$toppath;
                   10770:     if ($relpath) {
                   10771:         $currpath .= "/$relpath";
                   10772:     }
                   10773:     my $savefile;
                   10774:     if (ref($filehashref)) {
                   10775:         $savefile = 1;
                   10776:     }
                   10777:     if ($is_home) {
                   10778:         if (opendir(my $dirh,$currpath)) {
                   10779:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   10780:                 next if ($item eq '');
                   10781:                 if (-d "$currpath/$item") {
                   10782:                     my $newpath;
                   10783:                     if ($relpath) {
                   10784:                         $newpath = "$relpath/$item";
                   10785:                     } else {
                   10786:                         $newpath = $item;
                   10787:                     }
                   10788:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10789:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10790:                 } elsif ($savefile) {
                   10791:                     if ($context eq 'priv') {
                   10792:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10793:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10794:                         }
                   10795:                     } else {
                   10796:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   10797:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10798:                         }
                   10799:                     }
                   10800:                 }
                   10801:             }
                   10802:             closedir($dirh);
                   10803:         }
                   10804:     } else {
                   10805:         my ($dirlistref,$listerror) =
                   10806:             &dirlist($toppath.$relpath);
                   10807:         my @dir_lines;
                   10808:         my $dirptr=16384;
                   10809:         if (ref($dirlistref) eq 'ARRAY') {
                   10810:             foreach my $dir_line (sort
                   10811:                               {
                   10812:                                   my ($afile)=split('&',$a,2);
                   10813:                                   my ($bfile)=split('&',$b,2);
                   10814:                                   return (lc($afile) cmp lc($bfile));
                   10815:                               } (@{$dirlistref})) {
                   10816:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   10817:                     split(/\&/,$dir_line,16);
                   10818:                 $item =~ s/\s+$//;
                   10819:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   10820:                 if ($dirptr&$testdir) {
                   10821:                     my $newpath;
                   10822:                     if ($relpath) {
                   10823:                         $newpath = "$relpath/$item";
                   10824:                     } else {
                   10825:                         $relpath = '/';
                   10826:                         $newpath = $item;
                   10827:                     }
                   10828:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10829:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10830:                 } elsif ($savefile) {
                   10831:                     if ($context eq 'priv') {
                   10832:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10833:                             $filehashref->{$relpath}{$item} = 1;
                   10834:                         }
                   10835:                     } else {
                   10836:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   10837:                             $filehashref->{$relpath}{$item} = 1;
                   10838:                         }
                   10839:                     }
                   10840:                 }
                   10841:             }
                   10842:         }
                   10843:     }
                   10844:     return;
                   10845: }
                   10846: 
1.26      www      10847: # -------------------------------------------------------- Value of a Condition
                   10848: 
1.713     albertel 10849: # gets the value of a specific preevaluated condition
                   10850: #    stored in the string  $env{user.state.<cid>}
                   10851: # or looks up a condition reference in the bighash and if if hasn't
                   10852: # already been evaluated recurses into docondval to get the value of
                   10853: # the condition, then memoizing it to 
                   10854: #   $env{user.state.<cid>.<condition>}
1.40      www      10855: sub directcondval {
                   10856:     my $number=shift;
1.620     albertel 10857:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10858: 	&Apache::lonuserstate::evalstate();
                   10859:     }
1.713     albertel 10860:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10861: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10862:     } elsif ($number =~ /^_/) {
                   10863: 	my $sub_condition;
                   10864: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10865: 		&GDBM_READER(),0640)) {
                   10866: 	    $sub_condition=$bighash{'conditions'.$number};
                   10867: 	    untie(%bighash);
                   10868: 	}
                   10869: 	my $value = &docondval($sub_condition);
1.949     raeburn  10870: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10871: 	return $value;
                   10872:     }
1.620     albertel 10873:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10874:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10875:     } else {
                   10876:        return 2;
                   10877:     }
                   10878: }
                   10879: 
1.713     albertel 10880: # get the collection of conditions for this resource
1.26      www      10881: sub condval {
                   10882:     my $condidx=shift;
1.54      www      10883:     my $allpathcond='';
1.713     albertel 10884:     foreach my $cond (split(/\|/,$condidx)) {
                   10885: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10886: 	    $allpathcond.=
                   10887: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10888: 	}
1.191     harris41 10889:     }
1.54      www      10890:     $allpathcond=~s/\|$//;
1.713     albertel 10891:     return &docondval($allpathcond);
                   10892: }
                   10893: 
                   10894: #evaluates an expression of conditions
                   10895: sub docondval {
                   10896:     my ($allpathcond) = @_;
                   10897:     my $result=0;
                   10898:     if ($env{'request.course.id'}
                   10899: 	&& defined($allpathcond)) {
                   10900: 	my $operand='|';
                   10901: 	my @stack;
                   10902: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10903: 	    if ($chunk eq '(') {
                   10904: 		push @stack,($operand,$result);
                   10905: 	    } elsif ($chunk eq ')') {
                   10906: 		my $before=pop @stack;
                   10907: 		if (pop @stack eq '&') {
                   10908: 		    $result=$result>$before?$before:$result;
                   10909: 		} else {
                   10910: 		    $result=$result>$before?$result:$before;
                   10911: 		}
                   10912: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10913: 		$operand=$chunk;
                   10914: 	    } else {
                   10915: 		my $new=directcondval($chunk);
                   10916: 		if ($operand eq '&') {
                   10917: 		    $result=$result>$new?$new:$result;
                   10918: 		} else {
                   10919: 		    $result=$result>$new?$result:$new;
                   10920: 		}
                   10921: 	    }
                   10922: 	}
1.26      www      10923:     }
                   10924:     return $result;
1.421     albertel 10925: }
                   10926: 
                   10927: # ---------------------------------------------------- Devalidate courseresdata
                   10928: 
                   10929: sub devalidatecourseresdata {
                   10930:     my ($coursenum,$coursedomain)=@_;
                   10931:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10932:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10933: }
                   10934: 
1.763     www      10935: 
1.200     www      10936: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10937: #
                   10938: #  Parameters:
                   10939: #      $coursenum    - Number of the course.
                   10940: #      $coursedomain - Domain at which the course was created.
                   10941: #  Returns:
                   10942: #     A hash of the course parameters along (I think) with timestamps
                   10943: #     and version info.
1.877     foxr     10944: 
1.624     albertel 10945: sub get_courseresdata {
                   10946:     my ($coursenum,$coursedomain)=@_;
1.200     www      10947:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10948:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10949:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10950:     my %dumpreply;
1.417     albertel 10951:     unless (defined($cached)) {
1.624     albertel 10952: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10953: 	$result=\%dumpreply;
1.251     albertel 10954: 	my ($tmp) = keys(%dumpreply);
                   10955: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10956: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10957: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10958: 	    return $tmp;
1.416     albertel 10959: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10960: 	    $result=undef;
1.599     albertel 10961: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10962: 	}
                   10963:     }
1.624     albertel 10964:     return $result;
                   10965: }
                   10966: 
1.633     albertel 10967: sub devalidateuserresdata {
                   10968:     my ($uname,$udom)=@_;
                   10969:     my $hashid="$udom:$uname";
                   10970:     &devalidate_cache_new('userres',$hashid);
                   10971: }
                   10972: 
1.624     albertel 10973: sub get_userresdata {
                   10974:     my ($uname,$udom)=@_;
                   10975:     #most student don\'t have any data set, check if there is some data
                   10976:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10977: 
                   10978:     my $hashid="$udom:$uname";
                   10979:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10980:     if (!defined($cached)) {
                   10981: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10982: 	$result=\%resourcedata;
                   10983: 	&do_cache_new('userres',$hashid,$result,600);
                   10984:     }
                   10985:     my ($tmp)=keys(%$result);
                   10986:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10987: 	return $result;
                   10988:     }
                   10989:     #error 2 occurs when the .db doesn't exist
                   10990:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  10991:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   10992: 	    &logthis("<font color=\"blue\">WARNING:".
                   10993: 		     " Trying to get resource data for ".
                   10994: 		     $uname." at ".$udom.": ".
                   10995: 		     $tmp."</font>");
                   10996:         }
1.624     albertel 10997:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10998: 	#&EXT_cache_set($udom,$uname);
                   10999: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11000: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11001:     }
                   11002:     return $tmp;
                   11003: }
1.879     foxr     11004: #----------------------------------------------- resdata - return resource data
                   11005: #  Purpose:
                   11006: #    Return resource data for either users or for a course.
                   11007: #  Parameters:
                   11008: #     $name      - Course/user name.
                   11009: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  11010: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  11011: #     $mapp      - decluttered URL of enclosing map  
                   11012: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   11013: #     $recurseup - Ref to array of map URLs, starting with map containing
                   11014: #                  $mapp up through hierarchy of nested maps to top level map.  
                   11015: #     $courseid  - CourseID (first part of param identifier).
                   11016: #     $modifier  - Middle part of param identifier.
                   11017: #     $what      - Last part of param identifier.
1.879     foxr     11018: #     @which     - Array of names of resources desired.
                   11019: #  Returns:
                   11020: #     The value of the first reasource in @which that is found in the
                   11021: #     resource hash.
                   11022: #  Exceptional Conditions:
                   11023: #     If the $type passed in is not valid (not the string 'course' or 
                   11024: #     'user', an undefined  reference is returned.
                   11025: #     If none of the resources are found, an undef is returned
1.624     albertel 11026: sub resdata {
1.1301    raeburn  11027:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   11028:         $modifier,$what,@which)=@_;
1.624     albertel 11029:     my $result;
                   11030:     if ($type eq 'course') {
                   11031: 	$result=&get_courseresdata($name,$domain);
                   11032:     } elsif ($type eq 'user') {
                   11033: 	$result=&get_userresdata($name,$domain);
                   11034:     }
                   11035:     if (!ref($result)) { return $result; }    
1.251     albertel 11036:     foreach my $item (@which) {
1.1301    raeburn  11037:         if ($item->[1] eq 'course') {
                   11038:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   11039:                 unless ($$recursed) {
1.1302    raeburn  11040:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  11041:                     $$recursed = 1;
                   11042:                 }
                   11043:                 foreach my $item (@${recurseup}) {
                   11044:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   11045:                     last if (defined($result->{$norecursechk}));
                   11046:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   11047:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   11048:                 }
                   11049:             }
                   11050:         }
                   11051:         if (defined($result->{$item->[0]})) {
1.927     albertel 11052: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11053: 	}
1.250     albertel 11054:     }
1.291     albertel 11055:     return undef;
1.200     www      11056: }
                   11057: 
1.1298    raeburn  11058: sub get_domain_ltitools {
                   11059:     my ($cdom) = @_;
                   11060:     my %ltitools;
                   11061:     my ($result,$cached)=&is_cached_new('ltitools',$cdom);
                   11062:     if (defined($cached)) {
                   11063:         if (ref($result) eq 'HASH') {
                   11064:             %ltitools = %{$result};
                   11065:         }
                   11066:     } else {
                   11067:         my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
                   11068:         if (ref($domconfig{'ltitools'}) eq 'HASH') {
                   11069:             %ltitools = %{$domconfig{'ltitools'}};
1.1344    raeburn  11070:             my %encdomconfig = &get_dom('encconfig',['ltitools'],$cdom);
                   11071:             if (ref($encdomconfig{'ltitools'}) eq 'HASH') {
                   11072:                 foreach my $id (keys(%ltitools)) {
                   11073:                     if (ref($encdomconfig{'ltitools'}{$id}) eq 'HASH') {
                   11074:                         foreach my $item ('key','secret') {
                   11075:                             $ltitools{$id}{$item} = $encdomconfig{'ltitools'}{$id}{$item};
                   11076:                         }
                   11077:                     }
                   11078:                 }
                   11079:             }
1.1298    raeburn  11080:         }
                   11081:         my $cachetime = 24*60*60;
                   11082:         &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
                   11083:     }
                   11084:     return %ltitools;
                   11085: }
                   11086: 
1.1236    raeburn  11087: sub get_numsuppfiles {
                   11088:     my ($cnum,$cdom,$ignorecache)=@_;
                   11089:     my $hashid=$cnum.':'.$cdom;
                   11090:     my ($suppcount,$cached);
                   11091:     unless ($ignorecache) {
                   11092:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11093:     }
                   11094:     unless (defined($cached)) {
                   11095:         my $chome=&homeserver($cnum,$cdom);
                   11096:         unless ($chome eq 'no_host') {
                   11097:             ($suppcount,my $errors) = (0,0);
                   11098:             my $suppmap = 'supplemental.sequence';
                   11099:             ($suppcount,$errors) = 
                   11100:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11101:         }
                   11102:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11103:     }
                   11104:     return $suppcount;
                   11105: }
                   11106: 
1.379     matthew  11107: #
                   11108: # EXT resource caching routines
                   11109: #
                   11110: 
1.1302    raeburn  11111: {
                   11112: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   11113: #
                   11114: # The course for which we cache
                   11115: my $cachedmapkey='';
                   11116: # The cached recursive maps for this course
                   11117: my %cachedmaps=();
                   11118: # When this was last done
                   11119: my $cachedmaptime='';
                   11120: 
1.379     matthew  11121: sub clear_EXT_cache_status {
1.383     albertel 11122:     &delenv('cache.EXT.');
1.379     matthew  11123: }
                   11124: 
                   11125: sub EXT_cache_status {
                   11126:     my ($target_domain,$target_user) = @_;
1.383     albertel 11127:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11128:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11129:         # We know already the user has no data
                   11130:         return 1;
                   11131:     } else {
                   11132:         return 0;
                   11133:     }
                   11134: }
                   11135: 
                   11136: sub EXT_cache_set {
                   11137:     my ($target_domain,$target_user) = @_;
1.383     albertel 11138:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11139:     #&appenv({$cachename => time});
1.379     matthew  11140: }
                   11141: 
1.28      www      11142: # --------------------------------------------------------- Value of a Variable
1.58      www      11143: sub EXT {
1.715     albertel 11144: 
1.1228    raeburn  11145:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11146:     unless ($varname) { return ''; }
1.218     albertel 11147:     #get real user name/domain, courseid and symb
                   11148:     my $courseid;
1.359     albertel 11149:     my $publicuser;
1.427     www      11150:     if ($symbparm) {
                   11151: 	$symbparm=&get_symb_from_alias($symbparm);
                   11152:     }
1.218     albertel 11153:     if (!($uname && $udom)) {
1.790     albertel 11154:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11155:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11156:     } else {
1.620     albertel 11157: 	$courseid=$env{'request.course.id'};
1.218     albertel 11158:     }
1.48      www      11159:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11160:     my $rest;
1.320     albertel 11161:     if (defined($therest[0])) {
1.48      www      11162:        $rest=join('.',@therest);
                   11163:     } else {
                   11164:        $rest='';
                   11165:     }
1.320     albertel 11166: 
1.57      www      11167:     my $qualifierrest=$qualifier;
                   11168:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11169:     my $spacequalifierrest=$space;
                   11170:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11171:     if ($realm eq 'user') {
1.48      www      11172: # --------------------------------------------------------------- user.resource
                   11173: 	if ($space eq 'resource') {
1.651     albertel 11174: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11175: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11176: 		 &&
1.744     albertel 11177: 		 ($symbparm eq &symbread()) ) {	
                   11178: 		# if we are in the middle of processing the resource the
                   11179: 		# get the value we are planning on committing
                   11180:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11181:                     return $Apache::lonhomework::results{$qualifierrest};
                   11182:                 } else {
                   11183:                     return $Apache::lonhomework::history{$qualifierrest};
                   11184:                 }
1.335     albertel 11185: 	    } else {
1.359     albertel 11186: 		my %restored;
1.620     albertel 11187: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11188: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11189: 		} else {
                   11190: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11191: 		}
1.335     albertel 11192: 		return $restored{$qualifierrest};
                   11193: 	    }
1.48      www      11194: # ----------------------------------------------------------------- user.access
                   11195:         } elsif ($space eq 'access') {
1.218     albertel 11196: 	    # FIXME - not supporting calls for a specific user
1.48      www      11197:             return &allowed($qualifier,$rest);
                   11198: # ------------------------------------------ user.preferences, user.environment
                   11199:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11200: 	    if (($uname eq $env{'user.name'}) &&
                   11201: 		($udom eq $env{'user.domain'})) {
                   11202: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11203: 	    } else {
1.359     albertel 11204: 		my %returnhash;
                   11205: 		if (!$publicuser) {
                   11206: 		    %returnhash=&userenvironment($udom,$uname,
                   11207: 						 $qualifierrest);
                   11208: 		}
1.218     albertel 11209: 		return $returnhash{$qualifierrest};
                   11210: 	    }
1.48      www      11211: # ----------------------------------------------------------------- user.course
                   11212:         } elsif ($space eq 'course') {
1.218     albertel 11213: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11214:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11215: # ------------------------------------------------------------------- user.role
                   11216:         } elsif ($space eq 'role') {
1.218     albertel 11217: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11218:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11219:             if ($qualifier eq 'value') {
                   11220: 		return $role;
                   11221:             } elsif ($qualifier eq 'extent') {
                   11222:                 return $where;
                   11223:             }
                   11224: # ----------------------------------------------------------------- user.domain
                   11225:         } elsif ($space eq 'domain') {
1.218     albertel 11226:             return $udom;
1.48      www      11227: # ------------------------------------------------------------------- user.name
                   11228:         } elsif ($space eq 'name') {
1.218     albertel 11229:             return $uname;
1.48      www      11230: # ---------------------------------------------------- Any other user namespace
1.29      www      11231:         } else {
1.359     albertel 11232: 	    my %reply;
                   11233: 	    if (!$publicuser) {
                   11234: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11235: 	    }
                   11236: 	    return $reply{$qualifierrest};
1.48      www      11237:         }
1.236     www      11238:     } elsif ($realm eq 'query') {
                   11239: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11240:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11241: 						[$spacequalifierrest]);
1.620     albertel 11242: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11243:    } elsif ($realm eq 'request') {
1.48      www      11244: # ------------------------------------------------------------- request.browser
                   11245:         if ($space eq 'browser') {
1.1145    bisitz   11246:             return $env{'browser.'.$qualifier};
1.57      www      11247: # ------------------------------------------------------------ request.filename
                   11248:         } else {
1.620     albertel 11249:             return $env{'request.'.$spacequalifierrest};
1.29      www      11250:         }
1.28      www      11251:     } elsif ($realm eq 'course') {
1.48      www      11252: # ---------------------------------------------------------- course.description
1.620     albertel 11253:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11254:     } elsif ($realm eq 'resource') {
1.165     www      11255: 
1.620     albertel 11256: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11257: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11258: 	}
1.693     albertel 11259: 
1.1232    raeburn  11260:         if ($qualifier eq '') {
                   11261: 	    if ($space eq 'title') {
                   11262: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11263: 	        return &gettitle($symbparm);
                   11264: 	    }
1.693     albertel 11265: 	
1.1232    raeburn  11266: 	    if ($space eq 'map') {
                   11267: 	        my ($map) = &decode_symb($symbparm);
                   11268: 	        return &symbread($map);
                   11269: 	    }
                   11270:             if ($space eq 'maptitle') {
                   11271:                 my ($map) = &decode_symb($symbparm);
                   11272:                 return &gettitle($map);
                   11273:             }
                   11274: 	    if ($space eq 'filename') {
                   11275: 	        if ($symbparm) {
                   11276: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11277: 	        }
                   11278: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11279: 	    }
1.1232    raeburn  11280: 
1.1233    raeburn  11281:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11282:                 if ($space eq 'visibleparts') {
                   11283:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11284:                     my $item;
                   11285:                     if (ref($navmap)) {
                   11286:                         my $res = $navmap->getBySymb($symbparm);
                   11287:                         my $parts = $res->parts();
                   11288:                         if (ref($parts) eq 'ARRAY') {
                   11289:                             $item = join(',',@{$parts});
                   11290:                         }
                   11291:                         undef($navmap);
1.1232    raeburn  11292:                     }
1.1233    raeburn  11293:                     return $item;
1.1232    raeburn  11294:                 }
                   11295:             }
                   11296:         }
1.693     albertel 11297: 
1.1301    raeburn  11298: 	my ($section, $group, @groups, @recurseup, $recursed);
                   11299: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  11300:         if (($courseid eq '') && ($cid)) {
                   11301:             $courseid = $cid;
                   11302:         }
                   11303: 	if (($symbparm && $courseid) && 
                   11304: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      11305: 
1.218     albertel 11306: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11307: 
1.60      www      11308: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11309: 	    my $symbp=$symbparm;
1.1301    raeburn  11310: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11311: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  11312:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 11313: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 11314: 	    if (($env{'user.name'} eq $uname) &&
                   11315: 		($env{'user.domain'} eq $udom)) {
                   11316: 		$section=$env{'request.course.sec'};
1.733     raeburn  11317:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11318:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11319: 	    } else {
1.539     albertel 11320: 		if (! defined($usection)) {
1.551     albertel 11321: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11322: 		} else {
                   11323: 		    $section = $usection;
                   11324: 		}
1.733     raeburn  11325:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11326: 	    }
                   11327: 
                   11328: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11329: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  11330:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 11331: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11332: 
1.593     albertel 11333: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11334: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  11335:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 11336: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11337: 
1.60      www      11338: # ----------------------------------------------------------- first, check user
1.624     albertel 11339: 
1.1301    raeburn  11340: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   11341:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 11342: 				       ([$courselevelr,'resource'],
                   11343: 					[$courselevelm,'map'     ],
1.1301    raeburn  11344:                                         [$courseleveli,'map'     ],
1.927     albertel 11345: 					[$courselevel, 'course'  ]));
1.931     albertel 11346: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11347: 
1.594     albertel 11348: # ------------------------------------------------ second, check some of course
1.684     raeburn  11349:             my $coursereply;
1.691     raeburn  11350:             if (@groups > 0) {
                   11351:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  11352:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   11353:                                        $mapp,\$recursed,\@recurseup);
                   11354:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  11355:             }
1.96      www      11356: 
1.684     raeburn  11357: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11358: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11359: 				  'course',$mapp,\$recursed,\@recurseup,
                   11360:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 11361: 				  ([$seclevelr,   'resource'],
                   11362: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  11363:                                    [$secleveli,   'map'     ],
1.927     albertel 11364: 				   [$seclevel,    'course'  ],
                   11365: 				   [$courselevelr,'resource']));
                   11366: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11367: 
1.60      www      11368: # ------------------------------------------------------ third, check map parms
1.218     albertel 11369: 	    my %parmhash=();
                   11370: 	    my $thisparm='';
                   11371: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11372: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11373: 		    &GDBM_READER(),0640)) {
1.218     albertel 11374: 		$thisparm=$parmhash{$symbparm};
                   11375: 		untie(%parmhash);
                   11376: 	    }
1.927     albertel 11377: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11378: 	}
1.594     albertel 11379: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  11380:  
                   11381:         my $what = $spacequalifierrest;
                   11382: 	$what=~s/\./\_/;
1.282     albertel 11383: 	my $filename;
                   11384: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11385: 	if ($symbparm) {
1.409     www      11386: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11387: 	} else {
1.620     albertel 11388: 	    $filename=$env{'request.filename'};
1.282     albertel 11389: 	}
1.1301    raeburn  11390: 	my $metadata=&metadata($filename,$what);
1.927     albertel 11391: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1301    raeburn  11392: 	$metadata=&metadata($filename,'parameter_'.$what);
1.927     albertel 11393: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11394: 
1.1301    raeburn  11395: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 11396: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11397: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11398: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11399: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11400: 				     'course',$mapp,\$recursed,\@recurseup,
                   11401:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 11402: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  11403:                                       [$courseleveli,'map'   ],
1.927     albertel 11404: 				      [$courselevel, 'course']));
                   11405: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11406: 	}
1.145     www      11407: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11408: 	unless ($space eq '0') {
1.336     albertel 11409: 	    my @parts=split(/_/,$space);
                   11410: 	    my $id=pop(@parts);
                   11411: 	    my $part=join('_',@parts);
                   11412: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11413: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11414: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11415: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11416: 	}
1.395     albertel 11417: 	if ($recurse) { return undef; }
                   11418: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11419: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11420: # ---------------------------------------------------- Any other user namespace
                   11421:     } elsif ($realm eq 'environment') {
                   11422: # ----------------------------------------------------------------- environment
1.620     albertel 11423: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11424: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11425: 	} else {
1.770     albertel 11426: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11427: 		return '';
                   11428: 	    }
1.219     albertel 11429: 	    my %returnhash=&userenvironment($udom,$uname,
                   11430: 					    $spacequalifierrest);
                   11431: 	    return $returnhash{$spacequalifierrest};
                   11432: 	}
1.28      www      11433:     } elsif ($realm eq 'system') {
1.48      www      11434: # ----------------------------------------------------------------- system.time
                   11435: 	if ($space eq 'time') {
                   11436: 	    return time;
                   11437:         }
1.696     albertel 11438:     } elsif ($realm eq 'server') {
                   11439: # ----------------------------------------------------------------- system.time
                   11440: 	if ($space eq 'name') {
                   11441: 	    return $ENV{'SERVER_NAME'};
                   11442:         }
1.28      www      11443:     }
1.48      www      11444:     return '';
1.61      www      11445: }
                   11446: 
1.927     albertel 11447: sub get_reply {
                   11448:     my ($reply_value) = @_;
1.940     raeburn  11449:     if (ref($reply_value) eq 'ARRAY') {
                   11450:         if (wantarray) {
                   11451: 	    return @$reply_value;
                   11452:         }
                   11453:         return $reply_value->[0];
                   11454:     } else {
                   11455:         return $reply_value;
1.927     albertel 11456:     }
                   11457: }
                   11458: 
1.691     raeburn  11459: sub check_group_parms {
1.1301    raeburn  11460:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   11461:         $recursed,$recurseupref) = @_;
                   11462:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   11463:                   [$what,'course']);
                   11464:     my $coursereply;
1.691     raeburn  11465:     foreach my $group (@{$groups}) {
1.1301    raeburn  11466:         my @groupitems = ();
1.691     raeburn  11467:         foreach my $level (@levels) {
1.927     albertel 11468:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11469:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11470:         }
1.1301    raeburn  11471:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11472:                                    $env{'course.'.$courseid.'.domain'},
                   11473:                                    'course',$mapp,$recursed,$recurseupref,
                   11474:                                    $courseid,'.['.$group.'].',$what,
                   11475:                                    @groupitems);
                   11476:         last if (defined($coursereply));
1.691     raeburn  11477:     }
                   11478:     return $coursereply;
                   11479: }
                   11480: 
1.1301    raeburn  11481: sub get_map_hierarchy {
1.1302    raeburn  11482:     my ($mapname,$courseid) = @_;
                   11483:     my @recurseup = ();
1.1301    raeburn  11484:     if ($mapname) {
1.1302    raeburn  11485:         if (($cachedmapkey eq $courseid) &&
                   11486:             (abs($cachedmaptime-time)<5)) {
                   11487:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   11488:                 return @{$cachedmaps{$mapname}};
                   11489:             }
                   11490:         }
1.1301    raeburn  11491:         my $navmap = Apache::lonnavmaps::navmap->new();
                   11492:         if (ref($navmap)) {
                   11493:             @recurseup = $navmap->recurseup_maps($mapname);
                   11494:             undef($navmap);
1.1302    raeburn  11495:             $cachedmaps{$mapname} = \@recurseup;
                   11496:             $cachedmaptime=time;
                   11497:             $cachedmapkey=$courseid;
1.1301    raeburn  11498:         }
                   11499:     }
                   11500:     return @recurseup;
                   11501: }
                   11502: 
1.1302    raeburn  11503: }
                   11504: 
1.691     raeburn  11505: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11506:     my ($courseid,@groups) = @_;
                   11507:     @groups = sort(@groups);
1.691     raeburn  11508:     return @groups;
                   11509: }
                   11510: 
1.395     albertel 11511: sub packages_tab_default {
                   11512:     my ($uri,$varname)=@_;
                   11513:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11514: 
                   11515:     my (@extension,@specifics,$do_default);
                   11516:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11517: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11518: 	if ($pack_type eq 'default') {
                   11519: 	    $do_default=1;
                   11520: 	} elsif ($pack_type eq 'extension') {
                   11521: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11522: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11523: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11524: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11525: 	}
                   11526:     }
                   11527:     # first look for a package that matches the requested part id
                   11528:     foreach my $package (@specifics) {
                   11529: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11530: 	next if ($pack_part ne $part);
                   11531: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11532: 	    return $packagetab{"$pack_type&$name&default"};
                   11533: 	}
                   11534:     }
                   11535:     # look for any possible matching non extension_ package
                   11536:     foreach my $package (@specifics) {
                   11537: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11538: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11539: 	    return $packagetab{"$pack_type&$name&default"};
                   11540: 	}
1.585     albertel 11541: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11542: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11543: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11544: 	}
                   11545:     }
1.738     albertel 11546:     # look for any posible extension_ match
                   11547:     foreach my $package (@extension) {
                   11548: 	my ($package,$pack_type)=@{$package};
                   11549: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11550: 	    return $packagetab{"$pack_type&$name&default"};
                   11551: 	}
                   11552: 	if (defined($packagetab{$package."&$name&default"})) {
                   11553: 	    return $packagetab{$package."&$name&default"};
                   11554: 	}
                   11555:     }
                   11556:     # look for a global default setting
                   11557:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11558: 	return $packagetab{"default&$name&default"};
                   11559:     }
1.395     albertel 11560:     return undef;
                   11561: }
                   11562: 
1.334     albertel 11563: sub add_prefix_and_part {
                   11564:     my ($prefix,$part)=@_;
                   11565:     my $keyroot;
                   11566:     if (defined($prefix) && $prefix !~ /^__/) {
                   11567: 	# prefix that has a part already
                   11568: 	$keyroot=$prefix;
                   11569:     } elsif (defined($prefix)) {
                   11570: 	# prefix that is missing a part
                   11571: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11572:     } else {
                   11573: 	# no prefix at all
                   11574: 	if (defined($part)) { $keyroot='_'.$part; }
                   11575:     }
                   11576:     return $keyroot;
                   11577: }
                   11578: 
1.71      www      11579: # ---------------------------------------------------------------- Get metadata
                   11580: 
1.599     albertel 11581: my %metaentry;
1.1070    www      11582: my %importedpartids;
1.71      www      11583: sub metadata {
1.176     www      11584:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11585:     $uri=&declutter($uri);
1.288     albertel 11586:     # if it is a non metadata possible uri return quickly
1.529     albertel 11587:     if (($uri eq '') || 
                   11588: 	(($uri =~ m|^/*adm/|) && 
1.1343    raeburn  11589: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  11590:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11591: 	return undef;
                   11592:     }
1.1261    raeburn  11593:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11594: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11595: 	return undef;
1.288     albertel 11596:     }
1.73      www      11597:     my $filename=$uri;
                   11598:     $uri=~s/\.meta$//;
1.172     www      11599: #
                   11600: # Is the metadata already cached?
1.177     www      11601: # Look at timestamp of caching
1.172     www      11602: # Everything is cached by the main uri, libraries are never directly cached
                   11603: #
1.428     albertel 11604:     if (!defined($liburi)) {
1.599     albertel 11605: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11606: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11607:     }
                   11608:     {
1.1069    www      11609: # Imported parts would go here
1.1070    www      11610:         my %importedids=();
                   11611:         my @origfileimportpartids=();
1.1069    www      11612:         my $importedparts=0;
1.172     www      11613: #
                   11614: # Is this a recursive call for a library?
                   11615: #
1.599     albertel 11616: #	if (! exists($metacache{$uri})) {
                   11617: #	    $metacache{$uri}={};
                   11618: #	}
1.924     albertel 11619: 	my $cachetime = 60*60;
1.171     www      11620:         if ($liburi) {
                   11621: 	    $liburi=&declutter($liburi);
                   11622:             $filename=$liburi;
1.401     bowersj2 11623:         } else {
1.599     albertel 11624: 	    &devalidate_cache_new('meta',$uri);
                   11625: 	    undef(%metaentry);
1.401     bowersj2 11626: 	}
1.140     www      11627:         my %metathesekeys=();
1.73      www      11628:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11629: 	my $metastring;
1.1140    www      11630: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11631: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11632: 	    $metastring = 
1.929     albertel 11633: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11634: 					  ('grade_target' => 'meta'));
                   11635: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11636: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11637:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11638: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11639: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11640: 	    $metastring=&getfile($file);
1.489     albertel 11641: 	}
1.208     albertel 11642:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11643:         my $token;
1.140     www      11644:         undef %metathesekeys;
1.71      www      11645:         while ($token=$parser->get_token) {
1.339     albertel 11646: 	    if ($token->[0] eq 'S') {
                   11647: 		if (defined($token->[2]->{'package'})) {
1.172     www      11648: #
                   11649: # This is a package - get package info
                   11650: #
1.339     albertel 11651: 		    my $package=$token->[2]->{'package'};
                   11652: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11653: 		    if (defined($token->[2]->{'id'})) { 
                   11654: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11655: 		    }
1.599     albertel 11656: 		    if ($metaentry{':packages'}) {
                   11657: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11658: 		    } else {
1.599     albertel 11659: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11660: 		    }
1.736     albertel 11661: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11662: 			my $part=$keyroot;
                   11663: 			$part=~s/^\_//;
1.736     albertel 11664: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11665: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11666: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11667: 			    # ignore package.tab specified default values
                   11668:                             # here &package_tab_default() will fetch those
                   11669: 			    if ($subp eq 'default') { next; }
1.736     albertel 11670: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11671: 			    my $unikey;
                   11672: 			    if ($pack =~ /_0$/) {
                   11673: 				$unikey='parameter_0_'.$name;
                   11674: 				$part=0;
                   11675: 			    } else {
                   11676: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11677: 			    }
1.339     albertel 11678: 			    if ($subp eq 'display') {
                   11679: 				$value.=' [Part: '.$part.']';
                   11680: 			    }
1.599     albertel 11681: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11682: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11683: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11684: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11685: 			    }
1.599     albertel 11686: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11687: 				$metaentry{':'.$unikey}=
                   11688: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11689: 			    }
1.339     albertel 11690: 			}
                   11691: 		    }
                   11692: 		} else {
1.172     www      11693: #
                   11694: # This is not a package - some other kind of start tag
1.339     albertel 11695: #
                   11696: 		    my $entry=$token->[1];
1.1068    www      11697: 		    my $unikey='';
1.175     www      11698: 
1.339     albertel 11699: 		    if ($entry eq 'import') {
1.175     www      11700: #
                   11701: # Importing a library here
1.339     albertel 11702: #
1.1067    www      11703:                         my $location=$parser->get_text('/import');
                   11704:                         my $dir=$filename;
                   11705:                         $dir=~s|[^/]*$||;
                   11706:                         $location=&filelocation($dir,$location);
1.1069    www      11707:                        
1.1068    www      11708:                         my $importmode=$token->[2]->{'importmode'};
                   11709:                         if ($importmode eq 'problem') {
1.1069    www      11710: # Import as problem/response
1.1068    www      11711:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11712:                         } elsif ($importmode eq 'part') {
                   11713: # Import as part(s)
1.1069    www      11714:                            $importedparts=1;
                   11715: # We need to get the original file and the imported file to get the part order correct
                   11716: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   11717: # Load and inspect original file
1.1070    www      11718:                            if ($#origfileimportpartids<0) {
                   11719:                               undef(%importedpartids);
                   11720:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11721:                               my $origfile=&getfile($origfilelocation);
                   11722:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11723:                            }
                   11724: 
1.1069    www      11725: # Load and inspect imported file
                   11726:                            my $impfile=&getfile($location);
                   11727:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11728:                            if ($#impfilepartids>=0) {
                   11729: # This problem had parts
1.1070    www      11730:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11731:                            } else {
                   11732: # Importing by turning a single problem into a problem part
                   11733: # It gets the import-tags ID as part-ID
                   11734:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11735:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11736:                            }
1.1068    www      11737:                         } else {
                   11738: # Normal import
                   11739:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11740:                            if (defined($token->[2]->{'id'})) {
                   11741:                               $unikey.='_'.$token->[2]->{'id'};
                   11742:                            }
1.1067    www      11743:                         }
                   11744: 
1.339     albertel 11745: 			if ($depthcount<20) {
1.736     albertel 11746: 			    my $metadata = 
                   11747: 				&metadata($uri,'keys', $location,$unikey,
                   11748: 					  $depthcount+1);
                   11749: 			    foreach my $meta (split(',',$metadata)) {
                   11750: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11751: 				$metathesekeys{$meta}=1;
1.339     albertel 11752: 			    }
1.1068    www      11753: 			
                   11754:                         }
1.1067    www      11755: 		    } else {
                   11756: #
                   11757: # Not importing, some other kind of non-package, non-library start tag
                   11758: # 
                   11759:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11760:                         if (defined($token->[2]->{'id'})) {
                   11761:                             $unikey.='_'.$token->[2]->{'id'};
                   11762:                         }
1.339     albertel 11763: 			if (defined($token->[2]->{'name'})) { 
                   11764: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11765: 			}
                   11766: 			$metathesekeys{$unikey}=1;
1.736     albertel 11767: 			foreach my $param (@{$token->[3]}) {
                   11768: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11769: 				$token->[2]->{$param};
1.339     albertel 11770: 			}
                   11771: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11772: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11773: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11774: 		 # only ws inside the tag, and not in default, so use default
                   11775: 		 # as value
1.599     albertel 11776: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11777: 			} elsif ( $internaltext =~ /\S/ ) {
                   11778: 		  # something interesting inside the tag
                   11779: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11780: 			} else {
1.908     albertel 11781: 		  # no interesting values, don't set a default
1.339     albertel 11782: 			}
1.172     www      11783: # end of not-a-package not-a-library import
1.339     albertel 11784: 		    }
1.172     www      11785: # end of not-a-package start tag
1.339     albertel 11786: 		}
1.172     www      11787: # the next is the end of "start tag"
1.339     albertel 11788: 	    }
                   11789: 	}
1.483     albertel 11790: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11791: 	$extension = lc($extension);
                   11792: 	if ($extension eq 'htm') { $extension='html'; }
                   11793: 
1.737     albertel 11794: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11795: 	    #no specific packages #how's our extension
                   11796: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11797: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11798: 					 \%metathesekeys);
                   11799: 	}
1.883     albertel 11800: 
                   11801: 	if (!exists($metaentry{':packages'})
                   11802: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11803: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11804: 		#no specific packages well let's get default then
                   11805: 		if ($key!~/^default&/) { next; }
1.488     albertel 11806: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11807: 					     \%metathesekeys);
                   11808: 	    }
                   11809: 	}
1.338     www      11810: # are there custom rights to evaluate
1.599     albertel 11811: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11812: 
1.338     www      11813:     #
                   11814:     # Importing a rights file here
1.339     albertel 11815:     #
                   11816: 	    unless ($depthcount) {
1.599     albertel 11817: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11818: 		my $dir=$filename;
                   11819: 		$dir=~s|[^/]*$||;
                   11820: 		$location=&filelocation($dir,$location);
1.736     albertel 11821: 		my $rights_metadata =
                   11822: 		    &metadata($uri,'keys',$location,'_rights',
                   11823: 			      $depthcount+1);
                   11824: 		foreach my $rights (split(',',$rights_metadata)) {
                   11825: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11826: 		    $metathesekeys{$rights}=1;
1.339     albertel 11827: 		}
                   11828: 	    }
                   11829: 	}
1.737     albertel 11830: 	# uniqifiy package listing
                   11831: 	my %seen;
                   11832: 	my @uniq_packages =
                   11833: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11834: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11835: 
1.1070    www      11836:         if ($importedparts) {
                   11837: # We had imported parts and need to rebuild partorder
                   11838:            $metaentry{':partorder'}='';
                   11839:            $metathesekeys{'partorder'}=1;
                   11840:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   11841:                if ($origfileimportpartids[$index] eq 'part') {
                   11842: # original part, part of the problem
                   11843:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   11844:                } else {
                   11845: # we have imported parts at this position
                   11846:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   11847:                }
                   11848:            }
                   11849:            $metaentry{':partorder'}=~s/^\,//;
                   11850:         }
                   11851: 
1.737     albertel 11852: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11853: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  11854: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 11855: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      11856: # this is the end of "was not already recently cached
1.71      www      11857:     }
1.599     albertel 11858:     return $metaentry{':'.$what};
1.261     albertel 11859: }
                   11860: 
1.488     albertel 11861: sub metadata_create_package_def {
1.483     albertel 11862:     my ($uri,$key,$package,$metathesekeys)=@_;
                   11863:     my ($pack,$name,$subp)=split(/\&/,$key);
                   11864:     if ($subp eq 'default') { next; }
                   11865:     
1.599     albertel 11866:     if (defined($metaentry{':packages'})) {
                   11867: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 11868:     } else {
1.599     albertel 11869: 	$metaentry{':packages'}=$package;
1.483     albertel 11870:     }
                   11871:     my $value=$packagetab{$key};
                   11872:     my $unikey;
                   11873:     $unikey='parameter_0_'.$name;
1.599     albertel 11874:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 11875:     $$metathesekeys{$unikey}=1;
1.599     albertel 11876:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11877: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 11878:     }
1.599     albertel 11879:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   11880: 	$metaentry{':'.$unikey}=
                   11881: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 11882:     }
                   11883: }
                   11884: 
1.261     albertel 11885: sub metadata_generate_part0 {
                   11886:     my ($metadata,$metacache,$uri) = @_;
                   11887:     my %allnames;
1.737     albertel 11888:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 11889: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 11890: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   11891: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 11892: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 11893: 	    $allnames{$name}=$part;
                   11894: 	  }
                   11895: 	}
                   11896:     }
                   11897:     foreach my $name (keys(%allnames)) {
                   11898:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 11899:       my $key=":parameter_0_$name";
1.261     albertel 11900:       $$metacache{"$key.part"}='0';
                   11901:       $$metacache{"$key.name"}=$name;
1.428     albertel 11902:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 11903: 					   $allnames{$name}.'_'.$name.
                   11904: 					   '.type'};
1.428     albertel 11905:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 11906: 			     '.display'};
1.644     www      11907:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11908:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11909:       $$metacache{"$key.display"}=$olddis;
                   11910:     }
1.71      www      11911: }
                   11912: 
1.764     albertel 11913: # ------------------------------------------------------ Devalidate title cache
                   11914: 
                   11915: sub devalidate_title_cache {
                   11916:     my ($url)=@_;
                   11917:     if (!$env{'request.course.id'}) { return; }
                   11918:     my $symb=&symbread($url);
                   11919:     if (!$symb) { return; }
                   11920:     my $key=$env{'request.course.id'}."\0".$symb;
                   11921:     &devalidate_cache_new('title',$key);
                   11922: }
                   11923: 
1.1014    droeschl 11924: # ------------------------------------------------- Get the title of a course
                   11925: 
                   11926: sub current_course_title {
                   11927:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11928: }
1.301     www      11929: # ------------------------------------------------- Get the title of a resource
                   11930: 
                   11931: sub gettitle {
                   11932:     my $urlsymb=shift;
                   11933:     my $symb=&symbread($urlsymb);
1.534     albertel 11934:     if ($symb) {
1.620     albertel 11935: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11936: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11937: 	if (defined($cached)) { 
                   11938: 	    return $result;
                   11939: 	}
1.534     albertel 11940: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11941: 	my $title='';
1.907     albertel 11942: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11943: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11944: 	} else {
                   11945: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11946: 		    &GDBM_READER(),0640)) {
                   11947: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11948: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11949: 		untie(%bighash);
                   11950: 	    }
1.534     albertel 11951: 	}
                   11952: 	$title=~s/\&colon\;/\:/gs;
                   11953: 	if ($title) {
1.1159    www      11954: # Remember both $symb and $title for dynamic metadata
                   11955:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11956:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11957: # Cache this title and then return it
1.599     albertel 11958: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11959: 	}
                   11960: 	$urlsymb=$url;
                   11961:     }
                   11962:     my $title=&metadata($urlsymb,'title');
                   11963:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11964:     return $title;
1.301     www      11965: }
1.613     albertel 11966: 
1.614     albertel 11967: sub get_slot {
                   11968:     my ($which,$cnum,$cdom)=@_;
                   11969:     if (!$cnum || !$cdom) {
1.790     albertel 11970: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11971: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11972: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11973:     }
1.703     albertel 11974:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11975:     my %slotinfo;
                   11976:     if (exists($remembered{$key})) {
                   11977: 	$slotinfo{$which} = $remembered{$key};
                   11978:     } else {
                   11979: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11980: 	&Apache::lonhomework::showhash(%slotinfo);
                   11981: 	my ($tmp)=keys(%slotinfo);
                   11982: 	if ($tmp=~/^error:/) { return (); }
                   11983: 	$remembered{$key} = $slotinfo{$which};
                   11984:     }
1.616     albertel 11985:     if (ref($slotinfo{$which}) eq 'HASH') {
                   11986: 	return %{$slotinfo{$which}};
                   11987:     }
                   11988:     return $slotinfo{$which};
1.614     albertel 11989: }
1.1150    raeburn  11990: 
                   11991: sub get_reservable_slots {
                   11992:     my ($cnum,$cdom,$uname,$udom) = @_;
                   11993:     my $now = time;
                   11994:     my $reservable_info;
                   11995:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   11996:     if (exists($remembered{$key})) {
                   11997:         $reservable_info = $remembered{$key};
                   11998:     } else {
                   11999:         my %resv;
                   12000:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12001:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12002:         $reservable_info = \%resv;
                   12003:         $remembered{$key} = $reservable_info;
                   12004:     }
                   12005:     return $reservable_info;
                   12006: }
                   12007: 
                   12008: sub get_course_slots {
                   12009:     my ($cnum,$cdom) = @_;
                   12010:     my $hashid=$cnum.':'.$cdom;
                   12011:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12012:     if (defined($cached)) {
                   12013:         if (ref($result) eq 'HASH') {
                   12014:             return %{$result};
                   12015:         }
                   12016:     } else {
                   12017:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12018:         my ($tmp) = keys(%slots);
                   12019:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  12020:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12021:             return %slots;
                   12022:         }
                   12023:     }
                   12024:     return;
                   12025: }
                   12026: 
                   12027: sub devalidate_slots_cache {
                   12028:     my ($cnum,$cdom)=@_;
                   12029:     my $hashid=$cnum.':'.$cdom;
                   12030:     &devalidate_cache_new('allslots',$hashid);
                   12031: }
                   12032: 
1.1181    raeburn  12033: sub get_coursechange {
                   12034:     my ($cdom,$cnum) = @_;
                   12035:     if ($cdom eq '' || $cnum eq '') {
                   12036:         return unless ($env{'request.course.id'});
                   12037:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12038:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12039:     }
                   12040:     my $hashid=$cdom.'_'.$cnum;
                   12041:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12042:     if ((defined($cached)) && ($change ne '')) {
                   12043:         return $change;
                   12044:     } else {
                   12045:         my %crshash;
                   12046:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12047:         if ($crshash{'internal.contentchange'} eq '') {
                   12048:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12049:             if ($change eq '') {
                   12050:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12051:                 $change = $crshash{'internal.created'};
                   12052:             }
                   12053:         } else {
                   12054:             $change = $crshash{'internal.contentchange'};
                   12055:         }
                   12056:         my $cachetime = 600;
                   12057:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12058:     }
                   12059:     return $change;
                   12060: }
                   12061: 
                   12062: sub devalidate_coursechange_cache {
                   12063:     my ($cnum,$cdom)=@_;
                   12064:     my $hashid=$cnum.':'.$cdom;
                   12065:     &devalidate_cache_new('crschange',$hashid);
                   12066: }
                   12067: 
1.31      www      12068: # ------------------------------------------------- Update symbolic store links
                   12069: 
                   12070: sub symblist {
                   12071:     my ($mapname,%newhash)=@_;
1.438     www      12072:     $mapname=&deversion(&declutter($mapname));
1.31      www      12073:     my %hash;
1.620     albertel 12074:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12075:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12076:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12077: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12078: 		next if ($url eq 'last_known'
                   12079: 			 && $env{'form.no_update_last_known'});
                   12080: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12081: 						    $newhash{$url}->[1],
                   12082: 						    $newhash{$url}->[0]);
1.191     harris41 12083:             }
1.31      www      12084:             if (untie(%hash)) {
                   12085: 		return 'ok';
                   12086:             }
                   12087:         }
                   12088:     }
                   12089:     return 'error';
1.212     www      12090: }
                   12091: 
                   12092: # --------------------------------------------------------------- Verify a symb
                   12093: 
                   12094: sub symbverify {
1.1190    raeburn  12095:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12096:     my $thisfn=$thisurl;
1.439     www      12097:     $thisfn=&declutter($thisfn);
1.215     www      12098: # direct jump to resource in page or to a sequence - will construct own symbs
                   12099:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12100: # check URL part
1.409     www      12101:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12102: 
1.431     www      12103:     unless ($url eq $thisfn) { return 0; }
1.213     www      12104: 
1.216     www      12105:     $symb=&symbclean($symb);
1.510     www      12106:     $thisurl=&deversion($thisurl);
1.439     www      12107:     $thisfn=&deversion($thisfn);
1.213     www      12108: 
                   12109:     my %bighash;
                   12110:     my $okay=0;
1.431     www      12111: 
1.620     albertel 12112:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12113:                             &GDBM_READER(),0640)) {
1.1204    raeburn  12114:         my $noclutter;
1.1032    raeburn  12115:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12116:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  12117:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12118:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12119:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12120:                 $noclutter = 1;
                   12121:             }
                   12122:         }
                   12123:         my $ids;
                   12124:         if ($noclutter) {
                   12125:             $ids=$bighash{'ids_'.$thisurl};
                   12126:         } else {
                   12127:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12128:         }
1.1102    raeburn  12129:         unless ($ids) {
                   12130:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   12131:             $ids=$bighash{$idkey};
1.216     www      12132:         }
                   12133:         if ($ids) {
                   12134: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  12135:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  12136:                 $symb =~ s/\?.+$//;
1.1202    raeburn  12137:             }
1.800     albertel 12138: 	    foreach my $id (split(/\,/,$ids)) {
                   12139: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12140:                if (
                   12141:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  12142:    eq $symb) {
                   12143:                    if (ref($encstate)) {
                   12144:                        $$encstate = $bighash{'encrypted_'.$id};
                   12145:                    }
1.620     albertel 12146: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  12147: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   12148:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  12149: 		       $okay=1;
1.1202    raeburn  12150:                        last;
1.582     albertel 12151: 		   }
                   12152: 	       }
1.216     www      12153: 	   }
                   12154:         }
1.213     www      12155: 	untie(%bighash);
                   12156:     }
                   12157:     return $okay;
1.31      www      12158: }
                   12159: 
1.210     www      12160: # --------------------------------------------------------------- Clean-up symb
                   12161: 
                   12162: sub symbclean {
                   12163:     my $symb=shift;
1.568     albertel 12164:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12165: # remove version from map
                   12166:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12167: 
1.210     www      12168: # remove version from URL
                   12169:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12170: 
1.507     www      12171: # remove wrapper
                   12172: 
1.510     www      12173:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12174:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12175:     return $symb;
1.409     www      12176: }
                   12177: 
                   12178: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12179: 
                   12180: sub encode_symb {
                   12181:     my ($map,$resid,$url)=@_;
                   12182:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12183: }
1.409     www      12184: 
                   12185: sub decode_symb {
1.568     albertel 12186:     my $symb=shift;
                   12187:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12188:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12189:     return (&fixversion($map),$resid,&fixversion($url));
                   12190: }
                   12191: 
                   12192: sub fixversion {
                   12193:     my $fn=shift;
1.609     banghart 12194:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12195:     my %bighash;
                   12196:     my $uri=&clutter($fn);
1.620     albertel 12197:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12198: # is this cached?
1.599     albertel 12199:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12200:     if (defined($cached)) { return $result; }
                   12201: # unfortunately not cached, or expired
1.620     albertel 12202:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12203: 	    &GDBM_READER(),0640)) {
                   12204:  	if ($bighash{'version_'.$uri}) {
                   12205:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12206:  	    unless (($version eq 'mostrecent') || 
                   12207: 		    ($version==&getversion($uri))) {
1.440     www      12208:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12209:  	    }
                   12210:  	}
                   12211:  	untie %bighash;
1.413     www      12212:     }
1.599     albertel 12213:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12214: }
                   12215: 
                   12216: sub deversion {
                   12217:     my $url=shift;
                   12218:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12219:     return $url;
1.210     www      12220: }
                   12221: 
1.31      www      12222: # ------------------------------------------------------ Return symb list entry
                   12223: 
                   12224: sub symbread {
1.1282    raeburn  12225:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  12226:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  12227:     if (defined($env{$cache_str})) {
                   12228:         if ($ignorecachednull) {
                   12229:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12230:         } else {
                   12231:             return $env{$cache_str};
                   12232:         }
                   12233:     }
1.242     www      12234: # no filename provided? try from environment
1.1265    raeburn  12235:     unless ($thisfn) {
1.620     albertel 12236:         if ($env{'request.symb'}) {
                   12237: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 12238: 	}
1.620     albertel 12239: 	$thisfn=$env{'request.filename'};
1.44      www      12240:     }
1.569     albertel 12241:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12242: # is that filename actually a symb? Verify, clean, and return
                   12243:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12244: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 12245: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12246: 	}
1.242     www      12247:     }
1.44      www      12248:     $thisfn=declutter($thisfn);
1.31      www      12249:     my %hash;
1.37      www      12250:     my %bighash;
                   12251:     my $syval='';
1.620     albertel 12252:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12253:         my $targetfn = $thisfn;
1.609     banghart 12254:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12255:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12256:         }
1.687     albertel 12257: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12258: 	    $targetfn=$1;
                   12259: 	}
1.620     albertel 12260:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12261:                       &GDBM_READER(),0640)) {
1.481     raeburn  12262: 	    $syval=$hash{$targetfn};
1.37      www      12263:             untie(%hash);
                   12264:         }
                   12265: # ---------------------------------------------------------- There was an entry
                   12266:         if ($syval) {
1.601     albertel 12267: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12268: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12269: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12270: 		    #return $env{$cache_str}='';
1.601     albertel 12271: 		#}    
                   12272: 		#$syval.=$1;
                   12273: 	    #}
1.37      www      12274:         } else {
                   12275: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12276:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12277:                             &GDBM_READER(),0640)) {
1.37      www      12278: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12279:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12280:               unless ($ids) { 
                   12281:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12282:               }
                   12283:               unless ($ids) {
                   12284: # alias?
                   12285: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12286:               }
1.37      www      12287:               if ($ids) {
                   12288: # ------------------------------------------------------------------- Has ID(s)
                   12289:                  my @possibilities=split(/\,/,$ids);
1.39      www      12290:                  if ($#possibilities==0) {
                   12291: # ----------------------------------------------- There is only one possibility
1.37      www      12292: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12293: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12294: 						    $resid,$thisfn);
1.1282    raeburn  12295:                      if (ref($possibles) eq 'HASH') {
                   12296:                          $possibles->{$syval} = 1;    
                   12297:                      }
                   12298:                      if ($checkforblock) {
                   12299:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12300:                          if (@blockers) {
                   12301:                              $syval = '';
                   12302:                              return;
                   12303:                          }
                   12304:                      }
                   12305:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      12306: # ------------------------------------------ There is more than one possibility
                   12307:                      my $realpossible=0;
1.800     albertel 12308:                      foreach my $id (@possibilities) {
                   12309: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  12310:                          my $canaccess;
                   12311:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12312:                              $canaccess = 1;
                   12313:                          } else { 
                   12314:                              $canaccess = &allowed('bre',$file);
                   12315:                          }
                   12316:                          if ($canaccess) {
                   12317:          		     my ($mapid,$resid)=split(/\./,$id);
                   12318:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12319:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12320: 						             $resid,$thisfn);
                   12321:                                  if (ref($possibles) eq 'HASH') {
                   12322:                                      $possibles->{$syval} = 1;
                   12323:                                  }
                   12324:                                  if ($checkforblock) {
                   12325:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12326:                                      unless (@blockers > 0) {
                   12327:                                          $syval = $poss_syval;
                   12328:                                          $realpossible++;
                   12329:                                      }
                   12330:                                  } else {
                   12331:                                      $syval = $poss_syval;
                   12332:                                      $realpossible++;
                   12333:                                  }
                   12334:                              }
1.39      www      12335: 			 }
1.191     harris41 12336:                      }
1.39      www      12337: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12338:                  } else {
                   12339:                      $syval='';
1.37      www      12340:                  }
                   12341: 	      }
1.1282    raeburn  12342:               untie(%bighash);
1.481     raeburn  12343:            }
1.31      www      12344:         }
1.62      www      12345:         if ($syval) {
1.620     albertel 12346: 	    return $env{$cache_str}=$syval;
1.62      www      12347:         }
1.31      www      12348:     }
1.949     raeburn  12349:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12350:     return $env{$cache_str}='';
1.31      www      12351: }
                   12352: 
                   12353: # ---------------------------------------------------------- Return random seed
                   12354: 
1.32      www      12355: sub numval {
                   12356:     my $txt=shift;
                   12357:     $txt=~tr/A-J/0-9/;
                   12358:     $txt=~tr/a-j/0-9/;
                   12359:     $txt=~tr/K-T/0-9/;
                   12360:     $txt=~tr/k-t/0-9/;
                   12361:     $txt=~tr/U-Z/0-5/;
                   12362:     $txt=~tr/u-z/0-5/;
                   12363:     $txt=~s/\D//g;
1.564     albertel 12364:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12365:     return int($txt);
1.368     albertel 12366: }
                   12367: 
1.484     albertel 12368: sub numval2 {
                   12369:     my $txt=shift;
                   12370:     $txt=~tr/A-J/0-9/;
                   12371:     $txt=~tr/a-j/0-9/;
                   12372:     $txt=~tr/K-T/0-9/;
                   12373:     $txt=~tr/k-t/0-9/;
                   12374:     $txt=~tr/U-Z/0-5/;
                   12375:     $txt=~tr/u-z/0-5/;
                   12376:     $txt=~s/\D//g;
                   12377:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12378:     my $total;
                   12379:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12380:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12381:     return int($total);
                   12382: }
                   12383: 
1.575     albertel 12384: sub numval3 {
                   12385:     use integer;
                   12386:     my $txt=shift;
                   12387:     $txt=~tr/A-J/0-9/;
                   12388:     $txt=~tr/a-j/0-9/;
                   12389:     $txt=~tr/K-T/0-9/;
                   12390:     $txt=~tr/k-t/0-9/;
                   12391:     $txt=~tr/U-Z/0-5/;
                   12392:     $txt=~tr/u-z/0-5/;
                   12393:     $txt=~s/\D//g;
                   12394:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12395:     my $total;
                   12396:     foreach my $val (@txts) { $total+=$val; }
                   12397:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12398:     return $total;
                   12399: }
                   12400: 
1.675     albertel 12401: sub digest {
                   12402:     my ($data)=@_;
                   12403:     my $digest=&Digest::MD5::md5($data);
                   12404:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12405:     my ($e,$f);
                   12406:     {
                   12407:         use integer;
                   12408:         $e=($a+$b);
                   12409:         $f=($c+$d);
                   12410:         if ($_64bit) {
                   12411:             $e=(($e<<32)>>32);
                   12412:             $f=(($f<<32)>>32);
                   12413:         }
                   12414:     }
                   12415:     if (wantarray) {
                   12416: 	return ($e,$f);
                   12417:     } else {
                   12418: 	my $g;
                   12419: 	{
                   12420: 	    use integer;
                   12421: 	    $g=($e+$f);
                   12422: 	    if ($_64bit) {
                   12423: 		$g=(($g<<32)>>32);
                   12424: 	    }
                   12425: 	}
                   12426: 	return $g;
                   12427:     }
                   12428: }
                   12429: 
1.368     albertel 12430: sub latest_rnd_algorithm_id {
1.675     albertel 12431:     return '64bit5';
1.366     albertel 12432: }
1.32      www      12433: 
1.503     albertel 12434: sub get_rand_alg {
                   12435:     my ($courseid)=@_;
1.790     albertel 12436:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12437:     if ($courseid) {
1.620     albertel 12438: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12439:     }
                   12440:     return &latest_rnd_algorithm_id();
                   12441: }
                   12442: 
1.562     albertel 12443: sub validCODE {
                   12444:     my ($CODE)=@_;
                   12445:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12446:     return 0;
                   12447: }
                   12448: 
1.491     albertel 12449: sub getCODE {
1.620     albertel 12450:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12451:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12452: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12453: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12454: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12455:     }
                   12456:     return undef;
                   12457: }
1.1133    foxr     12458: #
                   12459: #  Determines the random seed for a specific context:
                   12460: #
                   12461: # parameters:
                   12462: #   symb      - in course context the symb for the seed.
                   12463: #   course_id - The course id of the form domain_coursenum.
                   12464: #   domain    - Domain for the user.
                   12465: #   course    - Course for the user.
                   12466: #   cenv      - environment of the course.
                   12467: #
                   12468: # NOTE:
                   12469: #   All parameters are picked out of the environment if missing
                   12470: #   or not defined.
                   12471: #   If a symb cannot be determined the current time is used instead.
                   12472: #
                   12473: #  For a given well defined symb, courside, domain, username,
                   12474: #  and course environment, the seed is reproducible.
                   12475: #
1.31      www      12476: sub rndseed {
1.1133    foxr     12477:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12478:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12479:     if (!defined($symb)) {
1.366     albertel 12480: 	unless ($symb=$wsymb) { return time; }
                   12481:     }
1.1146    foxr     12482:     if (!defined $courseid) { 
                   12483: 	$courseid=$wcourseid; 
                   12484:     }
                   12485:     if (!defined $domain) { $domain=$wdomain; }
                   12486:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12487: 
                   12488:     my $which;
                   12489:     if (defined($cenv->{'rndseed'})) {
                   12490: 	$which = $cenv->{'rndseed'};
                   12491:     } else {
                   12492: 	$which =&get_rand_alg($courseid);
                   12493:     }
1.491     albertel 12494:     if (defined(&getCODE())) {
1.1133    foxr     12495: 
1.675     albertel 12496: 	if ($which eq '64bit5') {
                   12497: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12498: 	} elsif ($which eq '64bit4') {
1.575     albertel 12499: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12500: 	} else {
                   12501: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12502: 	}
1.675     albertel 12503:     } elsif ($which eq '64bit5') {
                   12504: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12505:     } elsif ($which eq '64bit4') {
                   12506: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12507:     } elsif ($which eq '64bit3') {
                   12508: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12509:     } elsif ($which eq '64bit2') {
                   12510: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12511:     } elsif ($which eq '64bit') {
                   12512: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12513:     }
                   12514:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12515: }
                   12516: 
                   12517: sub rndseed_32bit {
                   12518:     my ($symb,$courseid,$domain,$username)=@_;
                   12519:     {
                   12520: 	use integer;
                   12521: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12522: 	my $symbseed=numval($symb) << 22;
                   12523: 	my $namechck=unpack("%32C*",$username) << 17;
                   12524: 	my $nameseed=numval($username) << 12;
                   12525: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12526: 	my $courseseed=unpack("%32C*",$courseid);
                   12527: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12528: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12529: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12530: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12531: 	return $num;
                   12532:     }
                   12533: }
                   12534: 
                   12535: sub rndseed_64bit {
                   12536:     my ($symb,$courseid,$domain,$username)=@_;
                   12537:     {
                   12538: 	use integer;
                   12539: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12540: 	my $symbseed=numval($symb) << 10;
                   12541: 	my $namechck=unpack("%32S*",$username);
                   12542: 	
                   12543: 	my $nameseed=numval($username) << 21;
                   12544: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12545: 	my $courseseed=unpack("%32S*",$courseid);
                   12546: 	
                   12547: 	my $num1=$symbchck+$symbseed+$namechck;
                   12548: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12549: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12550: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12551: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12552: 	return "$num1,$num2";
1.155     albertel 12553:     }
1.366     albertel 12554: }
                   12555: 
1.443     albertel 12556: sub rndseed_64bit2 {
                   12557:     my ($symb,$courseid,$domain,$username)=@_;
                   12558:     {
                   12559: 	use integer;
                   12560: 	# strings need to be an even # of cahracters long, it it is odd the
                   12561:         # last characters gets thrown away
                   12562: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12563: 	my $symbseed=numval($symb) << 10;
                   12564: 	my $namechck=unpack("%32S*",$username.' ');
                   12565: 	
                   12566: 	my $nameseed=numval($username) << 21;
1.501     albertel 12567: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12568: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12569: 	
                   12570: 	my $num1=$symbchck+$symbseed+$namechck;
                   12571: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12572: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12573: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12574: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12575: 	return "$num1,$num2";
                   12576:     }
                   12577: }
                   12578: 
                   12579: sub rndseed_64bit3 {
                   12580:     my ($symb,$courseid,$domain,$username)=@_;
                   12581:     {
                   12582: 	use integer;
                   12583: 	# strings need to be an even # of cahracters long, it it is odd the
                   12584:         # last characters gets thrown away
                   12585: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12586: 	my $symbseed=numval2($symb) << 10;
                   12587: 	my $namechck=unpack("%32S*",$username.' ');
                   12588: 	
                   12589: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12590: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12591: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12592: 	
                   12593: 	my $num1=$symbchck+$symbseed+$namechck;
                   12594: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12595: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12596: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12597: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12598: 	
1.503     albertel 12599: 	return "$num1:$num2";
1.443     albertel 12600:     }
                   12601: }
                   12602: 
1.575     albertel 12603: sub rndseed_64bit4 {
                   12604:     my ($symb,$courseid,$domain,$username)=@_;
                   12605:     {
                   12606: 	use integer;
                   12607: 	# strings need to be an even # of cahracters long, it it is odd the
                   12608:         # last characters gets thrown away
                   12609: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12610: 	my $symbseed=numval3($symb) << 10;
                   12611: 	my $namechck=unpack("%32S*",$username.' ');
                   12612: 	
                   12613: 	my $nameseed=numval3($username) << 21;
                   12614: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12615: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12616: 	
                   12617: 	my $num1=$symbchck+$symbseed+$namechck;
                   12618: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12619: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12620: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12621: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12622: 	
1.575     albertel 12623: 	return "$num1:$num2";
                   12624:     }
                   12625: }
                   12626: 
1.675     albertel 12627: sub rndseed_64bit5 {
                   12628:     my ($symb,$courseid,$domain,$username)=@_;
                   12629:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12630:     return "$num1:$num2";
                   12631: }
                   12632: 
1.366     albertel 12633: sub rndseed_CODE_64bit {
                   12634:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12635:     {
1.366     albertel 12636: 	use integer;
1.443     albertel 12637: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12638: 	my $symbseed=numval2($symb);
1.491     albertel 12639: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12640: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12641: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12642: 	my $num1=$symbseed+$CODEchck;
                   12643: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12644: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12645: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12646: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12647: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12648: 	return "$num1:$num2";
1.366     albertel 12649:     }
                   12650: }
                   12651: 
1.575     albertel 12652: sub rndseed_CODE_64bit4 {
                   12653:     my ($symb,$courseid,$domain,$username)=@_;
                   12654:     {
                   12655: 	use integer;
                   12656: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12657: 	my $symbseed=numval3($symb);
                   12658: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12659: 	my $CODEseed=numval3(&getCODE());
                   12660: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12661: 	my $num1=$symbseed+$CODEchck;
                   12662: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12663: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12664: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12665: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12666: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12667: 	return "$num1:$num2";
                   12668:     }
                   12669: }
                   12670: 
1.675     albertel 12671: sub rndseed_CODE_64bit5 {
                   12672:     my ($symb,$courseid,$domain,$username)=@_;
                   12673:     my $code = &getCODE();
                   12674:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12675:     return "$num1:$num2";
                   12676: }
                   12677: 
1.366     albertel 12678: sub setup_random_from_rndseed {
                   12679:     my ($rndseed)=@_;
1.503     albertel 12680:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  12681:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12682:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12683:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12684:         } else {
                   12685:             &Math::Random::random_set_seed($num1,$num2);
                   12686:         }
1.366     albertel 12687:     } else {
                   12688: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12689:     }
1.36      albertel 12690: }
                   12691: 
1.474     albertel 12692: sub latest_receipt_algorithm_id {
1.835     albertel 12693:     return 'receipt3';
1.474     albertel 12694: }
                   12695: 
1.480     www      12696: sub recunique {
                   12697:     my $fucourseid=shift;
                   12698:     my $unique;
1.835     albertel 12699:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12700: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12701: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12702:     } else {
                   12703: 	$unique=$perlvar{'lonReceipt'};
                   12704:     }
                   12705:     return unpack("%32C*",$unique);
                   12706: }
                   12707: 
                   12708: sub recprefix {
                   12709:     my $fucourseid=shift;
                   12710:     my $prefix;
1.835     albertel 12711:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12712: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12713: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12714:     } else {
                   12715: 	$prefix=$perlvar{'lonHostID'};
                   12716:     }
                   12717:     return unpack("%32C*",$prefix);
                   12718: }
                   12719: 
1.76      www      12720: sub ireceipt {
1.474     albertel 12721:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12722: 
                   12723:     my $return =&recprefix($fucourseid).'-';
                   12724: 
                   12725:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12726: 	$env{'request.state'} eq 'construct') {
                   12727: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12728: 	return $return;
                   12729:     }
                   12730: 
1.76      www      12731:     my $cuname=unpack("%32C*",$funame);
                   12732:     my $cudom=unpack("%32C*",$fudom);
                   12733:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12734:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12735:     my $cunique=&recunique($fucourseid);
1.474     albertel 12736:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12737:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12738: 
1.790     albertel 12739: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12740: 			       
                   12741: 	$return.= ($cunique%$cuname+
                   12742: 		   $cunique%$cudom+
                   12743: 		   $cusymb%$cuname+
                   12744: 		   $cusymb%$cudom+
                   12745: 		   $cucourseid%$cuname+
                   12746: 		   $cucourseid%$cudom+
                   12747: 		   $cpart%$cuname+
                   12748: 		   $cpart%$cudom);
                   12749:     } else {
                   12750: 	$return.= ($cunique%$cuname+
                   12751: 		   $cunique%$cudom+
                   12752: 		   $cusymb%$cuname+
                   12753: 		   $cusymb%$cudom+
                   12754: 		   $cucourseid%$cuname+
                   12755: 		   $cucourseid%$cudom);
                   12756:     }
                   12757:     return $return;
1.76      www      12758: }
                   12759: 
                   12760: sub receipt {
1.474     albertel 12761:     my ($part)=@_;
1.790     albertel 12762:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12763:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12764: }
1.260     ng       12765: 
1.790     albertel 12766: sub whichuser {
                   12767:     my ($passedsymb)=@_;
                   12768:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12769:     if (defined($env{'form.grade_symb'})) {
                   12770: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12771: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12772: 	if (!$allowed &&
                   12773: 	    exists($env{'request.course.sec'}) &&
                   12774: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12775: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12776: 			      '/'.$env{'request.course.sec'});
                   12777: 	}
                   12778: 	if ($allowed) {
                   12779: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12780: 	    $courseid=$tmp_courseid;
                   12781: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12782: 	    ($name)=&get_env_multiple('form.grade_username');
                   12783: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12784: 	}
                   12785:     }
                   12786:     if (!$passedsymb) {
                   12787: 	$symb=&symbread();
                   12788:     } else {
                   12789: 	$symb=$passedsymb;
                   12790:     }
                   12791:     $courseid=$env{'request.course.id'};
                   12792:     $domain=$env{'user.domain'};
                   12793:     $name=$env{'user.name'};
                   12794:     if ($name eq 'public' && $domain eq 'public') {
                   12795: 	if (!defined($env{'form.username'})) {
                   12796: 	    $env{'form.username'}.=time.rand(10000000);
                   12797: 	}
                   12798: 	$name.=$env{'form.username'};
                   12799:     }
                   12800:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12801: 
                   12802: }
                   12803: 
1.36      albertel 12804: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12805: # returns either the contents of the file or 
                   12806: # -1 if the file doesn't exist
1.481     raeburn  12807: #
                   12808: # if the target is a file that was uploaded via DOCS, 
                   12809: # a check will be made to see if a current copy exists on the local server,
                   12810: # if it does this will be served, otherwise a copy will be retrieved from
                   12811: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12812: # the local server.   
1.472     albertel 12813: 
1.36      albertel 12814: sub getfile {
1.538     albertel 12815:     my ($file) = @_;
1.609     banghart 12816:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12817:     &repcopy($file);
                   12818:     return &readfile($file);
                   12819: }
                   12820: 
                   12821: sub repcopy_userfile {
                   12822:     my ($file)=@_;
1.1142    raeburn  12823:     my $londocroot = $perlvar{'lonDocRoot'};
                   12824:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12825:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12826:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12827: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12828:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12829:     if (-e "$file") {
1.828     www      12830: # we already have a local copy, check it out
1.538     albertel 12831: 	my @fileinfo = stat($file);
1.828     www      12832: 	my $rtncode;
                   12833: 	my $info;
1.538     albertel 12834: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12835: 	if ($lwpresp ne 'ok') {
1.828     www      12836: # there is no such file anymore, even though we had a local copy
1.482     albertel 12837: 	    if ($rtncode eq '404') {
1.538     albertel 12838: 		unlink($file);
1.482     albertel 12839: 	    }
                   12840: 	    return -1;
                   12841: 	}
                   12842: 	if ($info < $fileinfo[9]) {
1.828     www      12843: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12844: 	    return 'ok';
1.828     www      12845: 	} else {
                   12846: # the file is outdated, get rid of it
                   12847: 	    unlink($file);
1.482     albertel 12848: 	}
1.828     www      12849:     }
                   12850: # one way or the other, at this point, we don't have the file
                   12851: # construct the correct path for the file
                   12852:     my @parts = ($cdom,$cnum); 
                   12853:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12854: 	push @parts, split(/\//,$1);
                   12855:     }
                   12856:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   12857:     foreach my $part (@parts) {
                   12858: 	$path .= '/'.$part;
                   12859: 	if (!-e $path) {
                   12860: 	    mkdir($path,0770);
1.482     albertel 12861: 	}
                   12862:     }
1.828     www      12863: # now the path exists for sure
                   12864: # get a user agent
                   12865:     my $transferfile=$file.'.in.transfer';
                   12866: # FIXME: this should flock
                   12867:     if (-e $transferfile) { return 'ok'; }
                   12868:     my $request;
                   12869:     $uri=~s/^\///;
1.980     raeburn  12870:     my $homeserver = &homeserver($cnum,$cdom);
                   12871:     my $protocol = $protocol{$homeserver};
                   12872:     $protocol = 'http' if ($protocol ne 'https');
                   12873:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.1345    raeburn  12874:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828     www      12875: # did it work?
                   12876:     if ($response->is_error()) {
                   12877: 	unlink($transferfile);
                   12878: 	&logthis("Userfile repcopy failed for $uri");
                   12879: 	return -1;
                   12880:     }
                   12881: # worked, rename the transfer file
                   12882:     rename($transferfile,$file);
1.607     raeburn  12883:     return 'ok';
1.481     raeburn  12884: }
                   12885: 
1.517     albertel 12886: sub tokenwrapper {
                   12887:     my $uri=shift;
1.980     raeburn  12888:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 12889:     $uri=~s|^/||;
1.620     albertel 12890:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 12891:     my $token=$1;
1.552     albertel 12892:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   12893:     if ($udom && $uname && $file) {
                   12894: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  12895:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  12896:         my $homeserver = &homeserver($uname,$udom);
                   12897:         my $protocol = $protocol{$homeserver};
                   12898:         $protocol = 'http' if ($protocol ne 'https');
                   12899:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 12900:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   12901:                                '&tokenissued='.$perlvar{'lonHostID'};
                   12902:     } else {
                   12903:         return '/adm/notfound.html';
                   12904:     }
                   12905: }
                   12906: 
1.828     www      12907: # call with reqtype HEAD: get last modification time
                   12908: # call with reqtype GET: get the file contents
                   12909: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12910: #
1.481     raeburn  12911: sub getuploaded {
                   12912:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12913:     $uri=~s/^\///;
1.980     raeburn  12914:     my $homeserver = &homeserver($cnum,$cdom);
                   12915:     my $protocol = $protocol{$homeserver};
                   12916:     $protocol = 'http' if ($protocol ne 'https');
                   12917:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12918:     my $request=new HTTP::Request($reqtype,$uri);
1.1345    raeburn  12919:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481     raeburn  12920:     $$rtncode = $response->code;
1.482     albertel 12921:     if (! $response->is_success()) {
                   12922: 	return 'failed';
                   12923:     }      
                   12924:     if ($reqtype eq 'HEAD') {
1.486     www      12925: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12926:     } elsif ($reqtype eq 'GET') {
                   12927: 	$$info = $response->content;
1.472     albertel 12928:     }
1.482     albertel 12929:     return 'ok';
1.36      albertel 12930: }
                   12931: 
1.481     raeburn  12932: sub readfile {
                   12933:     my $file = shift;
                   12934:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12935:     my $fh;
                   12936:     open($fh,"<$file");
                   12937:     my $a='';
1.800     albertel 12938:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12939:     return $a;
                   12940: }
                   12941: 
1.36      albertel 12942: sub filelocation {
1.590     banghart 12943:     my ($dir,$file) = @_;
                   12944:     my $location;
                   12945:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12946: 
                   12947:     if ($file =~ m-^/adm/-) {
                   12948: 	$file=~s-^/adm/wrapper/-/-;
                   12949: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12950:     }
1.882     albertel 12951: 
1.1139    www      12952:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12953:         $location = $file;
1.609     banghart 12954:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12955:         my ($udom,$uname,$filename)=
1.811     albertel 12956:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12957:         my $home=&homeserver($uname,$udom);
                   12958:         my $is_me=0;
                   12959:         my @ids=&current_machine_ids();
                   12960:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12961:         if ($is_me) {
1.1117    foxr     12962:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12963:         } else {
                   12964:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12965:   	      $udom.'/'.$uname.'/'.$filename;
                   12966:         }
1.882     albertel 12967:     } elsif ($file =~ m-^/adm/-) {
                   12968: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12969:     } else {
                   12970:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12971:         $file=~s:^/(res|priv)/:/:;
                   12972:         my $space=$1;
1.590     banghart 12973:         if ( !( $file =~ m:^/:) ) {
                   12974:             $location = $dir. '/'.$file;
                   12975:         } else {
1.1142    raeburn  12976:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12977:         }
1.59      albertel 12978:     }
1.590     banghart 12979:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12980:     while ($location=~m{/\.\./}) {
                   12981: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12982: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   12983: 	} else {
                   12984: 	    $location=~ s{/\.\./}{/}g;
                   12985: 	}
                   12986:     } #remove dir/..
1.590     banghart 12987:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   12988:     return $location;
1.46      www      12989: }
1.36      albertel 12990: 
1.46      www      12991: sub hreflocation {
                   12992:     my ($dir,$file)=@_;
1.980     raeburn  12993:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 12994: 	$file=filelocation($dir,$file);
1.700     albertel 12995:     } elsif ($file=~m-^/adm/-) {
                   12996: 	$file=~s-^/adm/wrapper/-/-;
                   12997: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 12998:     }
                   12999:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13000: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13001:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13002: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13003: 	        {/uploaded/$1/$2/}x;
1.46      www      13004:     }
1.913     albertel 13005:     if ($file=~ m{^/userfiles/}) {
                   13006: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13007:     }
1.462     albertel 13008:     return $file;
1.465     albertel 13009: }
                   13010: 
1.1139    www      13011: 
                   13012: 
                   13013: 
                   13014: 
1.465     albertel 13015: sub current_machine_domains {
1.853     albertel 13016:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13017: }
                   13018: 
                   13019: sub machine_domains {
                   13020:     my ($hostname) = @_;
1.465     albertel 13021:     my @domains;
1.838     albertel 13022:     my %hostname = &all_hostnames();
1.465     albertel 13023:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13024: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13025: 	if ($hostname eq $name) {
1.844     albertel 13026: 	    push(@domains,&host_domain($id));
1.465     albertel 13027: 	}
                   13028:     }
                   13029:     return @domains;
                   13030: }
                   13031: 
                   13032: sub current_machine_ids {
1.853     albertel 13033:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13034: }
                   13035: 
                   13036: sub machine_ids {
                   13037:     my ($hostname) = @_;
                   13038:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13039:     my @ids;
1.888     albertel 13040:     my %name_to_host = &all_names();
1.889     albertel 13041:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13042: 	return @{ $name_to_host{$hostname} };
                   13043:     }
                   13044:     return;
1.31      www      13045: }
                   13046: 
1.824     raeburn  13047: sub additional_machine_domains {
                   13048:     my @domains;
                   13049:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   13050:     while( my $line = <$fh>) {
                   13051:         $line =~ s/\s//g;
                   13052:         push(@domains,$line);
                   13053:     }
                   13054:     return @domains;
                   13055: }
                   13056: 
                   13057: sub default_login_domain {
                   13058:     my $domain = $perlvar{'lonDefDomain'};
                   13059:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13060:     foreach my $posdom (&current_machine_domains(),
                   13061:                         &additional_machine_domains()) {
                   13062:         if (lc($posdom) eq lc($testdomain)) {
                   13063:             $domain=$posdom;
                   13064:             last;
                   13065:         }
                   13066:     }
                   13067:     return $domain;
                   13068: }
                   13069: 
1.31      www      13070: # ------------------------------------------------------------- Declutters URLs
                   13071: 
                   13072: sub declutter {
                   13073:     my $thisfn=shift;
1.569     albertel 13074:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  13075:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13076:         $thisfn=~s{^/home/httpd/html}{};
                   13077:     }
1.31      www      13078:     $thisfn=~s/^\///;
1.697     albertel 13079:     $thisfn=~s|^adm/wrapper/||;
                   13080:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13081:     $thisfn=~s/^res\///;
1.1172    bisitz   13082:     $thisfn=~s/^priv\///;
1.1032    raeburn  13083:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13084:         $thisfn=~s/\?.+$//;
                   13085:     }
1.268     www      13086:     return $thisfn;
                   13087: }
                   13088: 
                   13089: # ------------------------------------------------------------- Clutter up URLs
                   13090: 
                   13091: sub clutter {
                   13092:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13093:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13094: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13095:        $thisfn='/res'.$thisfn; 
                   13096:     }
1.1031    raeburn  13097:     if ($thisfn !~m|^/adm|) {
                   13098: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13099: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13100: 	} else {
                   13101: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13102: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13103: 	    if ($embstyle eq 'ssi'
                   13104: 		|| ($embstyle eq 'hdn')
                   13105: 		|| ($embstyle eq 'rat')
                   13106: 		|| ($embstyle eq 'prv')
                   13107: 		|| ($embstyle eq 'ign')) {
                   13108: 		#do nothing with these
                   13109: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13110: 		|| ($embstyle eq 'emb')
                   13111: 		|| ($embstyle eq 'wrp')) {
                   13112: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13113: 	    } elsif ($embstyle eq 'unk'
                   13114: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13115: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13116: 	    } else {
1.718     www      13117: #		&logthis("Got a blank emb style");
1.695     albertel 13118: 	    }
1.694     albertel 13119: 	}
1.1343    raeburn  13120:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298    raeburn  13121:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 13122:     }
1.31      www      13123:     return $thisfn;
1.12      www      13124: }
                   13125: 
1.787     albertel 13126: sub clutter_with_no_wrapper {
                   13127:     my $uri = &clutter(shift);
                   13128:     if ($uri =~ m-^/adm/-) {
                   13129: 	$uri =~ s-^/adm/wrapper/-/-;
                   13130: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13131:     }
                   13132:     return $uri;
                   13133: }
                   13134: 
1.557     albertel 13135: sub freeze_escape {
                   13136:     my ($value)=@_;
                   13137:     if (ref($value)) {
                   13138: 	$value=&nfreeze($value);
                   13139: 	return '__FROZEN__'.&escape($value);
                   13140:     }
                   13141:     return &escape($value);
                   13142: }
                   13143: 
1.11      www      13144: 
1.557     albertel 13145: sub thaw_unescape {
                   13146:     my ($value)=@_;
                   13147:     if ($value =~ /^__FROZEN__/) {
                   13148: 	substr($value,0,10,undef);
                   13149: 	$value=&unescape($value);
                   13150: 	return &thaw($value);
                   13151:     }
                   13152:     return &unescape($value);
                   13153: }
                   13154: 
1.436     albertel 13155: sub correct_line_ends {
                   13156:     my ($result)=@_;
                   13157:     $$result =~s/\r\n/\n/mg;
                   13158:     $$result =~s/\r/\n/mg;
1.415     albertel 13159: }
1.1       albertel 13160: # ================================================================ Main Program
                   13161: 
1.184     www      13162: sub goodbye {
1.204     albertel 13163:    &logthis("Starting Shut down");
1.443     albertel 13164: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13165:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13166: #converted
1.599     albertel 13167: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13168:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13169: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13170: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13171: #1.1 only
1.870     albertel 13172: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13173: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13174: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13175: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13176:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13177:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13178:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13179:    &flushcourselogs();
                   13180:    &logthis("Shutting down");
                   13181: }
                   13182: 
1.852     albertel 13183: sub get_dns {
1.1210    raeburn  13184:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13185:     if (!$ignore_cache) {
                   13186: 	my ($content,$cached)=
                   13187: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13188: 	if ($cached) {
1.1210    raeburn  13189: 	    &$func($content,$hashref);
1.869     albertel 13190: 	    return;
                   13191: 	}
                   13192:     }
                   13193: 
                   13194:     my %alldns;
1.852     albertel 13195:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   13196:     foreach my $dns (<$config>) {
                   13197: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  13198:         my $line = $1;
                   13199:         my ($host,$protocol) = split(/:/,$line);
                   13200:         if ($protocol ne 'https') {
                   13201:             $protocol = 'http';
                   13202:         }
                   13203: 	$alldns{$host} = $protocol;
1.869     albertel 13204:     }
                   13205:     while (%alldns) {
1.1263    raeburn  13206: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.979     raeburn  13207: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.1345    raeburn  13208:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
1.979     raeburn  13209:         delete($alldns{$dns});
1.852     albertel 13210: 	next if ($response->is_error());
                   13211: 	my @content = split("\n",$response->content);
1.1210    raeburn  13212: 	unless ($nocache) {
1.1219    raeburn  13213: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210    raeburn  13214: 	}
                   13215: 	&$func(\@content,$hashref);
1.869     albertel 13216: 	return;
1.852     albertel 13217:     }
                   13218:     close($config);
1.871     albertel 13219:     my $which = (split('/',$url))[3];
                   13220:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   13221:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 13222:     my @content = <$config>;
1.1210    raeburn  13223:     &$func(\@content,$hashref);
                   13224:     return;
                   13225: }
                   13226: 
                   13227: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  13228: sub parse_dns_checksums_tab {
1.1210    raeburn  13229:     my ($lines,$hashref) = @_;
1.1264    raeburn  13230:     my $lonhost = $perlvar{'lonHostID'};
                   13231:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  13232:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  13233:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13234:     my $webconfdir = '/etc/httpd/conf';
                   13235:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13236:         $webconfdir = '/etc/apache2';
                   13237:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13238:         if ($1 >= 10) {
                   13239:             $webconfdir = '/etc/apache2';
                   13240:         }
                   13241:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13242:         if ($1 >= 10.0) {
                   13243:             $webconfdir = '/etc/apache2';
                   13244:         }
                   13245:     }
1.1210    raeburn  13246:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13247:     my (%chksum,%revnum);
                   13248:     if (ref($lines) eq 'ARRAY') {
                   13249:         chomp(@{$lines});
1.1238    raeburn  13250:         my $version = shift(@{$lines});
                   13251:         if ($version eq $release) {  
1.1210    raeburn  13252:             foreach my $line (@{$lines}) {
1.1238    raeburn  13253:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  13254:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13255:                     if ($webconfdir eq '/etc/apache2') {
                   13256:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13257:                     }
                   13258:                 }
1.1238    raeburn  13259:                 $chksum{$file} = $shasum;
                   13260:                 $revnum{$file} = $version;
1.1210    raeburn  13261:             }
                   13262:             if (ref($hashref) eq 'HASH') {
                   13263:                 %{$hashref} = (
                   13264:                                 sums     => \%chksum,
                   13265:                                 versions => \%revnum,
                   13266:                               );
                   13267:             }
                   13268:         }
                   13269:     }
1.869     albertel 13270:     return;
1.852     albertel 13271: }
1.1210    raeburn  13272: 
                   13273: sub fetch_dns_checksums {
1.1238    raeburn  13274:     my %checksums;
                   13275:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  13276:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  13277:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13278:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  13279:              \%checksums);
1.1210    raeburn  13280:     return \%checksums;
                   13281: }
                   13282: 
1.327     albertel 13283: # ------------------------------------------------------------ Read domain file
                   13284: {
1.852     albertel 13285:     my $loaded;
1.846     albertel 13286:     my %domain;
                   13287: 
1.852     albertel 13288:     sub parse_domain_tab {
                   13289: 	my ($lines) = @_;
                   13290: 	foreach my $line (@$lines) {
                   13291: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13292: 
1.846     albertel 13293: 	    chomp($line);
1.852     albertel 13294: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13295: 	    my %this_domain;
                   13296: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13297: 			       'lang_def', 'city', 'longi', 'lati',
                   13298: 			       'primary') {
                   13299: 		$this_domain{$field} = shift(@elements);
                   13300: 	    }
                   13301: 	    $domain{$name} = \%this_domain;
1.852     albertel 13302: 	}
                   13303:     }
1.864     albertel 13304: 
                   13305:     sub reset_domain_info {
                   13306: 	undef($loaded);
                   13307: 	undef(%domain);
                   13308:     }
                   13309: 
1.852     albertel 13310:     sub load_domain_tab {
1.1293    raeburn  13311: 	my ($ignore_cache,$nocache) = @_;
                   13312: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13313: 	my $fh;
                   13314: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   13315: 	    my @lines = <$fh>;
                   13316: 	    &parse_domain_tab(\@lines);
1.448     albertel 13317: 	}
1.852     albertel 13318: 	close($fh);
                   13319: 	$loaded = 1;
1.327     albertel 13320:     }
1.846     albertel 13321: 
                   13322:     sub domain {
1.852     albertel 13323: 	&load_domain_tab() if (!$loaded);
                   13324: 
1.846     albertel 13325: 	my ($name,$what) = @_;
                   13326: 	return if ( !exists($domain{$name}) );
                   13327: 
                   13328: 	if (!$what) {
                   13329: 	    return $domain{$name}{'description'};
                   13330: 	}
                   13331: 	return $domain{$name}{$what};
                   13332:     }
1.974     raeburn  13333: 
                   13334:     sub domain_info {
                   13335:         &load_domain_tab() if (!$loaded);
                   13336:         return %domain;
                   13337:     }
                   13338: 
1.327     albertel 13339: }
                   13340: 
                   13341: 
1.1       albertel 13342: # ------------------------------------------------------------- Read hosts file
                   13343: {
1.838     albertel 13344:     my %hostname;
1.844     albertel 13345:     my %hostdom;
1.845     albertel 13346:     my %libserv;
1.852     albertel 13347:     my $loaded;
1.888     albertel 13348:     my %name_to_host;
1.1074    raeburn  13349:     my %internetdom;
1.1107    raeburn  13350:     my %LC_dns_serv;
1.852     albertel 13351: 
                   13352:     sub parse_hosts_tab {
                   13353: 	my ($file) = @_;
                   13354: 	foreach my $configline (@$file) {
                   13355: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13356:             chomp($configline);
                   13357: 	    if ($configline =~ /^\^/) {
                   13358:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13359:                     $LC_dns_serv{$1} = 1;
                   13360:                 }
                   13361:                 next;
                   13362:             }
1.1074    raeburn  13363: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13364: 	    $name=~s/\s//g;
                   13365: 	    if ($id && $domain && $role && $name) {
                   13366: 		$hostname{$id}=$name;
1.888     albertel 13367: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 13368: 		$hostdom{$id}=$domain;
                   13369: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13370:                 if (defined($protocol)) {
                   13371:                     if ($protocol eq 'https') {
                   13372:                         $protocol{$id} = $protocol;
                   13373:                     } else {
                   13374:                         $protocol{$id} = 'http'; 
                   13375:                     }
1.968     raeburn  13376:                 } else {
1.969     raeburn  13377:                     $protocol{$id} = 'http';
1.968     raeburn  13378:                 }
1.1074    raeburn  13379:                 if (defined($intdom)) {
                   13380:                     $internetdom{$id} = $intdom;
                   13381:                 }
1.852     albertel 13382: 	    }
                   13383: 	}
                   13384:     }
1.864     albertel 13385:     
                   13386:     sub reset_hosts_info {
1.897     albertel 13387: 	&purge_remembered();
1.864     albertel 13388: 	&reset_domain_info();
                   13389: 	&reset_hosts_ip_info();
1.1339    raeburn  13390:         undef(%internetdom);
1.892     albertel 13391: 	undef(%name_to_host);
1.864     albertel 13392: 	undef(%hostname);
                   13393: 	undef(%hostdom);
                   13394: 	undef(%libserv);
                   13395: 	undef($loaded);
                   13396:     }
1.1       albertel 13397: 
1.852     albertel 13398:     sub load_hosts_tab {
1.1293    raeburn  13399: 	my ($ignore_cache,$nocache) = @_;
                   13400: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852     albertel 13401: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   13402: 	my @config = <$config>;
                   13403: 	&parse_hosts_tab(\@config);
                   13404: 	close($config);
                   13405: 	$loaded=1;
1.1       albertel 13406:     }
1.852     albertel 13407: 
1.838     albertel 13408:     sub hostname {
1.852     albertel 13409: 	&load_hosts_tab() if (!$loaded);
                   13410: 
1.838     albertel 13411: 	my ($lonid) = @_;
                   13412: 	return $hostname{$lonid};
                   13413:     }
1.845     albertel 13414: 
1.838     albertel 13415:     sub all_hostnames {
1.852     albertel 13416: 	&load_hosts_tab() if (!$loaded);
                   13417: 
1.838     albertel 13418: 	return %hostname;
                   13419:     }
1.845     albertel 13420: 
1.888     albertel 13421:     sub all_names {
1.1293    raeburn  13422:         my ($ignore_cache,$nocache) = @_;
                   13423: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13424: 
                   13425: 	return %name_to_host;
                   13426:     }
                   13427: 
1.974     raeburn  13428:     sub all_host_domain {
                   13429:         &load_hosts_tab() if (!$loaded);
                   13430:         return %hostdom;
                   13431:     }
                   13432: 
1.1339    raeburn  13433:     sub all_host_intdom {
                   13434:         &load_hosts_tab() if (!$loaded);
                   13435:         return %internetdom;
                   13436:     }
                   13437: 
1.845     albertel 13438:     sub is_library {
1.852     albertel 13439: 	&load_hosts_tab() if (!$loaded);
                   13440: 
1.845     albertel 13441: 	return exists($libserv{$_[0]});
                   13442:     }
                   13443: 
                   13444:     sub all_library {
1.852     albertel 13445: 	&load_hosts_tab() if (!$loaded);
                   13446: 
1.845     albertel 13447: 	return %libserv;
                   13448:     }
                   13449: 
1.1062    droeschl 13450:     sub unique_library {
                   13451: 	#2x reverse removes all hostnames that appear more than once
                   13452:         my %unique = reverse &all_library();
                   13453:         return reverse %unique;
                   13454:     }
                   13455: 
1.841     albertel 13456:     sub get_servers {
1.852     albertel 13457: 	&load_hosts_tab() if (!$loaded);
                   13458: 
1.841     albertel 13459: 	my ($domain,$type) = @_;
                   13460: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13461: 	                                          : %hostname;
                   13462: 	my %result;
1.842     albertel 13463: 	if (ref($domain) eq 'ARRAY') {
                   13464: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13465: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13466: 		    $result{$host} = $hostname;
                   13467: 		}
                   13468: 	    }
                   13469: 	} else {
                   13470: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13471: 		if ($hostdom{$host} eq $domain) {
                   13472: 		    $result{$host} = $hostname;
                   13473: 		}
1.841     albertel 13474: 	    }
                   13475: 	}
                   13476: 	return %result;
                   13477:     }
1.845     albertel 13478: 
1.1062    droeschl 13479:     sub get_unique_servers {
                   13480:         my %unique = reverse &get_servers(@_);
                   13481: 	return reverse %unique;
                   13482:     }
                   13483: 
1.844     albertel 13484:     sub host_domain {
1.852     albertel 13485: 	&load_hosts_tab() if (!$loaded);
                   13486: 
1.844     albertel 13487: 	my ($lonid) = @_;
                   13488: 	return $hostdom{$lonid};
                   13489:     }
                   13490: 
1.841     albertel 13491:     sub all_domains {
1.852     albertel 13492: 	&load_hosts_tab() if (!$loaded);
                   13493: 
1.841     albertel 13494: 	my %seen;
                   13495: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13496: 	return @uniq;
                   13497:     }
1.1074    raeburn  13498: 
                   13499:     sub internet_dom {
                   13500:         &load_hosts_tab() if (!$loaded);
                   13501: 
                   13502:         my ($lonid) = @_;
                   13503:         return $internetdom{$lonid};
                   13504:     }
1.1107    raeburn  13505: 
                   13506:     sub is_LC_dns {
                   13507:         &load_hosts_tab() if (!$loaded);
                   13508: 
                   13509:         my ($hostname) = @_;
                   13510:         return exists($LC_dns_serv{$hostname});
                   13511:     }
                   13512: 
1.1       albertel 13513: }
                   13514: 
1.847     albertel 13515: { 
                   13516:     my %iphost;
1.856     albertel 13517:     my %name_to_ip;
                   13518:     my %lonid_to_ip;
1.869     albertel 13519: 
1.847     albertel 13520:     sub get_hosts_from_ip {
                   13521: 	my ($ip) = @_;
                   13522: 	my %iphosts = &get_iphost();
                   13523: 	if (ref($iphosts{$ip})) {
                   13524: 	    return @{$iphosts{$ip}};
                   13525: 	}
                   13526: 	return;
1.839     albertel 13527:     }
1.864     albertel 13528:     
                   13529:     sub reset_hosts_ip_info {
                   13530: 	undef(%iphost);
                   13531: 	undef(%name_to_ip);
                   13532: 	undef(%lonid_to_ip);
                   13533:     }
1.856     albertel 13534: 
                   13535:     sub get_host_ip {
                   13536: 	my ($lonid) = @_;
                   13537: 	if (exists($lonid_to_ip{$lonid})) {
                   13538: 	    return $lonid_to_ip{$lonid};
                   13539: 	}
                   13540: 	my $name=&hostname($lonid);
                   13541:    	my $ip = gethostbyname($name);
                   13542: 	return if (!$ip || length($ip) ne 4);
                   13543: 	$ip=inet_ntoa($ip);
                   13544: 	$name_to_ip{$name}   = $ip;
                   13545: 	$lonid_to_ip{$lonid} = $ip;
                   13546: 	return $ip;
                   13547:     }
1.847     albertel 13548:     
                   13549:     sub get_iphost {
1.1293    raeburn  13550: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13551: 
1.869     albertel 13552: 	if (!$ignore_cache) {
                   13553: 	    if (%iphost) {
                   13554: 		return %iphost;
                   13555: 	    }
                   13556: 	    my ($ip_info,$cached)=
                   13557: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13558: 	    if ($cached) {
                   13559: 		%iphost      = %{$ip_info->[0]};
                   13560: 		%name_to_ip  = %{$ip_info->[1]};
                   13561: 		%lonid_to_ip = %{$ip_info->[2]};
                   13562: 		return %iphost;
                   13563: 	    }
                   13564: 	}
1.894     albertel 13565: 
                   13566: 	# get yesterday's info for fallback
                   13567: 	my %old_name_to_ip;
                   13568: 	my ($ip_info,$cached)=
                   13569: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13570: 	if ($cached) {
                   13571: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13572: 	}
                   13573: 
1.1293    raeburn  13574: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13575: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13576: 	    my $ip;
                   13577: 	    if (!exists($name_to_ip{$name})) {
                   13578: 		$ip = gethostbyname($name);
                   13579: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13580: 		    if (defined($old_name_to_ip{$name})) {
                   13581: 			$ip = $old_name_to_ip{$name};
                   13582: 			&logthis("Can't find $name defaulting to old $ip");
                   13583: 		    } else {
                   13584: 			&logthis("Name $name no IP found");
                   13585: 			next;
                   13586: 		    }
                   13587: 		} else {
                   13588: 		    $ip=inet_ntoa($ip);
1.847     albertel 13589: 		}
                   13590: 		$name_to_ip{$name} = $ip;
                   13591: 	    } else {
                   13592: 		$ip = $name_to_ip{$name};
1.653     albertel 13593: 	    }
1.888     albertel 13594: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13595: 		$lonid_to_ip{$id} = $ip;
                   13596: 	    }
                   13597: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13598: 	}
1.1293    raeburn  13599:         unless ($nocache) {
                   13600: 	    &do_cache_new('iphost','iphost',
                   13601: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13602: 		          48*60*60);
                   13603:         }
1.869     albertel 13604: 
1.847     albertel 13605: 	return %iphost;
1.598     albertel 13606:     }
                   13607: 
1.992     raeburn  13608:     #
                   13609:     #  Given a DNS returns the loncapa host name for that DNS 
                   13610:     # 
                   13611:     sub host_from_dns {
                   13612:         my ($dns) = @_;
                   13613:         my @hosts;
                   13614:         my $ip;
                   13615: 
1.993     raeburn  13616:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13617:             $ip = $name_to_ip{$dns};
                   13618:         }
                   13619:         if (!$ip) {
                   13620:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13621:             if (length($ip) == 4) { 
                   13622: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13623:             }
                   13624:         }
                   13625:         if ($ip) {
                   13626: 	    @hosts = get_hosts_from_ip($ip);
                   13627: 	    return $hosts[0];
                   13628:         }
                   13629:         return undef;
1.986     foxr     13630:     }
1.992     raeburn  13631: 
1.1074    raeburn  13632:     sub get_internet_names {
                   13633:         my ($lonid) = @_;
                   13634:         return if ($lonid eq '');
                   13635:         my ($idnref,$cached)=
                   13636:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13637:         if ($cached) {
                   13638:             return $idnref;
                   13639:         }
                   13640:         my $ip = &get_host_ip($lonid);
                   13641:         my @hosts = &get_hosts_from_ip($ip);
                   13642:         my %iphost = &get_iphost();
                   13643:         my (@idns,%seen);
                   13644:         foreach my $id (@hosts) {
                   13645:             my $dom = &host_domain($id);
                   13646:             my $prim_id = &domain($dom,'primary');
                   13647:             my $prim_ip = &get_host_ip($prim_id);
                   13648:             next if ($seen{$prim_ip});
                   13649:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13650:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13651:                     my $intdom = &internet_dom($id);
                   13652:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13653:                         push(@idns,$intdom);
                   13654:                     }
                   13655:                 }
                   13656:             }
                   13657:             $seen{$prim_ip} = 1;
                   13658:         }
1.1219    raeburn  13659:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13660:     }
                   13661: 
1.986     foxr     13662: }
                   13663: 
1.1079    raeburn  13664: sub all_loncaparevs {
1.1249    raeburn  13665:     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 2.11);
1.1079    raeburn  13666: }
                   13667: 
1.1227    raeburn  13668: # ---------------------------------------------------------- Read loncaparev table
                   13669: {
                   13670:     sub load_loncaparevs { 
                   13671:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   13672:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   13673:                 while (my $configline=<$config>) {
                   13674:                     chomp($configline);
                   13675:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13676:                     $loncaparevs{$hostid}=$loncaparev;
                   13677:                 }
                   13678:                 close($config);
                   13679:             }
                   13680:         }
                   13681:     }
                   13682: }
                   13683: 
                   13684: # ---------------------------------------------------------- Read serverhostID table
                   13685: {
                   13686:     sub load_serverhomeIDs {
                   13687:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   13688:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   13689:                 while (my $configline=<$config>) {
                   13690:                     chomp($configline);
                   13691:                     my ($name,$id)=split(/:/,$configline);
                   13692:                     $serverhomeIDs{$name}=$id;
                   13693:                 }
                   13694:                 close($config);
                   13695:             }
                   13696:         }
                   13697:     }
                   13698: }
                   13699: 
                   13700: 
1.862     albertel 13701: BEGIN {
                   13702: 
                   13703: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13704:     unless ($readit) {
                   13705: {
                   13706:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13707:     %perlvar = (%perlvar,%{$configvars});
                   13708: }
                   13709: 
                   13710: 
1.1       albertel 13711: # ------------------------------------------------------ Read spare server file
                   13712: {
1.448     albertel 13713:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13714: 
                   13715:     while (my $configline=<$config>) {
                   13716:        chomp($configline);
1.284     matthew  13717:        if ($configline) {
1.784     albertel 13718: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13719: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13720: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13721:        }
                   13722:     }
1.448     albertel 13723:     close($config);
1.1       albertel 13724: }
1.11      www      13725: # ------------------------------------------------------------ Read permissions
                   13726: {
1.448     albertel 13727:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13728: 
                   13729:     while (my $configline=<$config>) {
1.448     albertel 13730: 	chomp($configline);
                   13731: 	if ($configline) {
                   13732: 	    my ($role,$perm)=split(/ /,$configline);
                   13733: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13734: 	}
1.11      www      13735:     }
1.448     albertel 13736:     close($config);
1.11      www      13737: }
                   13738: 
                   13739: # -------------------------------------------- Read plain texts for permissions
                   13740: {
1.448     albertel 13741:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13742: 
                   13743:     while (my $configline=<$config>) {
1.448     albertel 13744: 	chomp($configline);
                   13745: 	if ($configline) {
1.742     raeburn  13746: 	    my ($short,@plain)=split(/:/,$configline);
                   13747:             %{$prp{$short}} = ();
                   13748: 	    if (@plain > 0) {
                   13749:                 $prp{$short}{'std'} = $plain[0];
                   13750:                 for (my $i=1; $i<@plain; $i++) {
                   13751:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13752:                 }
                   13753:             }
1.448     albertel 13754: 	}
1.135     www      13755:     }
1.448     albertel 13756:     close($config);
1.135     www      13757: }
                   13758: 
                   13759: # ---------------------------------------------------------- Read package table
                   13760: {
1.448     albertel 13761:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13762: 
                   13763:     while (my $configline=<$config>) {
1.483     albertel 13764: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13765: 	chomp($configline);
                   13766: 	my ($short,$plain)=split(/:/,$configline);
                   13767: 	my ($pack,$name)=split(/\&/,$short);
                   13768: 	if ($plain ne '') {
                   13769: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13770: 	    $packagetab{$short}=$plain; 
                   13771: 	}
1.11      www      13772:     }
1.448     albertel 13773:     close($config);
1.329     matthew  13774: }
                   13775: 
1.1073    raeburn  13776: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  13777: 
                   13778: &load_loncaparevs();
1.1073    raeburn  13779: 
1.1074    raeburn  13780: # ---------------------------------------------------------- Read serverhostID table
                   13781: 
1.1227    raeburn  13782: &load_serverhomeIDs();
                   13783: 
                   13784: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13785: {
                   13786:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13787:     if (-e $file) {
                   13788:         my $parser = HTML::LCParser->new($file);
                   13789:         while (my $token = $parser->get_token()) {
                   13790:             if ($token->[0] eq 'S') {
                   13791:                 my $item = $token->[1];
                   13792:                 my $name = $token->[2]{'name'};
                   13793:                 my $value = $token->[2]{'value'};
1.1285    raeburn  13794:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  13795:                 my $namematch = $token->[2]{'namematch'};
                   13796:                 if ($item eq 'parameter') {
                   13797:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   13798:                         my $release = $parser->get_text();
                   13799:                         $release =~ s/(^\s*|\s*$ )//gx;
                   13800:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   13801:                     }
                   13802:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  13803:                     my $release = $parser->get_text();
                   13804:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  13805:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  13806:                 }
                   13807:             }
                   13808:         }
                   13809:     }
1.1073    raeburn  13810: }
                   13811: 
1.1138    raeburn  13812: # ---------------------------------------------------------- Read managers table
                   13813: {
                   13814:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   13815:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   13816:             while (my $configline=<$config>) {
                   13817:                 chomp($configline);
                   13818:                 next if ($configline =~ /^\#/);
                   13819:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13820:                     $managerstab{$configline} = 1;
                   13821:                 }
                   13822:             }
                   13823:             close($config);
                   13824:         }
                   13825:     }
                   13826: }
                   13827: 
1.329     matthew  13828: # ------------- set up temporary directory
                   13829: {
1.1117    foxr     13830:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  13831: 
1.11      www      13832: }
                   13833: 
1.794     albertel 13834: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   13835: 				'compress_threshold'=> 20_000,
                   13836:  			        });
1.185     www      13837: 
1.281     www      13838: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      13839: $dumpcount=0;
1.958     www      13840: $locknum=0;
1.22      www      13841: 
1.163     harris41 13842: &logtouch();
1.672     albertel 13843: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      13844: $readit=1;
1.564     albertel 13845:     {
                   13846: 	use integer;
                   13847: 	my $test=(2**32)+1;
1.568     albertel 13848: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 13849: 	&logthis(" Detected 64bit platform ($_64bit)");
                   13850:     }
1.195     www      13851: }
1.1       albertel 13852: }
1.179     www      13853: 
1.1       albertel 13854: 1;
1.191     harris41 13855: __END__
                   13856: 
1.243     albertel 13857: =pod
                   13858: 
1.191     harris41 13859: =head1 NAME
                   13860: 
1.243     albertel 13861: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 13862: 
                   13863: =head1 SYNOPSIS
                   13864: 
1.243     albertel 13865: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 13866: 
                   13867:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   13868: 
1.243     albertel 13869: Common parameters:
                   13870: 
                   13871: =over 4
                   13872: 
                   13873: =item *
                   13874: 
                   13875: $uname : an internal username (if $cname expecting a course Id specifically)
                   13876: 
                   13877: =item *
                   13878: 
                   13879: $udom : a domain (if $cdom expecting a course's domain specifically)
                   13880: 
                   13881: =item *
                   13882: 
                   13883: $symb : a resource instance identifier
                   13884: 
                   13885: =item *
                   13886: 
                   13887: $namespace : the name of a .db file that contains the data needed or
                   13888: being set.
                   13889: 
                   13890: =back
                   13891: 
1.394     bowersj2 13892: =head1 OVERVIEW
1.191     harris41 13893: 
1.394     bowersj2 13894: lonnet provides subroutines which interact with the
                   13895: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   13896: about classes, users, and resources.
1.243     albertel 13897: 
                   13898: For many of these objects you can also use this to store data about
                   13899: them or modify them in various ways.
1.191     harris41 13900: 
1.394     bowersj2 13901: =head2 Symbs
1.191     harris41 13902: 
1.394     bowersj2 13903: To identify a specific instance of a resource, LON-CAPA uses symbols
                   13904: or "symbs"X<symb>. These identifiers are built from the URL of the
                   13905: map, the resource number of the resource in the map, and the URL of
                   13906: the resource itself. The latter is somewhat redundant, but might help
                   13907: if maps change.
                   13908: 
                   13909: An example is
                   13910: 
                   13911:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   13912: 
                   13913: The respective map entry is
                   13914: 
                   13915:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   13916:   title="Problem 2">
                   13917:  </resource>
                   13918: 
                   13919: Symbs are used by the random number generator, as well as to store and
                   13920: restore data specific to a certain instance of for example a problem.
                   13921: 
                   13922: =head2 Storing And Retrieving Data
                   13923: 
                   13924: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   13925: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   13926: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   13927: is is the non-critical message twin of cstore. These functions are for
                   13928: handlers to store a perl hash to a user's permanent data space in an
                   13929: easy manner, and to retrieve it again on another call. It is expected
                   13930: that a handler would use this once at the beginning to retrieve data,
                   13931: and then again once at the end to send only the new data back.
                   13932: 
                   13933: The data is stored in the user's data directory on the user's
                   13934: homeserver under the ID of the course.
                   13935: 
                   13936: The hash that is returned by restore will have all of the previous
                   13937: value for all of the elements of the hash.
                   13938: 
                   13939: Example:
                   13940: 
                   13941:  #creating a hash
                   13942:  my %hash;
                   13943:  $hash{'foo'}='bar';
                   13944: 
                   13945:  #storing it
                   13946:  &Apache::lonnet::cstore(\%hash);
                   13947: 
                   13948:  #changing a value
                   13949:  $hash{'foo'}='notbar';
                   13950: 
                   13951:  #adding a new value
                   13952:  $hash{'bar'}='foo';
                   13953:  &Apache::lonnet::cstore(\%hash);
                   13954: 
                   13955:  #retrieving the hash
                   13956:  my %history=&Apache::lonnet::restore();
                   13957: 
                   13958:  #print the hash
                   13959:  foreach my $key (sort(keys(%history))) {
                   13960:    print("\%history{$key} = $history{$key}");
                   13961:  }
                   13962: 
                   13963: Will print out:
1.191     harris41 13964: 
1.394     bowersj2 13965:  %history{1:foo} = bar
                   13966:  %history{1:keys} = foo:timestamp
                   13967:  %history{1:timestamp} = 990455579
                   13968:  %history{2:bar} = foo
                   13969:  %history{2:foo} = notbar
                   13970:  %history{2:keys} = foo:bar:timestamp
                   13971:  %history{2:timestamp} = 990455580
                   13972:  %history{bar} = foo
                   13973:  %history{foo} = notbar
                   13974:  %history{timestamp} = 990455580
                   13975:  %history{version} = 2
                   13976: 
                   13977: Note that the special hash entries C<keys>, C<version> and
                   13978: C<timestamp> were added to the hash. C<version> will be equal to the
                   13979: total number of versions of the data that have been stored. The
                   13980: C<timestamp> attribute will be the UNIX time the hash was
                   13981: stored. C<keys> is available in every historical section to list which
                   13982: keys were added or changed at a specific historical revision of a
                   13983: hash.
                   13984: 
                   13985: B<Warning>: do not store the hash that restore returns directly. This
                   13986: will cause a mess since it will restore the historical keys as if the
                   13987: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 13988: 
1.394     bowersj2 13989: Calling convention:
1.191     harris41 13990: 
1.1225    raeburn  13991:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  13992:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 13993: 
1.394     bowersj2 13994: For more detailed information, see lonnet specific documentation.
1.191     harris41 13995: 
1.394     bowersj2 13996: =head1 RETURN MESSAGES
1.191     harris41 13997: 
1.394     bowersj2 13998: =over 4
1.191     harris41 13999: 
1.394     bowersj2 14000: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14001: 
1.394     bowersj2 14002: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14003: when the connection is brought back up
1.191     harris41 14004: 
1.394     bowersj2 14005: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14006: for later delivery
1.191     harris41 14007: 
1.967     bisitz   14008: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14009: 
1.394     bowersj2 14010: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14011: that was requested
1.191     harris41 14012: 
1.243     albertel 14013: =back
1.191     harris41 14014: 
1.243     albertel 14015: =head1 PUBLIC SUBROUTINES
1.191     harris41 14016: 
1.243     albertel 14017: =head2 Session Environment Functions
1.191     harris41 14018: 
1.243     albertel 14019: =over 4
1.191     harris41 14020: 
1.394     bowersj2 14021: =item * 
                   14022: X<appenv()>
1.949     raeburn  14023: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14024: the user envirnoment file, and will be restored for each access this
1.620     albertel 14025: user makes during this session, also modifies the %env for the current
1.949     raeburn  14026: process. Optional rolesarrayref - if defined contains a reference to an array
                   14027: of roles which are exempt from the restriction on modifying user.role entries 
                   14028: in the user's environment.db and in %env.    
1.191     harris41 14029: 
                   14030: =item *
1.394     bowersj2 14031: X<delenv()>
1.987     raeburn  14032: B<delenv($delthis,$regexp)>: removes all items from the session
                   14033: environment file that begin with $delthis. If the 
                   14034: optional second arg - $regexp - is true, $delthis is treated as a 
                   14035: regular expression, otherwise \Q$delthis\E is used. 
                   14036: The values are also deleted from the current processes %env.
1.191     harris41 14037: 
1.795     albertel 14038: =item * get_env_multiple($name) 
                   14039: 
                   14040: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14041: values may be defined and end up as an array ref.
                   14042: 
                   14043: returns an array of values
                   14044: 
1.243     albertel 14045: =back
                   14046: 
                   14047: =head2 User Information
1.191     harris41 14048: 
1.243     albertel 14049: =over 4
1.191     harris41 14050: 
                   14051: =item *
1.394     bowersj2 14052: X<queryauthenticate()>
                   14053: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14054: authentication scheme
                   14055: 
                   14056: =item *
1.394     bowersj2 14057: X<authenticate()>
1.1073    raeburn  14058: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14059: authenticate user from domain's lib servers (first use the current
                   14060: one). C<$upass> should be the users password.
1.1073    raeburn  14061: $checkdefauth is optional (value is 1 if a check should be made to
                   14062:    authenticate user using default authentication method, and allow
                   14063:    account creation if username does not have account in the domain).
                   14064: $clientcancheckhost is optional (value is 1 if checking whether the
                   14065:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14066: 
                   14067: =item *
1.394     bowersj2 14068: X<homeserver()>
                   14069: B<homeserver($uname,$udom)>: find the server which has
                   14070: the user's directory and files (there must be only one), this caches
                   14071: the answer, and also caches if there is a borken connection.
1.191     harris41 14072: 
                   14073: =item *
1.394     bowersj2 14074: X<idget()>
1.1300    raeburn  14075: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   14076: a list of student/employee IDs or clicker IDs
                   14077: (student/employee IDs are a unique resource in a domain, there must be 
                   14078: only 1 ID per username, and only 1 username per ID in a specific domain).
                   14079: clickerIDs are not necessarily unique, as students might share clickers.
                   14080: (returns hash: id=>name,id=>name)
1.191     harris41 14081: 
                   14082: =item *
1.394     bowersj2 14083: X<idrget()>
                   14084: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14085: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14086: 
                   14087: =item *
1.394     bowersj2 14088: X<idput()>
1.1300    raeburn  14089: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   14090: names and associated student/employee IDs or clicker IDs.
                   14091: 
                   14092: =item *
                   14093: X<iddel()>
                   14094: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   14095: student/employee ID or clicker ID username look-ups from domain.
                   14096: The homeserver ($uhome) and namespace ($namespace) are optional.
                   14097: If no $uhome is provided, it will be determined usig &homeserver()
                   14098: for each user.  If no $namespace is provided, the default is ids.
                   14099: 
                   14100: =item *
                   14101: X<updateclickers()>
                   14102: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   14103: clicker ID-to-username look-ups in clickers.db on library server.
                   14104: Permitted actions are add or del (i.e., add or delete). The 
                   14105: clickers.db contains clickerID as keys (escaped), and each corresponding
                   14106: value is an escaped comma-separated list of usernames (for whom the
                   14107: library server is the homeserver), who registered that particular ID.
                   14108: If $critical is true, the update will be sent via &critical, otherwise
                   14109: &reply() will be used.
1.191     harris41 14110: 
                   14111: =item *
1.394     bowersj2 14112: X<rolesinit()>
1.1169    droeschl 14113: B<rolesinit($udom,$username)>: get user privileges.
                   14114: returns user role, first access and timer interval hashes
1.243     albertel 14115: 
                   14116: =item *
1.1171    droeschl 14117: X<privileged()>
                   14118: B<privileged($username,$domain)>: returns a true if user has a
                   14119: privileged and active role (i.e. su or dc), false otherwise.
                   14120: 
                   14121: =item *
1.551     albertel 14122: X<getsection()>
                   14123: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14124: course $cname, return section name/number or '' for "not in course"
                   14125: and '-1' for "no section"
                   14126: 
                   14127: =item *
1.394     bowersj2 14128: X<userenvironment()>
                   14129: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14130: passed in @what from the requested user's environment, returns a hash
                   14131: 
1.858     raeburn  14132: =item * 
                   14133: X<userlog_query()>
1.859     albertel 14134: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14135: activity.log file. %filters defines filters applied when parsing the
                   14136: log file. These can be start or end timestamps, or the type of action
                   14137: - log to look for Login or Logout events, check for Checkin or
                   14138: Checkout, role for role selection. The response is in the form
                   14139: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14140: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14141: 
1.243     albertel 14142: =back
                   14143: 
                   14144: =head2 User Roles
                   14145: 
                   14146: =over 4
                   14147: 
                   14148: =item *
                   14149: 
1.1284    raeburn  14150: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14151: returns codes for allowed actions.
                   14152: 
                   14153: The first argument is required, all others are optional.
                   14154: 
                   14155: $priv is the privilege being checked.
                   14156: $uri contains additional information about what is being checked for access (e.g.,
                   14157: URL, course ID etc.). 
                   14158: $symb is the unique resource instance identifier in a course; if needed,
                   14159: but not provided, it will be retrieved via a call to &symbread(). 
                   14160: $role is the role for which a priv is being checked (only used if priv is evb). 
                   14161: $clientip is the user's IP address (only used when checking for access to portfolio 
                   14162: files).
                   14163: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   14164: prevents recursive calls to &allowed.
                   14165: 
1.243     albertel 14166:  F: full access
                   14167:  U,I,K: authentication modes (cxx only)
                   14168:  '': forbidden
                   14169:  1: user needs to choose course
                   14170:  2: browse allowed
1.766     albertel 14171:  A: passphrase authentication needed
1.1284    raeburn  14172:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14173: 
                   14174: =item *
                   14175: 
1.1192    raeburn  14176: constructaccess($url,$setpriv) : check for access to construction space URL
                   14177: 
                   14178: See if the owner domain and name in the URL match those in the
                   14179: expected environment.  If so, return three element list
                   14180: ($ownername,$ownerdomain,$ownerhome).
                   14181: 
                   14182: Otherwise return the null string.
                   14183: 
                   14184: If second argument 'setpriv' is true, it assigns the privileges,
                   14185: and returns the same three element list, unless the owner has
                   14186: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14187: in which case the null string is returned.
                   14188: 
                   14189: =item *
                   14190: 
1.1326    raeburn  14191: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14192: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14193: for system, domain, and course level. $uname and $udom are optional (current
                   14194: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14195: 
                   14196: =item *
                   14197: 
1.988     raeburn  14198: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14199: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14200: $type is Course (default) or Community.
1.988     raeburn  14201: If $forcedefault evaluates to true, text returned will be default 
                   14202: text for $type. Otherwise, if this is a course, the text returned 
                   14203: will be a custom name for the role (if defined in the course's 
                   14204: environment).  If no custom name is defined the default is returned.
                   14205:    
1.832     raeburn  14206: =item *
                   14207: 
1.1219    raeburn  14208: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14209: All arguments are optional. Returns a hash of a roles, either for
                   14210: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14211: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14212: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14213: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14214: For each key, value is set to colon-separated start and end times for
                   14215: the role.  If no username and domain are specified, will default to
1.934     raeburn  14216: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14217: of role statuses (active, future or previous), roles 
                   14218: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14219: to restrict the list of roles reported. If no array ref is 
                   14220: provided for types, will default to return only active roles.
1.834     albertel 14221: 
1.1195    raeburn  14222: =item *
                   14223: 
                   14224: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  14225: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   14226: 
                   14227: Additional optional arguments are: $type (if role checking is to be restricted 
                   14228: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  14229: available roles) or future (roles available in the future), and
                   14230: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  14231: have active Domain Coordinator role in course's domain or in additional
                   14232: domains (specified in 'Domains to check for privileged users' in course
                   14233: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14234: 
                   14235: =item *
                   14236: 
                   14237: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14238: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14239: $possdomains and $possroles are optional array refs -- to domains to check and
                   14240: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14241: users' roles.db to check for a dc or su role in any domain. This can be
                   14242: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14243: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14244: this then allows &privileged_by_domain() to be used, which caches the identity
                   14245: of privileged users, eliminating the need for repeated calls to &dump().
                   14246: 
                   14247: =item *
                   14248: 
                   14249: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14250: where the outer hash keys are domains specified in the $possdomains array ref,
                   14251: next inner hash keys are privileged roles specified in the $roles array ref,
                   14252: and the innermost hash contains key = value pairs for username:domain = end:start
                   14253: for active or future "privileged" users with that role in that domain. To avoid
                   14254: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14255: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  14256: 
1.243     albertel 14257: =back
                   14258: 
                   14259: =head2 User Modification
                   14260: 
                   14261: =over 4
                   14262: 
                   14263: =item *
                   14264: 
1.957     raeburn  14265: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14266: user for the level given by URL.  Optional start and end dates (leave empty
                   14267: string or zero for "no date")
1.191     harris41 14268: 
                   14269: =item *
                   14270: 
1.243     albertel 14271: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14272: change a users, password, possible return values are: ok,
                   14273: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14274: refused
1.191     harris41 14275: 
                   14276: =item *
                   14277: 
1.243     albertel 14278: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14279: 
                   14280: =item *
                   14281: 
1.1058    raeburn  14282: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14283:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14284: 
                   14285: will update user information (firstname,middlename,lastname,generation,
                   14286: permanentemail), and if forceid is true, student/employee ID also.
                   14287: A user's institutional affiliation(s) can also be updated.
                   14288: User information fields will not be overwritten with empty entries 
                   14289: unless the field is included in the $candelete array reference.
                   14290: This array is included when a single user is modified via "Manage Users",
                   14291: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14292: 
                   14293: =item *
                   14294: 
1.286     matthew  14295: modifystudent
                   14296: 
1.957     raeburn  14297: modify a student's enrollment and identification information.
1.1235    raeburn  14298: The course id is resolved based on the current user's environment.  
                   14299: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14300: associated with a course.
                   14301: 
1.297     matthew  14302: This call is essentially a wrapper for lonnet::modifyuser and
                   14303: lonnet::modify_student_enrollment
1.286     matthew  14304: 
                   14305: Inputs: 
                   14306: 
                   14307: =over 4
                   14308: 
1.957     raeburn  14309: =item B<$udom> Student's loncapa domain
1.286     matthew  14310: 
1.957     raeburn  14311: =item B<$uname> Student's loncapa login name
1.286     matthew  14312: 
1.964     bisitz   14313: =item B<$uid> Student/Employee ID
1.286     matthew  14314: 
1.957     raeburn  14315: =item B<$umode> Student's authentication mode
1.286     matthew  14316: 
1.957     raeburn  14317: =item B<$upass> Student's password
1.286     matthew  14318: 
1.957     raeburn  14319: =item B<$first> Student's first name
1.286     matthew  14320: 
1.957     raeburn  14321: =item B<$middle> Student's middle name
1.286     matthew  14322: 
1.957     raeburn  14323: =item B<$last> Student's last name
1.286     matthew  14324: 
1.957     raeburn  14325: =item B<$gene> Student's generation
1.286     matthew  14326: 
1.957     raeburn  14327: =item B<$usec> Student's section in course
1.286     matthew  14328: 
                   14329: =item B<$end> Unix time of the roles expiration
                   14330: 
                   14331: =item B<$start> Unix time of the roles start date
                   14332: 
                   14333: =item B<$forceid> If defined, allow $uid to be changed
                   14334: 
                   14335: =item B<$desiredhome> server to use as home server for student
                   14336: 
1.957     raeburn  14337: =item B<$email> Student's permanent e-mail address
                   14338: 
                   14339: =item B<$type> Type of enrollment (auto or manual)
                   14340: 
1.963     raeburn  14341: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14342: 
                   14343: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14344: 
1.963     raeburn  14345: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14346: 
1.963     raeburn  14347: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14348: 
1.1216    raeburn  14349: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14350: 
                   14351: =item B<$credits> Number of credits student will earn from this class - only needs to be supplied if value needs to be different from default credits for class.
1.957     raeburn  14352: 
1.286     matthew  14353: =back
1.297     matthew  14354: 
                   14355: =item *
                   14356: 
                   14357: modify_student_enrollment
                   14358: 
1.1235    raeburn  14359: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14360: 'role.request.course' must be defined for this function to proceed.
                   14361: 
                   14362: Inputs:
                   14363: 
                   14364: =over 4
                   14365: 
1.1235    raeburn  14366: =item $udom, student's domain
1.297     matthew  14367: 
1.1235    raeburn  14368: =item $uname, student's name
1.297     matthew  14369: 
1.1235    raeburn  14370: =item $uid, student's user id
1.297     matthew  14371: 
1.1235    raeburn  14372: =item $first, student's first name
1.297     matthew  14373: 
                   14374: =item $middle
                   14375: 
                   14376: =item $last
                   14377: 
                   14378: =item $gene
                   14379: 
                   14380: =item $usec
                   14381: 
                   14382: =item $end
                   14383: 
                   14384: =item $start
                   14385: 
1.957     raeburn  14386: =item $type
                   14387: 
                   14388: =item $locktype
                   14389: 
                   14390: =item $cid
                   14391: 
                   14392: =item $selfenroll
                   14393: 
                   14394: =item $context
                   14395: 
1.1216    raeburn  14396: =item $credits, number of credits student will earn from this class
                   14397: 
1.1314    raeburn  14398: =item $instsec, institutional course section code for student
                   14399: 
1.297     matthew  14400: =back
                   14401: 
1.191     harris41 14402: 
                   14403: =item *
                   14404: 
1.243     albertel 14405: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14406: custom role; give a custom role to a user for the level given by URL.  Specify
                   14407: name and domain of role author, and role name
1.191     harris41 14408: 
                   14409: =item *
                   14410: 
1.243     albertel 14411: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14412: 
                   14413: =item *
                   14414: 
1.243     albertel 14415: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14416: 
                   14417: =back
                   14418: 
                   14419: =head2 Course Infomation
                   14420: 
                   14421: =over 4
1.191     harris41 14422: 
                   14423: =item *
                   14424: 
1.1118    foxr     14425: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14426: specified course id, including all environment settings for the
                   14427: course, the description of the course will be in the hash under the
                   14428: key 'description'
1.191     harris41 14429: 
1.1118    foxr     14430: $options is an optional parameter that if supplied is a hash reference that controls
                   14431: what how this function works.  It has the following key/values:
                   14432: 
                   14433: =over 4
                   14434: 
                   14435: =item freshen_cache
                   14436: 
                   14437: If defined, and the environment cache for the course is valid, it is 
                   14438: returned in the returned hash.
                   14439: 
                   14440: =item one_time
                   14441: 
                   14442: If defined, the last cache time is set to _now_
                   14443: 
                   14444: =item user
                   14445: 
                   14446: If defined, the supplied username is used instead of the current user.
                   14447: 
                   14448: 
                   14449: =back
                   14450: 
1.191     harris41 14451: =item *
                   14452: 
1.624     albertel 14453: resdata($name,$domain,$type,@which) : request for current parameter
                   14454: setting for a specific $type, where $type is either 'course' or 'user',
                   14455: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  14456: answers for 10 minutes.
1.243     albertel 14457: 
1.877     foxr     14458: =item *
                   14459: 
                   14460: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14461: data base, returning a hash that is keyed by the resource name and has
                   14462: values that are the resource value.  I believe that the timestamps and
                   14463: versions are also returned.
                   14464: 
1.1236    raeburn  14465: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14466: supplemental content area. This routine caches the number of files for 
                   14467: 10 minutes.
                   14468: 
1.243     albertel 14469: =back
                   14470: 
                   14471: =head2 Course Modification
                   14472: 
                   14473: =over 4
1.191     harris41 14474: 
                   14475: =item *
                   14476: 
1.243     albertel 14477: writecoursepref($courseid,%prefs) : write preferences (environment
                   14478: database) for a course
1.191     harris41 14479: 
                   14480: =item *
                   14481: 
1.1011    raeburn  14482: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14483: 
                   14484: =item *
                   14485: 
1.1038    raeburn  14486: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14487: 
1.1167    droeschl 14488: =item *
                   14489: 
                   14490: is_course($courseid), is_course($cdom, $cnum)
                   14491: 
                   14492: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14493: two component version $cdom, $cnum. It checks if the specified course exists.
                   14494: 
                   14495: Returns:
                   14496:     undef if the course doesn't exist, otherwise
                   14497:     in scalar context the combined courseid.
                   14498:     in list context the two components of the course identifier, domain and 
                   14499:     courseid.    
                   14500: 
1.243     albertel 14501: =back
                   14502: 
                   14503: =head2 Resource Subroutines
                   14504: 
                   14505: =over 4
1.191     harris41 14506: 
                   14507: =item *
                   14508: 
1.243     albertel 14509: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14510: 
                   14511: =item *
                   14512: 
1.243     albertel 14513: repcopy($filename) : subscribes to the requested file, and attempts to
                   14514: replicate from the owning library server, Might return
1.607     raeburn  14515: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14516: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14517: resource. Expects the local filesystem pathname
                   14518: (/home/httpd/html/res/....)
                   14519: 
                   14520: =back
                   14521: 
                   14522: =head2 Resource Information
                   14523: 
                   14524: =over 4
1.191     harris41 14525: 
                   14526: =item *
                   14527: 
1.1228    raeburn  14528: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14529: and returns the value of a variety of different possible values,
                   14530: $varname should be a request string, and the other parameters can be
                   14531: used to specify who and what one is asking about. Ordinarily, $cid 
                   14532: does not need to be specified, as it is retrived from 
                   14533: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14534: within lonuserstate::loadmap() when initializing a course, before
                   14535: $env{'request.course.id'} has been set, so it needs to be provided
                   14536: in that one case.
1.243     albertel 14537: 
                   14538: Possible values for $varname are environment.lastname (or other item
                   14539: from the envirnment hash), user.name (or someother aspect about the
                   14540: user), resource.0.maxtries (or some other part and parameter of a
                   14541: resource)
1.204     albertel 14542: 
                   14543: =item *
                   14544: 
1.243     albertel 14545: directcondval($number) : get current value of a condition; reads from a state
                   14546: string
1.204     albertel 14547: 
                   14548: =item *
                   14549: 
1.243     albertel 14550: condval($condidx) : value of condition index based on state
1.204     albertel 14551: 
                   14552: =item *
                   14553: 
1.243     albertel 14554: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14555: resource's metadata, $what should be either a specific key, or either
                   14556: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14557: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14558: 
                   14559: this function automatically caches all requests
1.191     harris41 14560: 
                   14561: =item *
                   14562: 
1.243     albertel 14563: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14564: network of library servers; returns file handle of where SQL and regex results
                   14565: will be stored for query
1.191     harris41 14566: 
                   14567: =item *
                   14568: 
1.1282    raeburn  14569: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   14570: return symbolic list entry (all arguments optional). 
                   14571: 
                   14572: Args: filename is the filename (including path) for the file for which a symb 
                   14573: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   14574: to check access status if more than one resource was found in the bighash 
                   14575: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   14576: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   14577: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14578: cause possible symbs to be checked to determine if they are subject to content
                   14579: blocking, if so they will not be included as possible symbs; possibles is a
                   14580: ref to a hash, which, as a side effect, will be populated with all possible 
                   14581: symbs (content blocking not tested).
                   14582:  
1.243     albertel 14583: returns the data handle
1.191     harris41 14584: 
                   14585: =item *
                   14586: 
1.1190    raeburn  14587: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   14588: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14589: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  14590: on failure, user must be in a course, as it assumes the existence of
                   14591: the course initial hash, and uses $env('request.course.id'}.  The third
                   14592: arg is an optional reference to a scalar.  If this arg is passed in the 
                   14593: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14594: encrypted; otherwise it will be null.  
1.191     harris41 14595: 
                   14596: =item *
                   14597: 
1.243     albertel 14598: symbclean($symb) : removes versions numbers from a symb, returns the
                   14599: cleaned symb
1.191     harris41 14600: 
                   14601: =item *
                   14602: 
1.243     albertel 14603: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14604: course map, user must be in a course for it to work.
1.191     harris41 14605: 
                   14606: =item *
                   14607: 
1.243     albertel 14608: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14609: 
                   14610: =item *
                   14611: 
1.243     albertel 14612: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14613: a random seed, all arguments are optional, if they aren't sent it uses the
                   14614: environment to derive them. Note: if symb isn't sent and it can't get one
                   14615: from &symbread it will use the current time as its return value
1.191     harris41 14616: 
                   14617: =item *
                   14618: 
1.243     albertel 14619: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14620: unfakeable, receipt
1.191     harris41 14621: 
                   14622: =item *
                   14623: 
1.620     albertel 14624: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14625: 
                   14626: =item *
                   14627: 
1.243     albertel 14628: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14629: 
                   14630: =item *
                   14631: 
1.243     albertel 14632: 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 14633: 
                   14634: =item *
                   14635: 
1.243     albertel 14636: 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 14637: 
                   14638: =item *
                   14639: 
1.243     albertel 14640: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14641: 
                   14642: =item *
                   14643: 
1.243     albertel 14644: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14645: forcing spreadsheet to reevaluate the resource scores next time.
                   14646: 
1.1195    raeburn  14647: =item * 
                   14648: 
1.1196    raeburn  14649: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14650: when viewing in course context.
1.1195    raeburn  14651: 
1.1196    raeburn  14652:  input: six args -- filename (decluttered), course number, course domain,
                   14653:                     url, symb (if registered) and group (if this is a 
                   14654:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  14655: 
1.1196    raeburn  14656:  output: array of five scalars --
1.1195    raeburn  14657:          $cfile -- url for file editing if editable on current server
                   14658:          $home -- homeserver of resource (i.e., for author if published,
                   14659:                                           or course if uploaded.).
                   14660:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  14661:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   14662:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  14663: 
                   14664: =item *
                   14665: 
                   14666: is_course_upload($file,$cnum,$cdom)
                   14667: 
                   14668: Used in course context to determine if current file was uploaded to 
                   14669: the course (i.e., would be found in /userfiles/docs on the course's 
                   14670: homeserver.
                   14671: 
                   14672:   input: 3 args -- filename (decluttered), course number and course domain.
                   14673:   output: boolean -- 1 if file was uploaded.
                   14674: 
1.243     albertel 14675: =back
                   14676: 
                   14677: =head2 Storing/Retreiving Data
                   14678: 
                   14679: =over 4
1.191     harris41 14680: 
                   14681: =item *
                   14682: 
1.1269    raeburn  14683: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   14684: permanently for this url; hashref needs to be given and should be a \%hashname;
                   14685: the remaining args aren't required and if they aren't passed or are '' they will
                   14686: be derived from the env (with the exception of $laststore, which is an 
                   14687: optional arg used when a user's submission is stored in grading).
                   14688: $laststore is $version=$timestamp, where $version is the most recent version
                   14689: number retrieved for the corresponding $symb in the $namespace db file, and
                   14690: $timestamp is the timestamp for that transaction (UNIX time).
                   14691: $laststore is currently only passed when cstore() is called by 
                   14692: structuretags::finalize_storage().
1.191     harris41 14693: 
                   14694: =item *
                   14695: 
1.1269    raeburn  14696: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   14697: but uses critical subroutine
1.191     harris41 14698: 
                   14699: =item *
                   14700: 
1.243     albertel 14701: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14702: all args are optional
1.191     harris41 14703: 
                   14704: =item *
                   14705: 
1.717     albertel 14706: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14707: dumps the complete (or key matching regexp) namespace into a hash
                   14708: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14709: normally &store()ed into
                   14710: 
                   14711: $range should be either an integer '100' (give me the first 100
                   14712:                                            matching records)
                   14713:               or be  two integers sperated by a - with no spaces
                   14714:                  '30-50' (give me the 30th through the 50th matching
                   14715:                           records)
                   14716: 
                   14717: 
                   14718: =item *
                   14719: 
1.1269    raeburn  14720: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14721: replaces a &store() version of data with a replacement set of data
                   14722: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  14723: reference. If $tolog is true, the transaction is logged in the courselog
                   14724: with an action=PUTSTORE.
1.717     albertel 14725: 
                   14726: =item *
                   14727: 
1.243     albertel 14728: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14729: works very similar to store/cstore, but all data is stored in a
                   14730: temporary location and can be reset using tmpreset, $storehash should
                   14731: be a hash reference, returns nothing on success
1.191     harris41 14732: 
                   14733: =item *
                   14734: 
1.243     albertel 14735: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14736: similar to restore, but all data is stored in a temporary location and
                   14737: can be reset using tmpreset. Returns a hash of values on success,
                   14738: error string otherwise.
1.191     harris41 14739: 
                   14740: =item *
                   14741: 
1.243     albertel 14742: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14743: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14744: 
                   14745: =item *
                   14746: 
1.243     albertel 14747: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14748: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14749: 
                   14750: =item *
                   14751: 
1.243     albertel 14752: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14753: namesp ($udom and $uname are optional)
1.191     harris41 14754: 
                   14755: =item *
                   14756: 
1.702     albertel 14757: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14758: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14759: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  14760: 
1.702     albertel 14761: $range should be either an integer '100' (give me the first 100
                   14762:                                            matching records)
                   14763:               or be  two integers sperated by a - with no spaces
                   14764:                  '30-50' (give me the 30th through the 50th matching
                   14765:                           records)
1.449     matthew  14766: =item *
                   14767: 
                   14768: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   14769: $store can be a scalar, an array reference, or if the amount to be 
                   14770: incremented is > 1, a hash reference.
                   14771: 
                   14772: ($udom and $uname are optional)
1.191     harris41 14773: 
                   14774: =item *
                   14775: 
1.243     albertel 14776: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   14777: ($udom and $uname are optional)
1.191     harris41 14778: 
                   14779: =item *
                   14780: 
1.243     albertel 14781: cput($namespace,$storehash,$udom,$uname) : critical put
                   14782: ($udom and $uname are optional)
1.191     harris41 14783: 
                   14784: =item *
                   14785: 
1.748     albertel 14786: newput($namespace,$storehash,$udom,$uname) :
                   14787: 
                   14788: Attempts to store the items in the $storehash, but only if they don't
                   14789: currently exist, if this succeeds you can be certain that you have 
                   14790: successfully created a new key value pair in the $namespace db.
                   14791: 
                   14792: 
                   14793: Args:
                   14794:  $namespace: name of database to store values to
                   14795:  $storehash: hashref to store to the db
                   14796:  $udom: (optional) domain of user containing the db
                   14797:  $uname: (optional) name of user caontaining the db
                   14798: 
                   14799: Returns:
                   14800:  'ok' -> succeeded in storing all keys of $storehash
                   14801:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   14802:                         least <key> already existed in the db (other
                   14803:                         requested keys may also already exist)
1.967     bisitz   14804:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 14805:  'con_lost' -> unable to contact request server
                   14806:  'refused' -> action was not allowed by remote machine
                   14807: 
                   14808: 
                   14809: =item *
                   14810: 
1.243     albertel 14811: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14812: reference filled in from namesp (encrypts the return communication)
                   14813: ($udom and $uname are optional)
1.191     harris41 14814: 
                   14815: =item *
                   14816: 
1.243     albertel 14817: log($udom,$name,$home,$message) : write to permanent log for user; use
                   14818: critical subroutine
                   14819: 
1.806     raeburn  14820: =item *
                   14821: 
1.860     raeburn  14822: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   14823: array reference filled in from namespace found in domain level on either
                   14824: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  14825: 
                   14826: =item *
                   14827: 
1.860     raeburn  14828: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   14829: domain level either on specified domain server ($uhome) or primary domain 
                   14830: server ($udom and $uhome are optional)
1.806     raeburn  14831: 
1.943     raeburn  14832: =item * 
                   14833: 
1.1240    raeburn  14834: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   14835: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   14836: the target domain.
                   14837: 
                   14838: May also include additional key => value pairs for the following groups:
                   14839: 
                   14840: =over
                   14841: 
                   14842: =item
                   14843: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   14844: 
                   14845: =over
                   14846: 
                   14847: =item defaultquota, authorquota
                   14848: 
                   14849: =back
                   14850: 
                   14851: =item
                   14852: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   14853: portfolio for users).
                   14854: 
                   14855: =over
                   14856: 
                   14857: =item
                   14858: aboutme, blog, webdav, portfolio
                   14859: 
                   14860: =back
                   14861: 
                   14862: =item
                   14863: requestcourses: ability to request courses, and how requests are processed.
                   14864: 
                   14865: =over
                   14866: 
                   14867: =item
1.1305    raeburn  14868: official, unofficial, community, textbook, placement
1.1240    raeburn  14869: 
                   14870: =back
                   14871: 
                   14872: =item
                   14873: inststatus: types of institutional affiliation, and order in which they are displayed.
                   14874: 
                   14875: =over
                   14876: 
                   14877: =item
1.1256    raeburn  14878: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  14879: 
                   14880: =back
                   14881: 
                   14882: =item
                   14883: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   14884: for course's uploaded content.
                   14885: 
                   14886: =over
                   14887: 
                   14888: =item
1.1246    raeburn  14889: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  14890: communityquota, textbookquota, placementquota
1.1240    raeburn  14891: 
                   14892: =back
                   14893: 
                   14894: =item
                   14895: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   14896: on your servers.
                   14897: 
                   14898: =over
                   14899: 
                   14900: =item 
                   14901: remotesessions, hostedsessions
                   14902: 
                   14903: =back
                   14904: 
                   14905: =back
                   14906: 
                   14907: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   14908: utility to create a configuration.db file on a domain's primary library server 
                   14909: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   14910: -- corresponding values are authentication type (internal, krb4, krb5,
                   14911: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   14912: will be available. Values are retrieved from cache (if current), unless the
                   14913: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   14914: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   14915: 
                   14916: Typical usage:
1.943     raeburn  14917: 
1.1240    raeburn  14918: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  14919: 
1.243     albertel 14920: =back
                   14921: 
                   14922: =head2 Network Status Functions
                   14923: 
                   14924: =over 4
1.191     harris41 14925: 
                   14926: =item *
                   14927: 
1.1137    raeburn  14928: dirlist() : return directory list based on URI (first arg).
                   14929: 
                   14930: Inputs: 1 required, 5 optional.
                   14931: 
                   14932: =over
                   14933: 
                   14934: =item 
                   14935: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   14936: 
                   14937: =item
                   14938: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   14939: 
                   14940: =item
                   14941: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   14942: 
                   14943: =item
                   14944: $getpropath - boolean: 1 if prepend path using &propath(). 
                   14945: 
                   14946: =item
                   14947: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   14948: 
                   14949: =item 
                   14950: $alternateRoot - path to prepend in place of path from $uri.
                   14951: 
                   14952: =back
                   14953: 
                   14954: Returns: Array of up to two items.
                   14955: 
                   14956: =over
                   14957: 
                   14958: a reference to an array of files/subdirectories
                   14959: 
                   14960: =over
                   14961: 
                   14962: Each element in the array of files/subdirectories is a & separated list of
                   14963: item name and the result of running stat on the item.  If dirlist was requested
                   14964: for a file instead of a directory, the item name will be ''. For a directory 
                   14965: listing, if the item is a metadata file, the element will end &N&M 
                   14966: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   14967: default copyright set (1).  
                   14968: 
                   14969: =back
                   14970: 
                   14971: a scalar containing error condition (if encountered).
                   14972: 
                   14973: =over
                   14974: 
                   14975: =item 
                   14976: no_host (no homeserver identified for $username:$domain).
                   14977: 
                   14978: =item 
                   14979: no_such_host (server contacted for listing not identified as valid host).
                   14980: 
                   14981: =item 
                   14982: con_lost (connection to remote server failed).
                   14983: 
                   14984: =item 
                   14985: refused (invalid $username:$domain received on lond side).
                   14986: 
                   14987: =item 
                   14988: no_such_dir (directory at specified path on lond side does not exist). 
                   14989: 
                   14990: =item 
                   14991: empty (directory at specified path on lond side is empty).
                   14992: 
                   14993: =over
                   14994: 
                   14995: This is currently not encountered because the &ls3, &ls2, 
                   14996: &ls (_handler) routines on the lond side do not filter out
                   14997: . and .. from a directory listing. 
                   14998: 
                   14999: =back
                   15000: 
                   15001: =back
                   15002: 
                   15003: =back
1.191     harris41 15004: 
                   15005: =item *
                   15006: 
1.243     albertel 15007: spareserver() : find server with least workload from spare.tab
                   15008: 
1.986     foxr     15009: 
                   15010: =item *
                   15011: 
                   15012: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15013: if there is no corresponding loncapa host.
                   15014: 
1.243     albertel 15015: =back
                   15016: 
1.986     foxr     15017: 
1.243     albertel 15018: =head2 Apache Request
                   15019: 
                   15020: =over 4
1.191     harris41 15021: 
                   15022: =item *
                   15023: 
1.243     albertel 15024: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15025: localhost, posts hash
                   15026: 
                   15027: =back
                   15028: 
                   15029: =head2 Data to String to Data
                   15030: 
                   15031: =over 4
1.191     harris41 15032: 
                   15033: =item *
                   15034: 
1.243     albertel 15035: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15036: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15037: 
                   15038: =item *
                   15039: 
1.243     albertel 15040: hashref2str($hashref) : convert a hashref into a string complete with
                   15041: escaping and '=' and '&' separators, supports elements that are
                   15042: arrayrefs and hashrefs
1.191     harris41 15043: 
                   15044: =item *
                   15045: 
1.243     albertel 15046: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15047: with escaping and '&' separators, supports elements that are arrayrefs
                   15048: and hashrefs
1.191     harris41 15049: 
                   15050: =item *
                   15051: 
1.243     albertel 15052: str2hash($string) : convert string to hash using unescaping and
                   15053: splitting on '=' and '&', supports elements that are arrayrefs and
                   15054: hashrefs
1.191     harris41 15055: 
                   15056: =item *
                   15057: 
1.243     albertel 15058: str2array($string) : convert string to hash using unescaping and
                   15059: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15060: 
                   15061: =back
                   15062: 
                   15063: =head2 Logging Routines
                   15064: 
                   15065: 
                   15066: These routines allow one to make log messages in the lonnet.log and
                   15067: lonnet.perm logfiles.
1.191     harris41 15068: 
1.1119    foxr     15069: =over 4
                   15070: 
1.191     harris41 15071: =item *
                   15072: 
1.243     albertel 15073: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15074: 
                   15075: =item *
                   15076: 
1.243     albertel 15077: logthis() : append message to the normal lonnet.log file, it gets
                   15078: preiodically rolled over and deleted.
1.191     harris41 15079: 
                   15080: =item *
                   15081: 
1.243     albertel 15082: logperm() : append a permanent message to lonnet.perm.log, this log
                   15083: file never gets deleted by any automated portion of the system, only
                   15084: messages of critical importance should go in here.
                   15085: 
1.1119    foxr     15086: 
1.243     albertel 15087: =back
                   15088: 
                   15089: =head2 General File Helper Routines
                   15090: 
                   15091: =over 4
1.191     harris41 15092: 
                   15093: =item *
                   15094: 
1.481     raeburn  15095: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15096: (a) files in /uploaded
                   15097:   (i) If a local copy of the file exists - 
                   15098:       compares modification date of local copy with last-modified date for 
                   15099:       definitive version stored on home server for course. If local copy is 
                   15100:       stale, requests a new version from the home server and stores it. 
                   15101:       If the original has been removed from the home server, then local copy 
                   15102:       is unlinked.
                   15103:   (ii) If local copy does not exist -
                   15104:       requests the file from the home server and stores it. 
                   15105:   
                   15106:   If $caller is 'uploadrep':  
                   15107:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15108:     for request for files originally uploaded via DOCS. 
                   15109:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15110:   
                   15111:   Otherwise:
                   15112:      This indicates a call from the content generation phase of the request.
                   15113:      -  returns the entire contents of the file or -1.
                   15114:      
                   15115: (b) files in /res
                   15116:    - returns the entire contents of a file or -1; 
                   15117:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15118: 
1.712     albertel 15119: 
                   15120: =item *
                   15121: 
                   15122: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15123:                   reference
                   15124: 
                   15125: returns either a stat() list of data about the file or an empty list
                   15126: if the file doesn't exist or couldn't find out about it (connection
                   15127: problems or user unknown)
                   15128: 
1.191     harris41 15129: =item *
                   15130: 
1.243     albertel 15131: filelocation($dir,$file) : returns file system location of a file
                   15132: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15133: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15134: and a file of ../bob will become /a/bob)
1.191     harris41 15135: 
                   15136: =item *
                   15137: 
                   15138: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15139: filelocation except for hrefs
                   15140: 
                   15141: =item *
                   15142: 
1.1261    raeburn  15143: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15144: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15145: 
1.243     albertel 15146: =back
                   15147: 
1.608     albertel 15148: =head2 Usererfile file routines (/uploaded*)
                   15149: 
                   15150: =over 4
                   15151: 
                   15152: =item *
                   15153: 
                   15154: userfileupload(): main rotine for putting a file in a user or course's
                   15155:                   filespace, arguments are,
                   15156: 
1.620     albertel 15157:  formname - required - this is the name of the element in $env where the
1.608     albertel 15158:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15159:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15160:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15161:  context - if coursedoc, store the file in the course of the active role
                   15162:              of the current user; 
                   15163:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15164:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15165:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15166:          if undefined, it will be placed in "unknown"
                   15167: 
                   15168:  (This routine calls clean_filename() to remove any dangerous
                   15169:  characters from the filename, and then calls finuserfileupload() to
                   15170:  complete the transaction)
                   15171: 
                   15172:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15173:  and /adm/notfound.html if unsuccessful
                   15174: 
                   15175: =item *
                   15176: 
                   15177: clean_filename(): routine for cleaing a filename up for storage in
                   15178:                  userfile space, argument is:
                   15179: 
                   15180:  filename - proposed filename
                   15181: 
                   15182: returns: the new clean filename
                   15183: 
                   15184: =item *
                   15185: 
1.1090    raeburn  15186: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15187: userspace, probably shouldn't be called directly
                   15188: 
                   15189:   docuname: username or courseid of destination for the file
                   15190:   docudom: domain of user/course of destination for the file
                   15191:   formname: same as for userfileupload()
1.1090    raeburn  15192:   fname: filename (including subdirectories) for the file
                   15193:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   15194:   allfiles: reference to hash used to store objects found by parser
                   15195:   codebase: reference to hash used for codebases of java objects found by parser
                   15196:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15197:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15198:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15199:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15200:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15201:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15202:   mimetype: reference to scalar to accommodate mime type determined
                   15203:             from File::MMagic if $parser = parse.
1.608     albertel 15204: 
                   15205:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15206:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15207:  was 'overwrite').
                   15208:  
1.608     albertel 15209: 
                   15210: =item *
                   15211: 
                   15212: renameuserfile(): renames an existing userfile to a new name
                   15213: 
                   15214:   Args:
                   15215:    docuname: username or courseid of destination for the file
                   15216:    docudom: domain of user/course of destination for the file
                   15217:    old: current file name (including any subdirs under userfiles)
                   15218:    new: desired file name (including any subdirs under userfiles)
                   15219: 
                   15220: =item *
                   15221: 
                   15222: mkdiruserfile(): creates a directory is a userfiles dir
                   15223: 
                   15224:   Args:
                   15225:    docuname: username or courseid of destination for the file
                   15226:    docudom: domain of user/course of destination for the file
                   15227:    dir: dir to create (including any subdirs under userfiles)
                   15228: 
                   15229: =item *
                   15230: 
                   15231: removeuserfile(): removes a file that exists in userfiles
                   15232: 
                   15233:   Args:
                   15234:    docuname: username or courseid of destination for the file
                   15235:    docudom: domain of user/course of destination for the file
                   15236:    fname: filname to delete (including any subdirs under userfiles)
                   15237: 
                   15238: =item *
                   15239: 
                   15240: removeuploadedurl(): convience function for removeuserfile()
                   15241: 
                   15242:   Args:
                   15243:    url:  a full /uploaded/... url to delete
                   15244: 
1.747     albertel 15245: =item * 
                   15246: 
                   15247: get_portfile_permissions():
                   15248:   Args:
                   15249:     domain: domain of user or course contain the portfolio files
                   15250:     user: name of user or num of course contain the portfolio files
                   15251:   Returns:
                   15252:     hashref of a dump of the proper file_permissions.db
                   15253:    
                   15254: 
                   15255: =item * 
                   15256: 
                   15257: get_access_controls():
                   15258: 
                   15259: Args:
                   15260:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15261:   group: (optional) the group you want the files associated with
                   15262:   file: (optional) the file you want access info on
                   15263: 
                   15264: Returns:
1.749     raeburn  15265:     a hash (keys are file names) of hashes containing
                   15266:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15267:         values are XML containing access control settings (see below) 
1.747     albertel 15268: 
                   15269: Internal notes:
                   15270: 
1.749     raeburn  15271:  access controls are stored in file_permissions.db as key=value pairs.
                   15272:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15273:         where scope -> public,guest,course,group,domains or users.
                   15274:               end -> UNIX time for end of access (0 -> no end date)
                   15275:               start -> UNIX time for start of access
                   15276: 
                   15277:     value -> XML description of access control
                   15278:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15279:             <start></start>
                   15280:             <end></end>
                   15281: 
                   15282:             <password></password>  for scope type = guest
                   15283: 
                   15284:             <domain></domain>     for scope type = course or group
                   15285:             <number></number>
                   15286:             <roles id="">
                   15287:              <role></role>
                   15288:              <access></access>
                   15289:              <section></section>
                   15290:              <group></group>
                   15291:             </roles>
                   15292: 
                   15293:             <dom></dom>         for scope type = domains
                   15294: 
                   15295:             <users>             for scope type = users
                   15296:              <user>
                   15297:               <uname></uname>
                   15298:               <udom></udom>
                   15299:              </user>
                   15300:             </users>
                   15301:            </scope> 
                   15302:               
                   15303:  Access data is also aggregated for each file in an additional key=value pair:
                   15304:  key -> path to file/file_name\0accesscontrol 
                   15305:  value -> reference to hash
                   15306:           hash contains key = value pairs
                   15307:           where key = uniqueID:scope_end_start
                   15308:                 value = UNIX time record was last updated
                   15309: 
                   15310:           Used to improve speed of look-ups of access controls for each file.  
                   15311:  
                   15312:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15313: 
1.1198    raeburn  15314: =item *
                   15315: 
1.749     raeburn  15316: modify_access_controls():
                   15317: 
                   15318: Modifies access controls for a portfolio file
                   15319: Args
                   15320: 1. file name
                   15321: 2. reference to hash of required changes,
                   15322: 3. domain
                   15323: 4. username
                   15324:   where domain,username are the domain of the portfolio owner 
                   15325:   (either a user or a course) 
                   15326: 
                   15327: Returns:
                   15328: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15329: 2. result of deletions ('ok' or 'error', with error message).
                   15330: 3. reference to hash of any new or updated access controls.
                   15331: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15332:    key = integer (inbound ID)
1.1198    raeburn  15333:    value = uniqueID
                   15334: 
                   15335: =item *
                   15336: 
                   15337: get_timebased_id():
                   15338: 
                   15339: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   15340: course via the Course Editor (e.g., folders, composite pages, 
                   15341: group bulletin boards).
                   15342: 
                   15343: Args: (first three required; six others optional)
                   15344: 
                   15345: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15346:    docssequence, or name of group
                   15347: 
                   15348: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15349:    e.g., num, boardids
                   15350: 
                   15351: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   15352:    file will be named nohist_namespace.db
                   15353: 
                   15354: 4. cdom: domain of course; default is current course domain from %env
                   15355: 
                   15356: 5. cnum: course number; default is current course number from %env
                   15357: 
                   15358: 6. idtype: set to concat if an additional digit is to be appended to the 
                   15359:    unix timestamp to form the suffix, if the plain timestamp is already
                   15360:    in use.  Default is to not do this, but simply increment the unix 
                   15361:    timestamp by 1 until a unique key is obtained.
                   15362: 
                   15363: 7. who: holder of locking key; defaults to user:domain for user.
                   15364: 
                   15365: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   15366:    retrying); default is 3.
                   15367: 
                   15368: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   15369: 
                   15370: Returns:
                   15371: 
                   15372: 1. suffix obtained (numeric)
                   15373: 
                   15374: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15375: 
                   15376: 3. error: contains (localized) error message if an error occurred.
                   15377: 
1.747     albertel 15378: 
1.608     albertel 15379: =back
                   15380: 
1.243     albertel 15381: =head2 HTTP Helper Routines
                   15382: 
                   15383: =over 4
                   15384: 
1.191     harris41 15385: =item *
                   15386: 
                   15387: escape() : unpack non-word characters into CGI-compatible hex codes
                   15388: 
                   15389: =item *
                   15390: 
                   15391: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15392: 
1.243     albertel 15393: =back
                   15394: 
                   15395: =head1 PRIVATE SUBROUTINES
                   15396: 
                   15397: =head2 Underlying communication routines (Shouldn't call)
                   15398: 
                   15399: =over 4
                   15400: 
                   15401: =item *
                   15402: 
                   15403: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15404: 
                   15405: =item *
                   15406: 
                   15407: reply() : uses subreply to send a message to remote machine, logs all failures
                   15408: 
                   15409: =item *
                   15410: 
                   15411: critical() : passes a critical message to another server; if cannot
                   15412: get through then place message in connection buffer directory and
                   15413: returns con_delayed, if incapable of saving message, returns
                   15414: con_failed
                   15415: 
                   15416: =item *
                   15417: 
                   15418: reconlonc() : tries to reconnect lonc client processes.
                   15419: 
                   15420: =back
                   15421: 
                   15422: =head2 Resource Access Logging
                   15423: 
                   15424: =over 4
                   15425: 
                   15426: =item *
                   15427: 
                   15428: flushcourselogs() : flush (save) buffer logs and access logs
                   15429: 
                   15430: =item *
                   15431: 
                   15432: courselog($what) : save message for course in hash
                   15433: 
                   15434: =item *
                   15435: 
                   15436: courseacclog($what) : save message for course using &courselog().  Perform
                   15437: special processing for specific resource types (problems, exams, quizzes, etc).
                   15438: 
1.191     harris41 15439: =item *
                   15440: 
                   15441: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15442: as a PerlChildExitHandler
1.243     albertel 15443: 
                   15444: =back
                   15445: 
                   15446: =head2 Other
                   15447: 
                   15448: =over 4
                   15449: 
                   15450: =item *
                   15451: 
                   15452: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15453: 
                   15454: =back
                   15455: 
                   15456: =cut
1.877     foxr     15457: 

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