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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1321  ! raeburn     4: # $Id: lonnet.pm,v 1.1320 2016/09/14 20:29:40 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.1182    foxr       78: 
1.1173    foxr       79: use Encode;
                     80: 
1.1245    raeburn    81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138    raeburn    82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     83:             %managerstab);
1.871     albertel   84: 
                     85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        88:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        89: 
1.1       albertel   90: use IO::Socket;
1.31      www        91: use GDBM_File;
1.208     albertel   92: use HTML::LCParser;
1.88      www        93: use Fcntl qw(:flock);
1.870     albertel   94: use Storable qw(thaw nfreeze);
1.1289    damieng    95: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   96: use Cache::Memcached;
1.676     albertel   97: use Digest::MD5;
1.790     albertel   98: use Math::Random;
1.1024    raeburn    99: use File::MMagic;
1.807     albertel  100: use LONCAPA qw(:DEFAULT :match);
1.740     www       101: use LONCAPA::Configuration;
1.1160    www       102: use LONCAPA::lonmetadata;
1.1167    droeschl  103: use LONCAPA::Lond;
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];
                    240:         if ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
                    241:             if ($1 < 6) {
                    242:                 $uselocal = 0;
                    243:             }
                    244:         }
                    245:     }
                    246:     if ($uselocal) {
                    247:         $rep = LONCAPA::Lond::server_certs(\%perlvar);
                    248:     } else {
                    249:         $rep=&reply('servercerts',$lonhost);
                    250:     }
                    251:     my ($result,%returnhash);
                    252:     if (defined($lonhost)) {
                    253:         if (!defined(&hostname($lonhost))) {
                    254:             return;
                    255:         }
                    256:     }
                    257:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    258:         ($rep eq 'unknown_cmd')) {
                    259:         $result = $rep;
                    260:     } else {
                    261:         $result = 'ok';
                    262:         my @pairs=split(/\&/,$rep);
                    263:         foreach my $item (@pairs) {
                    264:             my ($key,$value)=split(/=/,$item,2);
                    265:             my $what = &unescape($key);
                    266:             $returnhash{$what}=&thaw_unescape($value);
                    267:         }
                    268:     }
                    269:     return ($result,\%returnhash);
                    270: }
                    271: 
1.993     raeburn   272: sub get_server_loncaparev {
1.1073    raeburn   273:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   274:     if (defined($lonhost)) {
                    275:         if (!defined(&hostname($lonhost))) {
                    276:             undef($lonhost);
                    277:         }
                    278:     }
                    279:     if (!defined($lonhost)) {
                    280:         if (defined(&domain($dom,'primary'))) {
                    281:             $lonhost=&domain($dom,'primary');
                    282:             if ($lonhost eq 'no_host') {
                    283:                 undef($lonhost);
                    284:             }
                    285:         }
                    286:     }
                    287:     if (defined($lonhost)) {
1.1073    raeburn   288:         my $cachetime = 12*3600;
                    289:         if (!$ignore_cache) {
                    290:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    291:             if (defined($cached)) {
                    292:                 return $loncaparev;
                    293:             }
                    294:         }
                    295:         my ($answer,$loncaparev);
                    296:         my @ids=&current_machine_ids();
                    297:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    298:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   299:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   300:                 $loncaparev = $1;
                    301:             }
                    302:         } else {
                    303:             $answer = &reply('serverloncaparev',$lonhost);
                    304:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    305:                 if ($caller eq 'loncron') {
                    306:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   307:                     $ua->timeout(4);
1.1073    raeburn   308:                     my $protocol = $protocol{$lonhost};
                    309:                     $protocol = 'http' if ($protocol ne 'https');
                    310:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    311:                     my $request=new HTTP::Request('GET',$url);
                    312:                     my $response=$ua->request($request);
                    313:                     unless ($response->is_error()) {
                    314:                         my $content = $response->content;
1.1081    raeburn   315:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   316:                             $loncaparev = $1;
                    317:                         }
                    318:                     }
                    319:                 } else {
                    320:                     $loncaparev = $loncaparevs{$lonhost};
                    321:                 }
1.1081    raeburn   322:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   323:                 $loncaparev = $1;
                    324:             }
1.993     raeburn   325:         }
1.1073    raeburn   326:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   327:     }
                    328: }
                    329: 
1.1074    raeburn   330: sub get_server_homeID {
                    331:     my ($hostname,$ignore_cache,$caller) = @_;
                    332:     unless ($ignore_cache) {
                    333:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    334:         if (defined($cached)) {
                    335:             return $serverhomeID;
                    336:         }
                    337:     }
                    338:     my $cachetime = 12*3600;
                    339:     my $serverhomeID;
                    340:     if ($caller eq 'loncron') { 
                    341:         my @machine_ids = &machine_ids($hostname);
                    342:         foreach my $id (@machine_ids) {
                    343:             my $response = &reply('serverhomeID',$id);
                    344:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    345:                 $serverhomeID = $response;
                    346:                 last;
                    347:             }
                    348:         }
                    349:         if ($serverhomeID eq '') {
                    350:             $serverhomeID = $machine_ids[-1];
                    351:         }
                    352:     } else {
                    353:         $serverhomeID = $serverhomeIDs{$hostname};
                    354:     }
                    355:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    356: }
                    357: 
1.1121    raeburn   358: sub get_remote_globals {
                    359:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   360:     my ($result,%returnhash,%whatneeded);
                    361:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   362:         foreach my $what (sort(keys(%{$whathash}))) {
                    363:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   364:             my ($response,$cached);
1.1121    raeburn   365:             unless ($ignore_cache) {
1.1125    raeburn   366:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   367:             }
                    368:             if (defined($cached)) {
1.1125    raeburn   369:                 $returnhash{$what} = $response;
1.1121    raeburn   370:             } else {
1.1125    raeburn   371:                 $whatneeded{$what} = 1;
1.1121    raeburn   372:             }
                    373:         }
1.1125    raeburn   374:         if (keys(%whatneeded) == 0) {
                    375:             $result = 'ok';
                    376:         } else {
1.1121    raeburn   377:             my $requested = &freeze_escape(\%whatneeded);
                    378:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   379:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    380:                 ($rep eq 'unknown_cmd')) {
                    381:                 $result = $rep;
                    382:             } else {
                    383:                 $result = 'ok';
1.1121    raeburn   384:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   385:                 foreach my $item (@pairs) {
                    386:                     my ($key,$value)=split(/=/,$item,2);
                    387:                     my $what = &unescape($key);
                    388:                     my $hashid = $lonhost.'-'.$what;
                    389:                     $returnhash{$what}=&thaw_unescape($value);
                    390:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   391:                 }
                    392:             }
                    393:         }
                    394:     }
1.1125    raeburn   395:     return ($result,\%returnhash);
1.1121    raeburn   396: }
                    397: 
1.1124    raeburn   398: sub remote_devalidate_cache {
1.1241    raeburn   399:     my ($lonhost,$cachekeys) = @_;
                    400:     my $items;
                    401:     return unless (ref($cachekeys) eq 'ARRAY');
                    402:     my $cachestr = join('&',@{$cachekeys});
                    403:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   404:     return $response;
                    405: }
                    406: 
1.1       albertel  407: # -------------------------------------------------- Non-critical communication
                    408: sub subreply {
                    409:     my ($cmd,$server)=@_;
1.838     albertel  410:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      411:     #
                    412:     #  With loncnew process trimming, there's a timing hole between lonc server
                    413:     #  process exit and the master server picking up the listen on the AF_UNIX
                    414:     #  socket.  In that time interval, a lock file will exist:
                    415: 
                    416:     my $lockfile=$peerfile.".lock";
                    417:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1289    damieng   418: 	sleep(0.1);
1.549     foxr      419:     }
                    420:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      421:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      422:     #
1.550     foxr      423:     #   We'll give the connection a few tries before abandoning it.  If
                    424:     #   connection is not possible, we'll con_lost back to the client.
                    425:     #   
                    426:     my $client;
                    427:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    428: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    429: 				      Type    => SOCK_STREAM,
                    430: 				      Timeout => 10);
1.869     albertel  431: 	if ($client) {
1.550     foxr      432: 	    last;		# Connected!
1.850     albertel  433: 	} else {
1.853     albertel  434: 	    &create_connection(&hostname($server),$server);
1.550     foxr      435: 	}
1.1289    damieng   436:         sleep(0.1);	# Try again later if failed connection.
1.550     foxr      437:     }
                    438:     my $answer;
                    439:     if ($client) {
1.704     albertel  440: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      441: 	$answer=<$client>;
                    442: 	if (!$answer) { $answer="con_lost"; }
                    443: 	chomp($answer);
                    444:     } else {
                    445: 	$answer = 'con_lost';	# Failed connection.
                    446:     }
1.1       albertel  447:     return $answer;
                    448: }
                    449: 
                    450: sub reply {
                    451:     my ($cmd,$server)=@_;
1.838     albertel  452:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  453:     my $answer=subreply($cmd,$server);
1.65      www       454:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  455:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       456:                 " $cmd to $server returned $answer</font>");
                    457:     }
1.1       albertel  458:     return $answer;
                    459: }
                    460: 
                    461: # ----------------------------------------------------------- Send USR1 to lonc
                    462: 
                    463: sub reconlonc {
1.891     albertel  464:     my ($lonid) = @_;
                    465:     if ($lonid) {
1.1295    raeburn   466:         my $hostname = &hostname($lonid);
1.891     albertel  467: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    468: 	if ($hostname && -e $peerfile) {
                    469: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    470: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    471: 					     Type    => SOCK_STREAM,
                    472: 					     Timeout => 10);
                    473: 	    if ($client) {
                    474: 		print $client ("reset_retries\n");
                    475: 		my $answer=<$client>;
                    476: 		#reset just this one.
                    477: 	    }
                    478: 	}
                    479: 	return;
                    480:     }
                    481: 
1.836     www       482:     &logthis("Trying to reconnect lonc");
1.1       albertel  483:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  484:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  485: 	my $loncpid=<$fh>;
                    486:         chomp($loncpid);
                    487:         if (kill 0 => $loncpid) {
                    488: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    489:             kill USR1 => $loncpid;
                    490:             sleep 1;
1.1295    raeburn   491:         } else {
1.12      www       492: 	    &logthis(
1.672     albertel  493:                "<font color=\"blue\">WARNING:".
1.12      www       494:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  495:         }
                    496:     } else {
1.836     www       497: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  498:     }
                    499: }
                    500: 
                    501: # ------------------------------------------------------ Critical communication
1.12      www       502: 
1.1       albertel  503: sub critical {
                    504:     my ($cmd,$server)=@_;
1.838     albertel  505:     unless (&hostname($server)) {
1.672     albertel  506:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       507:                " Critical message to unknown server ($server)</font>");
                    508:         return 'no_such_host';
                    509:     }
1.1       albertel  510:     my $answer=reply($cmd,$server);
                    511:     if ($answer eq 'con_lost') {
1.1295    raeburn   512: 	&reconlonc($server);
1.589     albertel  513: 	my $answer=reply($cmd,$server);
1.1       albertel  514:         if ($answer eq 'con_lost') {
                    515:             my $now=time;
                    516:             my $middlename=$cmd;
1.5       www       517:             $middlename=substr($middlename,0,16);
1.1       albertel  518:             $middlename=~s/\W//g;
                    519:             my $dfilename=
1.305     www       520:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    521:             $dumpcount++;
1.1       albertel  522:             {
1.448     albertel  523: 		my $dfh;
                    524: 		if (open($dfh,">$dfilename")) {
                    525: 		    print $dfh "$cmd\n"; 
                    526: 		    close($dfh);
                    527: 		}
1.1       albertel  528:             }
1.1288    damieng   529:             sleep 1;
1.1       albertel  530:             my $wcmd='';
                    531:             {
1.448     albertel  532: 		my $dfh;
                    533: 		if (open($dfh,"<$dfilename")) {
                    534: 		    $wcmd=<$dfh>; 
                    535: 		    close($dfh);
                    536: 		}
1.1       albertel  537:             }
                    538:             chomp($wcmd);
1.7       www       539:             if ($wcmd eq $cmd) {
1.672     albertel  540: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       541:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  542:                 &logperm("D:$server:$cmd");
                    543: 	        return 'con_delayed';
                    544:             } else {
1.672     albertel  545:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       546:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  547:                 &logperm("F:$server:$cmd");
                    548:                 return 'con_failed';
                    549:             }
                    550:         }
                    551:     }
                    552:     return $answer;
1.405     albertel  553: }
                    554: 
1.755     albertel  555: # ------------------------------------------- check if return value is an error
                    556: 
                    557: sub error {
                    558:     my ($result) = @_;
1.756     albertel  559:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  560: 	if ($2 == 2) { return undef; }
                    561: 	return $1;
                    562:     }
                    563:     return undef;
                    564: }
                    565: 
1.783     albertel  566: sub convert_and_load_session_env {
                    567:     my ($lonidsdir,$handle)=@_;
                    568:     my @profile;
                    569:     {
1.917     albertel  570: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    571: 	if (!$opened) {
1.915     albertel  572: 	    return 0;
                    573: 	}
1.783     albertel  574: 	flock($idf,LOCK_SH);
                    575: 	@profile=<$idf>;
                    576: 	close($idf);
                    577:     }
                    578:     my %temp_env;
                    579:     foreach my $line (@profile) {
1.786     albertel  580: 	if ($line !~ m/=/) {
                    581: 	    return 0;
                    582: 	}
1.783     albertel  583: 	chomp($line);
                    584: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    585: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    586:     }
                    587:     unlink("$lonidsdir/$handle.id");
                    588:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    589: 	    0640)) {
                    590: 	%disk_env = %temp_env;
                    591: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    592: 	untie(%disk_env);
                    593:     }
1.786     albertel  594:     return 1;
1.783     albertel  595: }
                    596: 
1.374     www       597: # ------------------------------------------- Transfer profile into environment
1.780     albertel  598: my $env_loaded;
                    599: sub transfer_profile_to_env {
1.788     albertel  600:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    601:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       602: 
1.720     albertel  603:     if (!defined($lonidsdir)) {
                    604: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    605:     }
                    606:     if (!defined($handle)) {
                    607:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    608:     }
                    609: 
1.786     albertel  610:     my $convert;
                    611:     {
1.917     albertel  612:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    613: 	if (!$opened) {
1.915     albertel  614: 	    return;
                    615: 	}
1.786     albertel  616: 	flock($idf,LOCK_SH);
                    617: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    618: 		&GDBM_READER(),0640)) {
                    619: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    620: 	    untie(%disk_env);
                    621: 	} else {
                    622: 	    $convert = 1;
                    623: 	}
                    624:     }
                    625:     if ($convert) {
                    626: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    627: 	    &logthis("Failed to load session, or convert session.");
                    628: 	}
1.374     www       629:     }
1.783     albertel  630: 
1.786     albertel  631:     my %remove;
1.783     albertel  632:     while ( my $envname = each(%env) ) {
1.433     matthew   633:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    634:             if ($time < time-300) {
1.783     albertel  635:                 $remove{$key}++;
1.433     matthew   636:             }
                    637:         }
                    638:     }
1.783     albertel  639: 
1.619     albertel  640:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  641:     $env_loaded=1;
1.783     albertel  642:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   643:         &delenv($expired_key);
1.374     www       644:     }
1.1       albertel  645: }
                    646: 
1.916     albertel  647: # ---------------------------------------------------- Check for valid session 
                    648: sub check_for_valid_session {
1.1245    raeburn   649:     my ($r,$name,$userhashref) = @_;
1.916     albertel  650:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   651:     if ($name eq '') {
                    652:         $name = 'lonID';
                    653:     }
                    654:     my $lonid=$cookies{$name};
1.916     albertel  655:     return undef if (!$lonid);
                    656: 
                    657:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   658:     my $lonidsdir;
                    659:     if ($name eq 'lonDAV') {
                    660:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    661:     } else {
                    662:         $lonidsdir=$r->dir_config('lonIDsDir');
                    663:     }
1.916     albertel  664:     return undef if (!-e "$lonidsdir/$handle.id");
                    665: 
1.917     albertel  666:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    667:     return undef if (!$opened);
1.916     albertel  668: 
                    669:     flock($idf,LOCK_SH);
                    670:     my %disk_env;
                    671:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    672: 	    &GDBM_READER(),0640)) {
                    673: 	return undef;	
                    674:     }
                    675: 
                    676:     if (!defined($disk_env{'user.name'})
                    677: 	|| !defined($disk_env{'user.domain'})) {
                    678: 	return undef;
                    679:     }
1.1245    raeburn   680: 
                    681:     if (ref($userhashref) eq 'HASH') {
                    682:         $userhashref->{'name'} = $disk_env{'user.name'};
                    683:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1212    raeburn   684:     }
1.1245    raeburn   685: 
1.916     albertel  686:     return $handle;
                    687: }
                    688: 
1.830     albertel  689: sub timed_flock {
                    690:     my ($file,$lock_type) = @_;
                    691:     my $failed=0;
                    692:     eval {
                    693: 	local $SIG{__DIE__}='DEFAULT';
                    694: 	local $SIG{ALRM}=sub {
                    695: 	    $failed=1;
                    696: 	    die("failed lock");
                    697: 	};
                    698: 	alarm(13);
                    699: 	flock($file,$lock_type);
                    700: 	alarm(0);
                    701:     };
                    702:     if ($failed) {
                    703: 	return undef;
                    704:     } else {
                    705: 	return 1;
                    706:     }
                    707: }
                    708: 
1.5       www       709: # ---------------------------------------------------------- Append Environment
                    710: 
                    711: sub appenv {
1.949     raeburn   712:     my ($newenv,$roles) = @_;
                    713:     if (ref($newenv) eq 'HASH') {
                    714:         foreach my $key (keys(%{$newenv})) {
                    715:             my $refused = 0;
                    716: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    717:                 $refused = 1;
                    718:                 if (ref($roles) eq 'ARRAY') {
1.1250    raeburn   719:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   720:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    721:                         $refused = 0;
                    722:                     }
                    723:                 }
                    724:             }
                    725:             if ($refused) {
                    726:                 &logthis("<font color=\"blue\">WARNING: ".
                    727:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    728:                          .'</font>');
                    729: 	        delete($newenv->{$key});
                    730:             } else {
                    731:                 $env{$key}=$newenv->{$key};
                    732:             }
                    733:         }
                    734:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    735:         if ($opened
                    736: 	    && &timed_flock($env_file,LOCK_EX)
                    737: 	    &&
                    738: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    739: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    740: 	    while (my ($key,$value) = each(%{$newenv})) {
                    741: 	        $disk_env{$key} = $value;
                    742: 	    }
                    743: 	    untie(%disk_env);
1.35      www       744:         }
1.191     harris41  745:     }
1.56      www       746:     return 'ok';
                    747: }
                    748: # ----------------------------------------------------- Delete from Environment
                    749: 
                    750: sub delenv {
1.1104    raeburn   751:     my ($delthis,$regexp,$roles) = @_;
                    752:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    753:         my $refused = 1;
                    754:         if (ref($roles) eq 'ARRAY') {
                    755:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    756:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    757:                 $refused = 0;
                    758:             }
                    759:         }
                    760:         if ($refused) {
                    761:             &logthis("<font color=\"blue\">WARNING: ".
                    762:                      "Attempt to delete from environment ".$delthis);
                    763:             return 'error';
                    764:         }
1.56      www       765:     }
1.917     albertel  766:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    767:     if ($opened
1.915     albertel  768: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  769: 	&&
                    770: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    771: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  772: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   773: 	    if ($regexp) {
                    774:                 if ($key=~/^$delthis/) {
                    775:                     delete($env{$key});
                    776:                     delete($disk_env{$key});
                    777:                 } 
                    778:             } else {
                    779:                 if ($key=~/^\Q$delthis\E/) {
                    780: 		    delete($env{$key});
                    781: 		    delete($disk_env{$key});
                    782: 	        }
                    783:             }
1.448     albertel  784: 	}
1.783     albertel  785: 	untie(%disk_env);
1.5       www       786:     }
                    787:     return 'ok';
1.369     albertel  788: }
                    789: 
1.790     albertel  790: sub get_env_multiple {
                    791:     my ($name) = @_;
                    792:     my @values;
                    793:     if (defined($env{$name})) {
                    794:         # exists is it an array
                    795:         if (ref($env{$name})) {
                    796:             @values=@{ $env{$name} };
                    797:         } else {
                    798:             $values[0]=$env{$name};
                    799:         }
                    800:     }
                    801:     return(@values);
                    802: }
                    803: 
1.958     www       804: # ------------------------------------------------------------------- Locking
                    805: 
                    806: sub set_lock {
                    807:     my ($text)=@_;
                    808:     $locknum++;
                    809:     my $id=$$.'-'.$locknum;
                    810:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    811:              'session.lock.'.$id => $text});
                    812:     return $id;
                    813: }
                    814: 
                    815: sub get_locks {
                    816:     my $num=0;
                    817:     my %texts=();
                    818:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    819:        if ($lock=~/\w/) {
                    820:           $num++;
                    821:           $texts{$lock}=$env{'session.lock.'.$lock};
                    822:        }
                    823:    }
                    824:    return ($num,%texts);
                    825: }
                    826: 
                    827: sub remove_lock {
                    828:     my ($id)=@_;
                    829:     my $newlocks='';
                    830:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    831:        if (($lock=~/\w/) && ($lock ne $id)) {
                    832:           $newlocks.=','.$lock;
                    833:        }
                    834:     }
                    835:     &appenv({'session.locks' => $newlocks});
                    836:     &delenv('session.lock.'.$id);
                    837: }
                    838: 
                    839: sub remove_all_locks {
                    840:     my $activelocks=$env{'session.locks'};
                    841:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    842:        if ($lock=~/\w/) {
                    843:           &remove_lock($lock);
                    844:        }
                    845:     }
                    846: }
                    847: 
                    848: 
1.369     albertel  849: # ------------------------------------------ Find out current server userload
                    850: sub userload {
                    851:     my $numusers=0;
                    852:     {
                    853: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    854: 	my $filename;
                    855: 	my $curtime=time;
                    856: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  857: 	    next if ($filename eq '.' || $filename eq '..');
                    858: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  859: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  860: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  861: 	}
                    862: 	closedir(LONIDS);
                    863:     }
                    864:     my $userloadpercent=0;
                    865:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    866:     if ($maxuserload) {
1.371     albertel  867: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  868:     }
1.372     albertel  869:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  870:     return $userloadpercent;
1.283     www       871: }
                    872: 
1.1       albertel  873: # ------------------------------ Find server with least workload from spare.tab
1.11      www       874: 
1.1       albertel  875: sub spareserver {
1.1083    raeburn   876:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  877:     my $spare_server;
1.370     albertel  878:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  879:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    880:                                                      :  $userloadpercent;
1.1083    raeburn   881:     my ($uint_dom,$remotesessions);
                    882:     if (($udom ne '') && (&domain($udom) ne '')) {
                    883:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    884:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    885:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    886:         $remotesessions = $udomdefaults{'remotesessions'};
                    887:     }
1.1123    raeburn   888:     my $spareshash = &this_host_spares($udom);
                    889:     if (ref($spareshash) eq 'HASH') {
                    890:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    891:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279    raeburn   892:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    893:                                              $try_server));
1.1123    raeburn   894: 	        ($spare_server, $lowest_load) =
                    895: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    896:             }
1.1083    raeburn   897:         }
1.784     albertel  898: 
1.1123    raeburn   899:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    900: 
                    901:         if (!$found_server) {
                    902:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    903: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn   904:                     next unless (&spare_can_host($udom,$uint_dom,
                    905:                                                  $remotesessions,$try_server));
1.1123    raeburn   906: 	            ($spare_server, $lowest_load) =
                    907: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    908:                 }
                    909: 	    }
                    910:         }
1.784     albertel  911:     }
                    912: 
                    913:     if (!$want_server_name) {
1.968     raeburn   914:         my $protocol = 'http';
                    915:         if ($protocol{$spare_server} eq 'https') {
                    916:             $protocol = $protocol{$spare_server};
                    917:         }
1.1001    raeburn   918:         if (defined($spare_server)) {
                    919:             my $hostname = &hostname($spare_server);
1.1083    raeburn   920:             if (defined($hostname)) {
1.1001    raeburn   921: 	        $spare_server = $protocol.'://'.$hostname;
                    922:             }
                    923:         }
1.784     albertel  924:     }
                    925:     return $spare_server;
                    926: }
                    927: 
                    928: sub compare_server_load {
1.1253    raeburn   929:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    930: 
                    931:     if ($required) {
                    932:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    933:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    934:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    935:         if (($major eq '' && $minor eq '') ||
                    936:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    937:             return ($spare_server,$lowest_load);
                    938:         }
                    939:     }
1.784     albertel  940: 
                    941:     my $loadans     = &reply('load',    $try_server);
                    942:     my $userloadans = &reply('userload',$try_server);
                    943: 
                    944:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   945: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  946:     }
                    947: 
                    948:     my $load;
                    949:     if ($loadans =~ /\d/) {
                    950: 	if ($userloadans =~ /\d/) {
                    951: 	    #both are numbers, pick the bigger one
                    952: 	    $load = ($loadans > $userloadans) ? $loadans 
                    953: 		                              : $userloadans;
1.411     albertel  954: 	} else {
1.784     albertel  955: 	    $load = $loadans;
1.411     albertel  956: 	}
1.784     albertel  957:     } else {
                    958: 	$load = $userloadans;
                    959:     }
                    960: 
                    961:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    962: 	$spare_server = $try_server;
                    963: 	$lowest_load  = $load;
1.370     albertel  964:     }
1.784     albertel  965:     return ($spare_server,$lowest_load);
1.202     matthew   966: }
1.914     albertel  967: 
                    968: # --------------------------- ask offload servers if user already has a session
                    969: sub find_existing_session {
                    970:     my ($udom,$uname) = @_;
1.1123    raeburn   971:     my $spareshash = &this_host_spares($udom);
                    972:     if (ref($spareshash) eq 'HASH') {
                    973:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    974:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    975:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    976:             }
                    977:         }
                    978:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    979:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    980:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    981:             }
                    982:         }
1.914     albertel  983:     }
                    984:     return;
                    985: }
                    986: 
                    987: # -------------------------------- ask if server already has a session for user
                    988: sub has_user_session {
                    989:     my ($lonid,$udom,$uname) = @_;
                    990:     my $result = &reply(join(':','userhassession',
                    991: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    992:     return 1 if ($result eq 'ok');
                    993: 
                    994:     return 0;
                    995: }
                    996: 
1.1076    raeburn   997: # --------- determine least loaded server in a user's domain which allows login
                    998: 
                    999: sub choose_server {
1.1259    raeburn  1000:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1001:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1002:     my %servers = &get_servers($udom);
1.1076    raeburn  1003:     my $lowest_load = 30000;
1.1259    raeburn  1004:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1005:     if ($skiploadbal) {
                   1006:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1007:         unless (defined($cached)) {
                   1008:             my $cachetime = 60*60*24;
                   1009:             my %domconfig =
                   1010:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1011:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1012:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1013:                                            $cachetime);
                   1014:             }
                   1015:         }
                   1016:     }
1.1076    raeburn  1017:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn  1018:         if ($skiploadbal) {
                   1019:             if (ref($balancers) eq 'HASH') {
                   1020:                 next if (exists($balancers->{$lonhost}));
                   1021:             }
                   1022:         }   
1.1115    raeburn  1023:         my $loginvia;
                   1024:         if ($checkloginvia) {
                   1025:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1026:             if ($loginvia) {
                   1027:                 my ($server,$path) = split(/:/,$loginvia);
                   1028:                 ($login_host, $lowest_load) =
1.1253    raeburn  1029:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1030:                 if ($login_host eq $server) {
                   1031:                     $portal_path = $path;
1.1151    raeburn  1032:                     $isredirect = 1;
1.1116    raeburn  1033:                 }
                   1034:             } else {
                   1035:                 ($login_host, $lowest_load) =
1.1253    raeburn  1036:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1037:                 if ($login_host eq $lonhost) {
                   1038:                     $portal_path = '';
1.1151    raeburn  1039:                     $isredirect = ''; 
1.1116    raeburn  1040:                 }
                   1041:             }
                   1042:         } else {
1.1076    raeburn  1043:             ($login_host, $lowest_load) =
1.1253    raeburn  1044:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1045:         }
                   1046:     }
                   1047:     if ($login_host ne '') {
1.1116    raeburn  1048:         $hostname = &hostname($login_host);
1.1076    raeburn  1049:     }
1.1151    raeburn  1050:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn  1051: }
                   1052: 
1.202     matthew  1053: # --------------------------------------------- Try to change a user's password
                   1054: 
                   1055: sub changepass {
1.799     raeburn  1056:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1057:     $currentpass = &escape($currentpass);
                   1058:     $newpass     = &escape($newpass);
1.1030    raeburn  1059:     my $lonhost = $perlvar{'lonHostID'};
                   1060:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1061: 		       $server);
                   1062:     if (! $answer) {
                   1063: 	&logthis("No reply on password change request to $server ".
                   1064: 		 "by $uname in domain $udom.");
                   1065:     } elsif ($answer =~ "^ok") {
                   1066:         &logthis("$uname in $udom successfully changed their password ".
                   1067: 		 "on $server.");
                   1068:     } elsif ($answer =~ "^pwchange_failure") {
                   1069: 	&logthis("$uname in $udom was unable to change their password ".
                   1070: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1071: 		 "or pwchange");
                   1072:     } elsif ($answer =~ "^non_authorized") {
                   1073:         &logthis("$uname in $udom did not get their password correct when ".
                   1074: 		 "attempting to change it on $server.");
                   1075:     } elsif ($answer =~ "^auth_mode_error") {
                   1076:         &logthis("$uname in $udom attempted to change their password despite ".
                   1077: 		 "not being locally or internally authenticated on $server.");
                   1078:     } elsif ($answer =~ "^unknown_user") {
                   1079:         &logthis("$uname in $udom attempted to change their password ".
                   1080: 		 "on $server but were unable to because $server is not ".
                   1081: 		 "their home server.");
                   1082:     } elsif ($answer =~ "^refused") {
                   1083: 	&logthis("$server refused to change $uname in $udom password because ".
                   1084: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1085:     } elsif ($answer =~ "invalid_client") {
                   1086:         &logthis("$server refused to change $uname in $udom password because ".
                   1087:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1088:     }
                   1089:     return $answer;
1.1       albertel 1090: }
                   1091: 
1.169     harris41 1092: # ----------------------- Try to determine user's current authentication scheme
                   1093: 
                   1094: sub queryauthenticate {
                   1095:     my ($uname,$udom)=@_;
1.456     albertel 1096:     my $uhome=&homeserver($uname,$udom);
                   1097:     if (!$uhome) {
                   1098: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1099: 	return 'no_host';
                   1100:     }
                   1101:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1102:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1103: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1104:     }
1.456     albertel 1105:     return $answer;
1.169     harris41 1106: }
                   1107: 
1.1       albertel 1108: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1109: 
1.1       albertel 1110: sub authenticate {
1.1073    raeburn  1111:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1112:     $upass=&escape($upass);
                   1113:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1114:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1115:     my $newhome;
1.836     www      1116:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1117: # Maybe the machine was offline and only re-appeared again recently?
                   1118:         &reconlonc();
                   1119: # One more
1.952     raeburn  1120: 	$uhome=&homeserver($uname,$udom,1);
                   1121:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1122:             if (defined(&domain($udom,'primary'))) {
                   1123:                 $newhome=&domain($udom,'primary');
                   1124:             }
                   1125:             if ($newhome ne '') {
                   1126:                 $uhome = $newhome;
                   1127:             }
                   1128:         }
1.836     www      1129: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1130: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1131: 	    return 'no_host';
                   1132:         }
1.1       albertel 1133:     }
1.1073    raeburn  1134:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1135:     if ($answer eq 'authorized') {
1.952     raeburn  1136:         if ($newhome) {
                   1137:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1138:             return 'no_account_on_host'; 
                   1139:         } else {
                   1140:             &logthis("User $uname at $udom authorized by $uhome");
                   1141:             return $uhome;
                   1142:         }
1.471     albertel 1143:     }
                   1144:     if ($answer eq 'non_authorized') {
                   1145: 	&logthis("User $uname at $udom rejected by $uhome");
                   1146: 	return 'no_host'; 
1.9       www      1147:     }
1.471     albertel 1148:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1149:     return 'no_host';
                   1150: }
                   1151: 
1.1073    raeburn  1152: sub can_host_session {
1.1074    raeburn  1153:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1154:     my $canhost = 1;
1.1074    raeburn  1155:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1156:     if (ref($remotesessions) eq 'HASH') {
                   1157:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1158:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1159:                 $canhost = 0;
                   1160:             } else {
                   1161:                 $canhost = 1;
                   1162:             }
                   1163:         }
                   1164:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1165:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1166:                 $canhost = 1;
                   1167:             } else {
                   1168:                 $canhost = 0;
                   1169:             }
                   1170:         }
                   1171:         if ($canhost) {
                   1172:             if ($remotesessions->{'version'} ne '') {
                   1173:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1174:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1175:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1176:                         my $major = $1;
                   1177:                         my $minor = $2;
                   1178:                         if (($major < $reqmajor ) ||
                   1179:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1180:                             $canhost = 0;
                   1181:                         }
                   1182:                     } else {
                   1183:                         $canhost = 0;
                   1184:                     }
                   1185:                 }
                   1186:             }
                   1187:         }
                   1188:     }
                   1189:     if ($canhost) {
                   1190:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1191:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1192:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1193:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1194:                 if (($uint_dom ne '') && 
                   1195:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1196:                     $canhost = 0;
                   1197:                 } else {
                   1198:                     $canhost = 1;
                   1199:                 }
                   1200:             }
                   1201:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1202:                 if (($uint_dom ne '') && 
                   1203:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1204:                     $canhost = 1;
                   1205:                 } else {
                   1206:                     $canhost = 0;
                   1207:                 }
                   1208:             }
                   1209:         }
                   1210:     }
                   1211:     return $canhost;
                   1212: }
                   1213: 
1.1083    raeburn  1214: sub spare_can_host {
                   1215:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1216:     my $canhost=1;
1.1279    raeburn  1217:     my $try_server_hostname = &hostname($try_server);
                   1218:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1219:     my $serverhomedom = &host_domain($serverhomeID);
                   1220:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1221:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1222:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1223:             $canhost = 0;
                   1224:         }
                   1225:     }
                   1226:     if (($canhost) && ($uint_dom)) {
                   1227:         my @intdoms;
                   1228:         my $internet_names = &get_internet_names($try_server);
                   1229:         if (ref($internet_names) eq 'ARRAY') {
                   1230:             @intdoms = @{$internet_names};
                   1231:         }
                   1232:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1233:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1234:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1235:                                          $remotesessions,
                   1236:                                          $defdomdefaults{'hostedsessions'});
                   1237:         }
1.1083    raeburn  1238:     }
                   1239:     return $canhost;
                   1240: }
                   1241: 
1.1123    raeburn  1242: sub this_host_spares {
                   1243:     my ($dom) = @_;
1.1126    raeburn  1244:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1245:     my @hosts = &current_machine_ids();
                   1246:     foreach my $lonhost (@hosts) {
                   1247:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1248:             $dom_in_use = $dom;
                   1249:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1250:             last;
                   1251:         }
                   1252:     }
1.1126    raeburn  1253:     if ($dom_in_use ne '') {
                   1254:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1255:     }
                   1256:     if (ref($result) ne 'HASH') {
                   1257:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1258:         $dom_in_use = &host_domain($lonhost_in_use);
                   1259:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1260:         if (ref($result) ne 'HASH') {
                   1261:             $result = \%spareid;
                   1262:         }
                   1263:     }
                   1264:     return $result;
                   1265: }
                   1266: 
                   1267: sub spares_for_offload  {
                   1268:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1269:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1270:     if (defined($cached)) {
                   1271:         return $result;
                   1272:     } else {
1.1126    raeburn  1273:         my $cachetime = 60*60*24;
                   1274:         my %domconfig =
                   1275:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1276:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1277:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1278:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1279:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1280:                 }
                   1281:             }
                   1282:         }
                   1283:     }
1.1126    raeburn  1284:     return;
1.1123    raeburn  1285: }
                   1286: 
1.1129    raeburn  1287: sub get_lonbalancer_config {
                   1288:     my ($servers) = @_;
                   1289:     my ($currbalancer,$currtargets);
                   1290:     if (ref($servers) eq 'HASH') {
                   1291:         foreach my $server (keys(%{$servers})) {
                   1292:             my %what = (
                   1293:                          spareid => 1,
                   1294:                          perlvar => 1,
                   1295:                        );
                   1296:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1297:             if ($result eq 'ok') {
                   1298:                 if (ref($returnhash) eq 'HASH') {
                   1299:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1300:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1301:                             $currbalancer = $server;
                   1302:                             $currtargets = {};
                   1303:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1304:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1305:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1306:                                 }
                   1307:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1308:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1309:                                 }
                   1310:                             }
                   1311:                             last;
                   1312:                         }
                   1313:                     }
                   1314:                 }
                   1315:             }
                   1316:         }
                   1317:     }
                   1318:     return ($currbalancer,$currtargets);
                   1319: }
                   1320: 
                   1321: sub check_loadbalancing {
                   1322:     my ($uname,$udom) = @_;
1.1191    raeburn  1323:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1324:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1325:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1326:     my @hosts = &current_machine_ids();
1.1129    raeburn  1327:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1328:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1329:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1330:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1331:     my $domneedscache;
1.1129    raeburn  1332:     my $cachetime = 60*60*24;
                   1333: 
                   1334:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1335:         $dom_in_use = $udom;
                   1336:         $homeintdom = 1;
                   1337:     } else {
                   1338:         $dom_in_use = $serverhomedom;
                   1339:     }
                   1340:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1341:     unless (defined($cached)) {
                   1342:         my %domconfig =
                   1343:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1344:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1345:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1346:         } else {
                   1347:             $domneedscache = $dom_in_use;
1.1129    raeburn  1348:         }
                   1349:     }
                   1350:     if (ref($result) eq 'HASH') {
1.1191    raeburn  1351:         ($is_balancer,$currtargets,$currrules) = 
                   1352:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1353:         if ($is_balancer) {
                   1354:             if (ref($currrules) eq 'HASH') {
                   1355:                 if ($homeintdom) {
                   1356:                     if ($uname ne '') {
                   1357:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1358:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1359:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1360:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1361:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1362:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1363:                             }
                   1364:                         }
                   1365:                         if ($rule_in_effect eq '') {
                   1366:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1367:                             if ($userenv{'inststatus'} ne '') {
                   1368:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1369:                                 my ($othertitle,$usertypes,$types) =
                   1370:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1371:                                 if (ref($types) eq 'ARRAY') {
                   1372:                                     foreach my $type (@{$types}) {
                   1373:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1374:                                             if (exists($currrules->{$type})) {
                   1375:                                                 $rule_in_effect = $currrules->{$type};
                   1376:                                             }
                   1377:                                         }
                   1378:                                     }
                   1379:                                 }
                   1380:                             } else {
                   1381:                                 if (exists($currrules->{'default'})) {
                   1382:                                     $rule_in_effect = $currrules->{'default'};
                   1383:                                 }
                   1384:                             }
                   1385:                         }
                   1386:                     } else {
                   1387:                         if (exists($currrules->{'default'})) {
                   1388:                             $rule_in_effect = $currrules->{'default'};
                   1389:                         }
                   1390:                     }
                   1391:                 } else {
                   1392:                     if ($currrules->{'_LC_external'} ne '') {
                   1393:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1394:                     }
                   1395:                 }
                   1396:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1397:                                                        $uname,$udom);
                   1398:             }
                   1399:         }
                   1400:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1401:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1402:         unless (defined($cached)) {
                   1403:             my %domconfig =
                   1404:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1405:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1406:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1407:             } else {
                   1408:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1409:             }
                   1410:         }
                   1411:         if (ref($result) eq 'HASH') {
1.1191    raeburn  1412:             ($is_balancer,$currtargets,$currrules) = 
                   1413:                 &check_balancer_result($result,@hosts);
                   1414:             if ($is_balancer) {
1.1129    raeburn  1415:                 if (ref($currrules) eq 'HASH') {
                   1416:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1417:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1418:                     }
                   1419:                 }
                   1420:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1421:                                                        $uname,$udom);
                   1422:             }
                   1423:         } else {
                   1424:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1425:                 $is_balancer = 1;
                   1426:                 $offloadto = &this_host_spares($dom_in_use);
                   1427:             }
1.1307    raeburn  1428:             unless (defined($cached)) {
                   1429:                 $domneedscache = $serverhomedom;
                   1430:             }
1.1129    raeburn  1431:         }
                   1432:     } else {
                   1433:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1434:             $is_balancer = 1;
                   1435:             $offloadto = &this_host_spares($dom_in_use);
                   1436:         }
1.1307    raeburn  1437:         unless (defined($cached)) {
                   1438:             $domneedscache = $serverhomedom;
                   1439:         }
                   1440:     }
                   1441:     if ($domneedscache) {
                   1442:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1443:     }
1.1176    raeburn  1444:     if ($is_balancer) {
                   1445:         my $lowest_load = 30000;
                   1446:         if (ref($offloadto) eq 'HASH') {
                   1447:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1448:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1449:                     ($otherserver,$lowest_load) =
                   1450:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1451:                 }
1.1129    raeburn  1452:             }
1.1176    raeburn  1453:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1454: 
1.1176    raeburn  1455:             if (!$found_server) {
                   1456:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1457:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1458:                         ($otherserver,$lowest_load) =
                   1459:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1460:                     }
                   1461:                 }
                   1462:             }
                   1463:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1464:             if (@{$offloadto} == 1) {
                   1465:                 $otherserver = $offloadto->[0];
                   1466:             } elsif (@{$offloadto} > 1) {
                   1467:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1468:                     ($otherserver,$lowest_load) =
                   1469:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1470:                 }
                   1471:             }
                   1472:         }
1.1176    raeburn  1473:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1474:             $is_balancer = 0;
                   1475:             if ($uname ne '' && $udom ne '') {
                   1476:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1477:                     
                   1478:                     &appenv({'user.loadbalexempt'     => $lonhost,  
                   1479:                              'user.loadbalcheck.time' => time});
                   1480:                 }
1.1129    raeburn  1481:             }
                   1482:         }
                   1483:     }
                   1484:     return ($is_balancer,$otherserver);
                   1485: }
                   1486: 
1.1191    raeburn  1487: sub check_balancer_result {
                   1488:     my ($result,@hosts) = @_;
                   1489:     my ($is_balancer,$currtargets,$currrules);
                   1490:     if (ref($result) eq 'HASH') {
                   1491:         if ($result->{'lonhost'} ne '') {
                   1492:             my $currbalancer = $result->{'lonhost'};
                   1493:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1494:                 $is_balancer = 1;
                   1495:                 $currtargets = $result->{'targets'};
                   1496:                 $currrules = $result->{'rules'};
                   1497:             }
                   1498:         } else {
                   1499:             foreach my $key (keys(%{$result})) {
                   1500:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1501:                     (ref($result->{$key}) eq 'HASH')) {
                   1502:                     $is_balancer = 1;
                   1503:                     $currrules = $result->{$key}{'rules'};
                   1504:                     $currtargets = $result->{$key}{'targets'};
                   1505:                     last;
                   1506:                 }
                   1507:             }
                   1508:         }
                   1509:     }
                   1510:     return ($is_balancer,$currtargets,$currrules);
                   1511: }
                   1512: 
1.1129    raeburn  1513: sub get_loadbalancer_targets {
                   1514:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1515:     my $offloadto;
1.1175    raeburn  1516:     if ($rule_in_effect eq 'none') {
                   1517:         return [$perlvar{'lonHostID'}];
                   1518:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1519:         $offloadto = $currtargets;
                   1520:     } else {
                   1521:         if ($rule_in_effect eq 'homeserver') {
                   1522:             my $homeserver = &homeserver($uname,$udom);
                   1523:             if ($homeserver ne 'no_host') {
                   1524:                 $offloadto = [$homeserver];
                   1525:             }
                   1526:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1527:             my %domconfig =
                   1528:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1529:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1530:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1531:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1532:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1533:                     }
                   1534:                 }
                   1535:             } else {
1.1178    raeburn  1536:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1537:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1538:                 if (&hostname($remotebalancer) ne '') {
                   1539:                     $offloadto = [$remotebalancer];
                   1540:                 }
                   1541:             }
                   1542:         } elsif (&hostname($rule_in_effect) ne '') {
                   1543:             $offloadto = [$rule_in_effect];
                   1544:         }
                   1545:     }
                   1546:     return $offloadto;
                   1547: }
                   1548: 
1.1127    raeburn  1549: sub internet_dom_servers {
                   1550:     my ($dom) = @_;
                   1551:     my (%uniqservers,%servers);
                   1552:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1553:     my @machinedoms = &machine_domains($primaryserver);
                   1554:     foreach my $mdom (@machinedoms) {
                   1555:         my %currservers = %servers;
                   1556:         my %server = &get_servers($mdom);
                   1557:         %servers = (%currservers,%server);
                   1558:     }
                   1559:     my %by_hostname;
                   1560:     foreach my $id (keys(%servers)) {
                   1561:         push(@{$by_hostname{$servers{$id}}},$id);
                   1562:     }
                   1563:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1564:         if (@{$by_hostname{$hostname}} > 1) {
                   1565:             my $match = 0;
                   1566:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1567:                 if (&host_domain($id) eq $dom) {
                   1568:                     $uniqservers{$id} = $hostname;
                   1569:                     $match = 1;
                   1570:                 }
                   1571:             }
                   1572:             unless ($match) {
                   1573:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1574:             }
                   1575:         } else {
                   1576:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1577:         }
                   1578:     }
                   1579:     return %uniqservers;
                   1580: }
                   1581: 
1.1       albertel 1582: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1583: 
1.599     albertel 1584: my %homecache;
1.1       albertel 1585: sub homeserver {
1.230     stredwic 1586:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1587:     my $index="$uname:$udom";
1.426     albertel 1588: 
1.599     albertel 1589:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1590: 
                   1591:     my %servers = &get_servers($udom,'library');
                   1592:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1593:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1594: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1595: 
                   1596: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1597: 	if ($answer eq 'found') {
                   1598: 	    delete($badServerCache{$tryserver}); 
                   1599: 	    return $homecache{$index}=$tryserver;
                   1600: 	} elsif ($answer eq 'no_host') {
                   1601: 	    $badServerCache{$tryserver}=1;
                   1602: 	}
1.1       albertel 1603:     }    
                   1604:     return 'no_host';
1.70      www      1605: }
                   1606: 
1.1300    raeburn  1607: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1608: 
                   1609: sub idget {
1.1300    raeburn  1610:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1611:     my %returnhash=();
1.1300    raeburn  1612:     my @ids=(); 
                   1613:     if (ref($idsref) eq 'ARRAY') {
                   1614:         @ids = @{$idsref};
                   1615:     } else {
                   1616:         return %returnhash; 
                   1617:     }
                   1618:     if ($namespace eq '') {
                   1619:         $namespace = 'ids';
                   1620:     }
1.70      www      1621:     
1.841     albertel 1622:     my %servers = &get_servers($udom,'library');
                   1623:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1624: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1625: 	if ($namespace eq 'ids') {
                   1626: 	    $idlist=~tr/A-Z/a-z/;
                   1627: 	}
                   1628: 	my $reply;
                   1629: 	if ($namespace eq 'ids') {
                   1630: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1631: 	} else {
                   1632: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1633: 	}
1.841     albertel 1634: 	my @answer=();
                   1635: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1636: 	    @answer=split(/\&/,$reply);
                   1637: 	}                    ;
                   1638: 	my $i;
                   1639: 	for ($i=0;$i<=$#ids;$i++) {
                   1640: 	    if ($answer[$i]) {
1.1299    raeburn  1641: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1642: 	    }
1.841     albertel 1643: 	}
1.1300    raeburn  1644:     }
1.70      www      1645:     return %returnhash;
                   1646: }
                   1647: 
                   1648: # ------------------------------------- Find the IDs behind a list of usernames
                   1649: 
                   1650: sub idrget {
                   1651:     my ($udom,@unames)=@_;
                   1652:     my %returnhash=();
1.800     albertel 1653:     foreach my $uname (@unames) {
                   1654:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1655:     }
1.70      www      1656:     return %returnhash;
                   1657: }
                   1658: 
1.1300    raeburn  1659: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      1660: 
                   1661: sub idput {
1.1300    raeburn  1662:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      1663:     my %servers=();
1.1300    raeburn  1664:     my %ids=();
                   1665:     my %byid = ();
                   1666:     if (ref($idsref) eq 'HASH') {
                   1667:         %ids=%{$idsref};
                   1668:     }
                   1669:     if ($namespace eq '') {
                   1670:         $namespace = 'ids'; 
                   1671:     }
1.800     albertel 1672:     foreach my $uname (keys(%ids)) {
                   1673: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  1674:         if ($uhom eq '') {
                   1675:             $uhom=&homeserver($uname,$udom);
                   1676:         }
1.70      www      1677:         if ($uhom ne 'no_host') {
1.800     albertel 1678:             my $esc_unam=&escape($uname);
1.1300    raeburn  1679:             if ($namespace eq 'ids') {
                   1680:                 my $id=&escape($ids{$uname});
                   1681:                 $id=~tr/A-Z/a-z/;
                   1682:                 my $esc_unam=&escape($uname);
                   1683:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      1684:             } else {
1.1300    raeburn  1685:                 my @currids = split(/,/,$ids{$uname});
                   1686:                 foreach my $id (@currids) {
                   1687:                     $byid{$uhom}{$id} .= $uname.',';
                   1688:                 }
                   1689:             }
                   1690:         }
                   1691:     }
                   1692:     if ($namespace eq 'clickers') {
                   1693:         foreach my $server (keys(%byid)) {
                   1694:             if (ref($byid{$server}) eq 'HASH') {
                   1695:                 foreach my $id (keys(%{$byid{$server}})) {
                   1696:                     $byid{$server} =~ s/,$//;
                   1697:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   1698:                 }
1.70      www      1699:             }
                   1700:         }
1.191     harris41 1701:     }
1.800     albertel 1702:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1703:         $servers{$server} =~ s/\&$//;
                   1704:         if ($namespace eq 'ids') {     
                   1705:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   1706:         } else {
                   1707:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   1708:         }
1.191     harris41 1709:     }
1.344     www      1710: }
                   1711: 
1.1300    raeburn  1712: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  1713: 
                   1714: sub iddel {
1.1300    raeburn  1715:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  1716:     my %result=();
1.1300    raeburn  1717:     my %ids=();
                   1718:     my %byid = ();
                   1719:     if (ref($idshashref) eq 'HASH') {
                   1720:         %ids=%{$idshashref};
                   1721:     } else {
1.1231    raeburn  1722:         return %result;
                   1723:     }
1.1300    raeburn  1724:     if ($namespace eq '') {
                   1725:         $namespace = 'ids';
                   1726:     }
1.1231    raeburn  1727:     my %servers=();
1.1300    raeburn  1728:     while (my ($id,$unamestr) = each(%ids)) {
                   1729:         if ($namespace eq 'ids') {
                   1730:             my $uhom = $uhome;
                   1731:             if ($uhom eq '') { 
                   1732:                 $uhom=&homeserver($unamestr,$udom);
                   1733:             }
                   1734:             if ($uhom ne 'no_host') {
                   1735:                 $servers{$uhom}.='&'.&escape($id);
                   1736:             }
                   1737:          } else {
                   1738:             my @curritems = split(/,/,$ids{$id});
                   1739:             foreach my $uname (@curritems) {
                   1740:                 my $uhom = $uhome;
                   1741:                 if ($uhom eq '') {
                   1742:                     $uhom=&homeserver($uname,$udom);
                   1743:                 }
                   1744:                 if ($uhom ne 'no_host') { 
                   1745:                     $byid{$uhom}{$id} .= $uname.',';
                   1746:                 }
                   1747:             }
1.1231    raeburn  1748:         }
1.1300    raeburn  1749:     }
                   1750:     if ($namespace eq 'clickers') {
                   1751:         foreach my $server (keys(%byid)) {
                   1752:             if (ref($byid{$server}) eq 'HASH') {
                   1753:                 foreach my $id (keys(%{$byid{$server}})) {
                   1754:                     $byid{$server}{$id} =~ s/,$//;
                   1755:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   1756:                 }
1.1231    raeburn  1757:             }
                   1758:         }
                   1759:     }
                   1760:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1761:         $servers{$server} =~ s/\&$//;
                   1762:         if ($namespace eq 'ids') {
                   1763:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1764:         } elsif ($namespace eq 'clickers') {
                   1765:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   1766:         }
1.1231    raeburn  1767:     }
                   1768:     return %result;
                   1769: }
                   1770: 
1.1300    raeburn  1771: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   1772: 
                   1773: sub updateclickers {
                   1774:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   1775:     my %clickers;
                   1776:     if (ref($idshashref) eq 'HASH') {
                   1777:         %clickers=%{$idshashref};
                   1778:     } else {
                   1779:         return;
                   1780:     }
                   1781:     my $items='';
                   1782:     foreach my $item (keys(%clickers)) {
                   1783:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   1784:     }
                   1785:     $items=~s/\&$//;
                   1786:     my $request = "updateclickers:$udom:$action:$items";
                   1787:     if ($critical) {
                   1788:         return &critical($request,$uhome);
                   1789:     } else {
                   1790:         return &reply($request,$uhome);
                   1791:     }
                   1792: }
                   1793: 
1.1023    raeburn  1794: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1795: sub dump_dom {
1.1165    droeschl 1796:     my ($namespace, $udom, $regexp) = @_;
                   1797: 
                   1798:     $udom ||= $env{'user.domain'};
                   1799: 
                   1800:     return () unless $udom;
                   1801: 
                   1802:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1803: }
                   1804: 
1.1023    raeburn  1805: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1806: 
                   1807: sub get_dom {
1.860     raeburn  1808:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  1809:     return if ($udom eq 'public');
1.806     raeburn  1810:     my $items='';
                   1811:     foreach my $item (@$storearr) {
                   1812:         $items.=&escape($item).'&';
                   1813:     }
                   1814:     $items=~s/\&$//;
1.860     raeburn  1815:     if (!$udom) {
                   1816:         $udom=$env{'user.domain'};
1.1267    raeburn  1817:         return if ($udom eq 'public');
1.860     raeburn  1818:         if (defined(&domain($udom,'primary'))) {
                   1819:             $uhome=&domain($udom,'primary');
                   1820:         } else {
1.874     albertel 1821:             undef($uhome);
1.860     raeburn  1822:         }
                   1823:     } else {
                   1824:         if (!$uhome) {
                   1825:             if (defined(&domain($udom,'primary'))) {
                   1826:                 $uhome=&domain($udom,'primary');
                   1827:             }
                   1828:         }
                   1829:     }
                   1830:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1831:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1832:         my %returnhash;
1.875     albertel 1833:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1834:             return %returnhash;
                   1835:         }
1.806     raeburn  1836:         my @pairs=split(/\&/,$rep);
                   1837:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1838:             return @pairs;
                   1839:         }
                   1840:         my $i=0;
                   1841:         foreach my $item (@$storearr) {
                   1842:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1843:             $i++;
                   1844:         }
                   1845:         return %returnhash;
                   1846:     } else {
1.880     banghart 1847:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1848:     }
                   1849: }
                   1850: 
                   1851: # -------------------------------------------- put items in domain db files 
                   1852: 
                   1853: sub put_dom {
1.860     raeburn  1854:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1855:     if (!$udom) {
                   1856:         $udom=$env{'user.domain'};
                   1857:         if (defined(&domain($udom,'primary'))) {
                   1858:             $uhome=&domain($udom,'primary');
                   1859:         } else {
1.874     albertel 1860:             undef($uhome);
1.860     raeburn  1861:         }
                   1862:     } else {
                   1863:         if (!$uhome) {
                   1864:             if (defined(&domain($udom,'primary'))) {
                   1865:                 $uhome=&domain($udom,'primary');
                   1866:             }
                   1867:         }
                   1868:     } 
                   1869:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1870:         my $items='';
                   1871:         foreach my $item (keys(%$storehash)) {
                   1872:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1873:         }
                   1874:         $items=~s/\&$//;
                   1875:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1876:     } else {
1.860     raeburn  1877:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1878:     }
                   1879: }
                   1880: 
1.1023    raeburn  1881: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1882: sub newput_dom {
1.1023    raeburn  1883:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1884:     my $result;
                   1885:     if (!$udom) {
                   1886:         $udom=$env{'user.domain'};
                   1887:     }
1.1023    raeburn  1888:     if ($udom) {
                   1889:         my $uname = &get_domainconfiguser($udom);
                   1890:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1891:     }
                   1892:     return $result;
                   1893: }
                   1894: 
1.1023    raeburn  1895: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1896: sub del_dom {
1.1023    raeburn  1897:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1898:     if (ref($storearr) eq 'ARRAY') {
                   1899:         if (!$udom) {
                   1900:             $udom=$env{'user.domain'};
                   1901:         }
1.1023    raeburn  1902:         if ($udom) {
                   1903:             my $uname = &get_domainconfiguser($udom); 
                   1904:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1905:         }
                   1906:     }
                   1907: }
                   1908: 
1.1023    raeburn  1909: # ----------------------------------construct domainconfig user for a domain 
                   1910: sub get_domainconfiguser {
                   1911:     my ($udom) = @_;
                   1912:     return $udom.'-domainconfig';
                   1913: }
                   1914: 
1.837     raeburn  1915: sub retrieve_inst_usertypes {
                   1916:     my ($udom) = @_;
                   1917:     my (%returnhash,@order);
1.989     raeburn  1918:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1919:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1920:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  1921:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1922:     } else {
                   1923:         if (defined(&domain($udom,'primary'))) {
                   1924:             my $uhome=&domain($udom,'primary');
                   1925:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1926:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  1927:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1928:                 return (\%returnhash,\@order);
                   1929:             }
                   1930:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1931:             my @pairs=split(/\&/,$hashitems);
                   1932:             foreach my $item (@pairs) {
                   1933:                 my ($key,$value)=split(/=/,$item,2);
                   1934:                 $key = &unescape($key);
                   1935:                 next if ($key =~ /^error: 2 /);
                   1936:                 $returnhash{$key}=&thaw_unescape($value);
                   1937:             }
                   1938:             my @esc_order = split(/\&/,$orderitems);
                   1939:             foreach my $item (@esc_order) {
                   1940:                 push(@order,&unescape($item));
                   1941:             }
                   1942:         } else {
1.1256    raeburn  1943:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1944:         }
1.1256    raeburn  1945:         return (\%returnhash,\@order);
1.837     raeburn  1946:     }
                   1947: }
                   1948: 
1.868     raeburn  1949: sub is_domainimage {
                   1950:     my ($url) = @_;
1.1306    raeburn  1951:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  1952:         if (&domain($1) ne '') {
                   1953:             return '1';
                   1954:         }
                   1955:     }
                   1956:     return;
                   1957: }
                   1958: 
1.899     raeburn  1959: sub inst_directory_query {
                   1960:     my ($srch) = @_;
                   1961:     my $udom = $srch->{'srchdomain'};
                   1962:     my %results;
                   1963:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1964:     my $outcome;
1.899     raeburn  1965:     if ($homeserver ne '') {
1.904     albertel 1966: 	my $queryid=&reply("querysend:instdirsearch:".
                   1967: 			   &escape($srch->{'srchby'}).':'.
                   1968: 			   &escape($srch->{'srchterm'}).':'.
                   1969: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1970: 	my $host=&hostname($homeserver);
                   1971: 	if ($queryid !~/^\Q$host\E\_/) {
                   1972: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1973: 	    return;
                   1974: 	}
                   1975: 	my $response = &get_query_reply($queryid);
                   1976: 	my $maxtries = 5;
                   1977: 	my $tries = 1;
                   1978: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1979: 	    $response = &get_query_reply($queryid);
                   1980: 	    $tries ++;
                   1981: 	}
                   1982: 
                   1983:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1984:             if ($response eq 'unavailable') {
                   1985:                 $outcome = $response;
                   1986:             } else {
                   1987:                 $outcome = 'ok';
                   1988:                 my @matches = split(/\n/,$response);
                   1989:                 foreach my $match (@matches) {
                   1990:                     my ($key,$value) = split(/=/,$match);
                   1991:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1992:                 }
1.899     raeburn  1993:             }
                   1994:         }
                   1995:     }
1.909     raeburn  1996:     return ($outcome,%results);
1.899     raeburn  1997: }
                   1998: 
                   1999: sub usersearch {
                   2000:     my ($srch) = @_;
                   2001:     my $dom = $srch->{'srchdomain'};
                   2002:     my %results;
                   2003:     my %libserv = &all_library();
                   2004:     my $query = 'usersearch';
                   2005:     foreach my $tryserver (keys(%libserv)) {
                   2006:         if (&host_domain($tryserver) eq $dom) {
                   2007:             my $host=&hostname($tryserver);
                   2008:             my $queryid=
1.911     raeburn  2009:                 &reply("querysend:".&escape($query).':'.
                   2010:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2011:                        &escape($srch->{'srchtype'}).':'.
                   2012:                        &escape($srch->{'srchterm'}),$tryserver);
                   2013:             if ($queryid !~/^\Q$host\E\_/) {
                   2014:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2015:                 next;
1.899     raeburn  2016:             }
                   2017:             my $reply = &get_query_reply($queryid);
                   2018:             my $maxtries = 1;
                   2019:             my $tries = 1;
                   2020:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2021:                 $reply = &get_query_reply($queryid);
                   2022:                 $tries ++;
                   2023:             }
                   2024:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2025:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2026:             } else {
1.911     raeburn  2027:                 my @matches;
                   2028:                 if ($reply =~ /\n/) {
                   2029:                     @matches = split(/\n/,$reply);
                   2030:                 } else {
                   2031:                     @matches = split(/\&/,$reply);
                   2032:                 }
1.899     raeburn  2033:                 foreach my $match (@matches) {
                   2034:                     my ($uname,$udom,%userhash);
1.911     raeburn  2035:                     foreach my $entry (split(/:/,$match)) {
                   2036:                         my ($key,$value) =
                   2037:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2038:                         $userhash{$key} = $value;
                   2039:                         if ($key eq 'username') {
                   2040:                             $uname = $value;
                   2041:                         } elsif ($key eq 'domain') {
                   2042:                             $udom = $value;
1.911     raeburn  2043:                         }
1.899     raeburn  2044:                     }
                   2045:                     $results{$uname.':'.$udom} = \%userhash;
                   2046:                 }
                   2047:             }
                   2048:         }
                   2049:     }
                   2050:     return %results;
                   2051: }
                   2052: 
1.912     raeburn  2053: sub get_instuser {
                   2054:     my ($udom,$uname,$id) = @_;
                   2055:     my $homeserver = &domain($udom,'primary');
                   2056:     my ($outcome,%results);
                   2057:     if ($homeserver ne '') {
                   2058:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2059:                            &escape($id).':'.&escape($udom),$homeserver);
                   2060:         my $host=&hostname($homeserver);
                   2061:         if ($queryid !~/^\Q$host\E\_/) {
                   2062:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2063:             return;
                   2064:         }
                   2065:         my $response = &get_query_reply($queryid);
                   2066:         my $maxtries = 5;
                   2067:         my $tries = 1;
                   2068:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2069:             $response = &get_query_reply($queryid);
                   2070:             $tries ++;
                   2071:         }
                   2072:         if (!&error($response) && $response ne 'refused') {
                   2073:             if ($response eq 'unavailable') {
                   2074:                 $outcome = $response;
                   2075:             } else {
                   2076:                 $outcome = 'ok';
                   2077:                 my @matches = split(/\n/,$response);
                   2078:                 foreach my $match (@matches) {
                   2079:                     my ($key,$value) = split(/=/,$match);
                   2080:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2081:                 }
                   2082:             }
                   2083:         }
                   2084:     }
                   2085:     my %userinfo;
                   2086:     if (ref($results{$uname}) eq 'HASH') {
                   2087:         %userinfo = %{$results{$uname}};
                   2088:     } 
                   2089:     return ($outcome,%userinfo);
                   2090: }
                   2091: 
1.1290    raeburn  2092: sub get_multiple_instusers {
                   2093:     my ($udom,$users,$caller) = @_;
                   2094:     my ($outcome,$results);
                   2095:     if (ref($users) eq 'HASH') {
                   2096:         my $count = keys(%{$users}); 
                   2097:         my $requested = &freeze_escape($users);
                   2098:         my $homeserver = &domain($udom,'primary');
                   2099:         if ($homeserver ne '') {
                   2100:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2101:             my $host=&hostname($homeserver);
                   2102:             if ($queryid !~/^\Q$host\E\_/) {
                   2103:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2104:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2105:                 return ($outcome,$results);
                   2106:             }
                   2107:             my $response = &get_query_reply($queryid);
                   2108:             my $maxtries = 5;
                   2109:             if ($count > 100) {
                   2110:                 $maxtries = 1+int($count/20);
                   2111:             }
                   2112:             my $tries = 1;
                   2113:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2114:                 $response = &get_query_reply($queryid);
                   2115:                 $tries ++;
                   2116:             }
                   2117:             if ($response eq '') {
                   2118:                 $results = {};
                   2119:                 foreach my $key (keys(%{$users})) {
                   2120:                     my ($uname,$id);
                   2121:                     if ($caller eq 'id') {
                   2122:                         $id = $key;
                   2123:                     } else {
                   2124:                         $uname = $key;
                   2125:                     }
                   2126:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2127:                     $outcome = $resp;
1.1290    raeburn  2128:                     if ($resp eq 'ok') {
                   2129:                         %{$results} = (%{$results}, %info);
                   2130:                     } else {
                   2131:                         last;
                   2132:                     }
                   2133:                 }
                   2134:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2135:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2136:                     $outcome = $response;
                   2137:                 } else {
1.1291    raeburn  2138:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2139:                     if ($outcome eq 'ok') {
                   2140:                         $results = &thaw_unescape($userdata); 
                   2141:                     }
                   2142:                 }
                   2143:             }
                   2144:         }
                   2145:     }
                   2146:     return ($outcome,$results);
                   2147: }
                   2148: 
1.912     raeburn  2149: sub inst_rulecheck {
1.923     raeburn  2150:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2151:     my %returnhash;
                   2152:     if ($udom ne '') {
                   2153:         if (ref($rules) eq 'ARRAY') {
                   2154:             @{$rules} = map {&escape($_);} (@{$rules});
                   2155:             my $rulestr = join(':',@{$rules});
                   2156:             my $homeserver=&domain($udom,'primary');
                   2157:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2158:                 my $response;
                   2159:                 if ($item eq 'username') {                
                   2160:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2161:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2162:                                               $homeserver));
1.923     raeburn  2163:                 } elsif ($item eq 'id') {
                   2164:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2165:                                               ':'.&escape($id).':'.$rulestr,
                   2166:                                               $homeserver));
1.945     raeburn  2167:                 } elsif ($item eq 'selfcreate') {
                   2168:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2169:                                                &escape($udom).':'.&escape($uname).
                   2170:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2171:                 }
1.912     raeburn  2172:                 if ($response ne 'refused') {
                   2173:                     my @pairs=split(/\&/,$response);
                   2174:                     foreach my $item (@pairs) {
                   2175:                         my ($key,$value)=split(/=/,$item,2);
                   2176:                         $key = &unescape($key);
                   2177:                         next if ($key =~ /^error: 2 /);
                   2178:                         $returnhash{$key}=&thaw_unescape($value);
                   2179:                     }
                   2180:                 }
                   2181:             }
                   2182:         }
                   2183:     }
                   2184:     return %returnhash;
                   2185: }
                   2186: 
                   2187: sub inst_userrules {
1.923     raeburn  2188:     my ($udom,$check) = @_;
1.912     raeburn  2189:     my (%ruleshash,@ruleorder);
                   2190:     if ($udom ne '') {
                   2191:         my $homeserver=&domain($udom,'primary');
                   2192:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2193:             my $response;
                   2194:             if ($check eq 'id') {
                   2195:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2196:                                  $homeserver);
1.943     raeburn  2197:             } elsif ($check eq 'email') {
                   2198:                 $response=&reply('instemailrules:'.&escape($udom),
                   2199:                                  $homeserver);
1.923     raeburn  2200:             } else {
                   2201:                 $response=&reply('instuserrules:'.&escape($udom),
                   2202:                                  $homeserver);
                   2203:             }
1.912     raeburn  2204:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2205:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2206:                 ($response ne 'no_such_host')) {
                   2207:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2208:                 my @pairs=split(/\&/,$hashitems);
                   2209:                 foreach my $item (@pairs) {
                   2210:                     my ($key,$value)=split(/=/,$item,2);
                   2211:                     $key = &unescape($key);
                   2212:                     next if ($key =~ /^error: 2 /);
                   2213:                     $ruleshash{$key}=&thaw_unescape($value);
                   2214:                 }
                   2215:                 my @esc_order = split(/\&/,$orderitems);
                   2216:                 foreach my $item (@esc_order) {
                   2217:                     push(@ruleorder,&unescape($item));
                   2218:                 }
                   2219:             }
                   2220:         }
                   2221:     }
                   2222:     return (\%ruleshash,\@ruleorder);
                   2223: }
                   2224: 
1.976     raeburn  2225: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2226: 
                   2227: sub get_domain_defaults {
1.1240    raeburn  2228:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2229:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2230:     my $cachetime = 60*60*24;
1.1240    raeburn  2231:     unless ($ignore_cache) {
                   2232:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2233:         if (defined($cached)) {
                   2234:             if (ref($result) eq 'HASH') {
                   2235:                 return %{$result};
                   2236:             }
1.943     raeburn  2237:         }
                   2238:     }
                   2239:     my %domdefaults;
                   2240:     my %domconfig =
1.989     raeburn  2241:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2242:                                   'requestcourses','inststatus',
1.1183    raeburn  2243:                                   'coursedefaults','usersessions',
1.1258    raeburn  2244:                                   'requestauthor','selfenrollment',
1.1320    raeburn  2245:                                   'coursecategories','ssl','autoenroll',
                   2246:                                   'trust'],$domain);
1.1305    raeburn  2247:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2248:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2249:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2250:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2251:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2252:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2253:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2254:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  2255:     } else {
                   2256:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2257:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2258:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2259:     }
1.976     raeburn  2260:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2261:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2262:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2263:         } else {
                   2264:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2265:         }
1.1177    raeburn  2266:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2267:         foreach my $item (@usertools) {
                   2268:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2269:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2270:             }
                   2271:         }
1.1229    raeburn  2272:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2273:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2274:         }
1.976     raeburn  2275:     }
1.985     raeburn  2276:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2277:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2278:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2279:         }
                   2280:     }
1.1183    raeburn  2281:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2282:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2283:     }
1.989     raeburn  2284:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2285:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2286:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2287:         }
                   2288:     }
1.1047    raeburn  2289:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2290:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2291:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2292:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2293:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2294:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2295:         }
1.1254    raeburn  2296:         foreach my $type (@coursetypes) {
                   2297:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2298:                 unless ($type eq 'community') {
                   2299:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2300:                 }
                   2301:             }
                   2302:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2303:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2304:             }
1.1277    raeburn  2305:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2306:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2307:                     $domdefaults{$type.'postsubtimeout'} = 
                   2308:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2309:                 }
                   2310:             }
1.1230    raeburn  2311:         }
1.1286    raeburn  2312:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2313:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2314:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2315:                 if (@clonecodes) {
                   2316:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2317:                 }
                   2318:             }
                   2319:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2320:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2321:         }
1.1047    raeburn  2322:     }
1.1073    raeburn  2323:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2324:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2325:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2326:         }
                   2327:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2328:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2329:         }
1.1279    raeburn  2330:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2331:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2332:         }
1.1073    raeburn  2333:     }
1.1254    raeburn  2334:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2335:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2336:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2337:                             'approval','limit');
                   2338:             foreach my $type (@coursetypes) {
                   2339:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2340:                     my @mgrdc = ();
                   2341:                     foreach my $item (@settings) {
                   2342:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2343:                             push(@mgrdc,$item);
                   2344:                         }
                   2345:                     }
                   2346:                     if (@mgrdc) {
                   2347:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2348:                     }
                   2349:                 }
                   2350:             }
                   2351:         }
                   2352:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2353:             foreach my $type (@coursetypes) {
                   2354:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2355:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2356:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2357:                     }
                   2358:                 }
                   2359:             }
                   2360:         }
                   2361:     }
1.1258    raeburn  2362:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2363:         $domdefaults{'catauth'} = 'std';
                   2364:         $domdefaults{'catunauth'} = 'std';
                   2365:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2366:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2367:         }
                   2368:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2369:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2370:         }
                   2371:     }
1.1315    raeburn  2372:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2373:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2374:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2375:         }
                   2376:         if (ref($domconfig{'ssl'}{'connect'}) eq 'HASH') {
                   2377:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connect'};
                   2378:         }
                   2379:     }
1.1320    raeburn  2380:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2381:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2382:         foreach my $prefix (@prefixes) {
                   2383:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2384:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2385:             }
                   2386:         }
                   2387:     }
1.1314    raeburn  2388:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2389:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2390:     }
1.1219    raeburn  2391:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2392:     return %domdefaults;
                   2393: }
                   2394: 
1.1311    raeburn  2395: sub course_portal_url {
                   2396:     my ($cnum,$cdom) = @_;
                   2397:     my $chome = &homeserver($cnum,$cdom);
                   2398:     my $hostname = &hostname($chome);
                   2399:     my $protocol = $protocol{$chome};
                   2400:     $protocol = 'http' if ($protocol ne 'https');
                   2401:     my %domdefaults = &get_domain_defaults($cdom);
                   2402:     my $firsturl;
                   2403:     if ($domdefaults{'portal_def'}) {
                   2404:         $firsturl = $domdefaults{'portal_def'};
                   2405:     } else {
                   2406:         $firsturl = $protocol.'://'.$hostname;
                   2407:     }
                   2408:     return $firsturl;
                   2409: }
                   2410: 
1.344     www      2411: # --------------------------------------------------- Assign a key to a student
                   2412: 
                   2413: sub assign_access_key {
1.364     www      2414: #
                   2415: # a valid key looks like uname:udom#comments
                   2416: # comments are being appended
                   2417: #
1.498     www      2418:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2419:     $kdom=
1.620     albertel 2420:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2421:     $knum=
1.620     albertel 2422:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2423:     $cdom=
1.620     albertel 2424:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2425:     $cnum=
1.620     albertel 2426:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2427:     $udom=$env{'user.name'} unless (defined($udom));
                   2428:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2429:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2430:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2431:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2432:                                                   # assigned to this person
                   2433:                                                   # - this should not happen,
1.345     www      2434:                                                   # unless something went wrong
                   2435:                                                   # the first time around
                   2436: # ready to assign
1.364     www      2437:         $logentry=$1.'; '.$logentry;
1.496     www      2438:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2439:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2440: # key now belongs to user
1.346     www      2441: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2442:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2443:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2444:                 return 'ok';
                   2445:             } else {
                   2446:                 return 
                   2447:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2448: 	    }
                   2449:         } else {
                   2450:             return 'error: Could not assign key, try again later.';
                   2451:         }
1.364     www      2452:     } elsif (!$existing{$ckey}) {
1.345     www      2453: # the key does not exist
                   2454: 	return 'error: The key does not exist';
                   2455:     } else {
                   2456: # the key is somebody else's
                   2457: 	return 'error: The key is already in use';
                   2458:     }
1.344     www      2459: }
                   2460: 
1.364     www      2461: # ------------------------------------------ put an additional comment on a key
                   2462: 
                   2463: sub comment_access_key {
                   2464: #
                   2465: # a valid key looks like uname:udom#comments
                   2466: # comments are being appended
                   2467: #
                   2468:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2469:     $cdom=
1.620     albertel 2470:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2471:     $cnum=
1.620     albertel 2472:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2473:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2474:     if ($existing{$ckey}) {
                   2475:         $existing{$ckey}.='; '.$logentry;
                   2476: # ready to assign
1.367     www      2477:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2478:                                                  $cdom,$cnum) eq 'ok') {
                   2479: 	    return 'ok';
                   2480:         } else {
                   2481: 	    return 'error: Count not store comment.';
                   2482:         }
                   2483:     } else {
                   2484: # the key does not exist
                   2485: 	return 'error: The key does not exist';
                   2486:     }
                   2487: }
                   2488: 
1.344     www      2489: # ------------------------------------------------------ Generate a set of keys
                   2490: 
                   2491: sub generate_access_keys {
1.364     www      2492:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2493:     $cdom=
1.620     albertel 2494:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2495:     $cnum=
1.620     albertel 2496:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2497:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2498:     unless (($cdom) && ($cnum)) { return 0; }
                   2499:     if ($number>10000) { return 0; }
                   2500:     sleep(2); # make sure don't get same seed twice
                   2501:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2502:     my $total=0;
                   2503:     for (my $i=1;$i<=$number;$i++) {
                   2504:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2505:                   sprintf("%lx",int(100000*rand)).'-'.
                   2506:                   sprintf("%lx",int(100000*rand));
                   2507:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2508:        $newkey=~s/0/h/g; # and also 0 and O
                   2509:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2510:        if ($existing{$newkey}) {
                   2511:            $i--;
                   2512:        } else {
1.364     www      2513: 	  if (&put('accesskeys',
                   2514:               { $newkey => '# generated '.localtime().
1.620     albertel 2515:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2516:                            '; '.$logentry },
                   2517: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2518:               $total++;
                   2519: 	  }
                   2520:        }
                   2521:     }
1.620     albertel 2522:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2523:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2524:     return $total;
                   2525: }
                   2526: 
                   2527: # ------------------------------------------------------- Validate an accesskey
                   2528: 
                   2529: sub validate_access_key {
                   2530:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2531:     $cdom=
1.620     albertel 2532:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2533:     $cnum=
1.620     albertel 2534:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2535:     $udom=$env{'user.domain'} unless (defined($udom));
                   2536:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2537:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2538:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2539: }
                   2540: 
                   2541: # ------------------------------------- Find the section of student in a course
1.652     albertel 2542: sub devalidate_getsection_cache {
                   2543:     my ($udom,$unam,$courseid)=@_;
                   2544:     my $hashid="$udom:$unam:$courseid";
                   2545:     &devalidate_cache_new('getsection',$hashid);
                   2546: }
1.298     matthew  2547: 
1.815     albertel 2548: sub courseid_to_courseurl {
                   2549:     my ($courseid) = @_;
                   2550:     #already url style courseid
                   2551:     return $courseid if ($courseid =~ m{^/});
                   2552: 
                   2553:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2554: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2555: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2556: 	return "/$cdom/$cnum";
                   2557:     }
                   2558: 
                   2559:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2560:     if (exists($courseinfo{'num'})) {
                   2561: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2562:     }
                   2563: 
                   2564:     return undef;
                   2565: }
                   2566: 
1.298     matthew  2567: sub getsection {
                   2568:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2569:     my $cachetime=1800;
1.551     albertel 2570: 
                   2571:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2572:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2573:     if (defined($cached)) { return $result; }
                   2574: 
1.298     matthew  2575:     my %Pending; 
                   2576:     my %Expired;
                   2577:     #
                   2578:     # Each role can either have not started yet (pending), be active, 
                   2579:     #    or have expired.
                   2580:     #
                   2581:     # If there is an active role, we are done.
                   2582:     #
                   2583:     # If there is more than one role which has not started yet, 
                   2584:     #     choose the one which will start sooner
                   2585:     # If there is one role which has not started yet, return it.
                   2586:     #
                   2587:     # If there is more than one expired role, choose the one which ended last.
                   2588:     # If there is a role which has expired, return it.
                   2589:     #
1.815     albertel 2590:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2591:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2592:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2593:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2594:         my $section=$1;
                   2595:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2596:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2597:         my $now=time;
1.548     albertel 2598:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2599:             $Expired{$end}=$section;
                   2600:             next;
                   2601:         }
1.548     albertel 2602:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2603:             $Pending{$start}=$section;
                   2604:             next;
                   2605:         }
1.599     albertel 2606:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2607:     }
                   2608:     #
                   2609:     # Presumedly there will be few matching roles from the above
                   2610:     # loop and the sorting time will be negligible.
                   2611:     if (scalar(keys(%Pending))) {
                   2612:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2613:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2614:     } 
                   2615:     if (scalar(keys(%Expired))) {
                   2616:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2617:         my $time = pop(@sorted);
1.599     albertel 2618:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2619:     }
1.599     albertel 2620:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2621: }
1.70      www      2622: 
1.599     albertel 2623: sub save_cache {
                   2624:     &purge_remembered();
1.722     albertel 2625:     #&Apache::loncommon::validate_page();
1.620     albertel 2626:     undef(%env);
1.780     albertel 2627:     undef($env_loaded);
1.599     albertel 2628: }
1.452     albertel 2629: 
1.599     albertel 2630: my $to_remember=-1;
                   2631: my %remembered;
                   2632: my %accessed;
                   2633: my $kicks=0;
                   2634: my $hits=0;
1.849     albertel 2635: sub make_key {
                   2636:     my ($name,$id) = @_;
1.872     albertel 2637:     if (length($id) > 65 
                   2638: 	&& length(&escape($id)) > 200) {
                   2639: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2640:     }
1.849     albertel 2641:     return &escape($name.':'.$id);
                   2642: }
                   2643: 
1.599     albertel 2644: sub devalidate_cache_new {
                   2645:     my ($name,$id,$debug) = @_;
                   2646:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  2647:     my $remembered_id=$name.':'.$id;
1.849     albertel 2648:     $id=&make_key($name,$id);
1.599     albertel 2649:     $memcache->delete($id);
1.1319    damieng  2650:     delete($remembered{$remembered_id});
                   2651:     delete($accessed{$remembered_id});
1.599     albertel 2652: }
                   2653: 
                   2654: sub is_cached_new {
                   2655:     my ($name,$id,$debug) = @_;
1.1319    damieng  2656:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   2657:     if (exists($remembered{$remembered_id})) {
                   2658: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2659: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2660: 	$hits++;
1.1319    damieng  2661: 	return ($remembered{$remembered_id},1);
1.599     albertel 2662:     }
1.1319    damieng  2663:     $id=&make_key($name,$id);
1.599     albertel 2664:     my $value = $memcache->get($id);
                   2665:     if (!(defined($value))) {
                   2666: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2667: 	return (undef,undef);
1.416     albertel 2668:     }
1.599     albertel 2669:     if ($value eq '__undef__') {
                   2670: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2671: 	$value=undef;
                   2672:     }
1.1319    damieng  2673:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2674:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2675:     return ($value,1);
                   2676: }
                   2677: 
                   2678: sub do_cache_new {
                   2679:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  2680:     my $remembered_id=$name.':'.$id;
1.849     albertel 2681:     $id=&make_key($name,$id);
1.599     albertel 2682:     my $setvalue=$value;
                   2683:     if (!defined($setvalue)) {
                   2684: 	$setvalue='__undef__';
                   2685:     }
1.623     albertel 2686:     if (!defined($time) ) {
                   2687: 	$time=600;
                   2688:     }
1.599     albertel 2689:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2690:     my $result = $memcache->set($id,$setvalue,$time);
                   2691:     if (! $result) {
1.872     albertel 2692: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2693: 	$memcache->disconnect_all();
1.872     albertel 2694:     }
1.600     albertel 2695:     # need to make a copy of $value
1.1319    damieng  2696:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2697:     return $value;
                   2698: }
                   2699: 
                   2700: sub make_room {
1.1319    damieng  2701:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2702: 
1.1319    damieng  2703:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2704:                                     : $value;
1.599     albertel 2705:     if ($to_remember<0) { return; }
1.1319    damieng  2706:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2707:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2708:     my $to_kick;
                   2709:     my $max_time=0;
                   2710:     foreach my $other (keys(%accessed)) {
                   2711: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2712: 	    $to_kick=$other;
                   2713: 	    $max_time=&tv_interval($accessed{$other});
                   2714: 	}
                   2715:     }
                   2716:     delete($remembered{$to_kick});
                   2717:     delete($accessed{$to_kick});
                   2718:     $kicks++;
                   2719:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2720:     return;
                   2721: }
                   2722: 
1.599     albertel 2723: sub purge_remembered {
1.604     albertel 2724:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2725:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2726:     undef(%remembered);
                   2727:     undef(%accessed);
1.428     albertel 2728: }
1.70      www      2729: # ------------------------------------- Read an entry from a user's environment
                   2730: 
                   2731: sub userenvironment {
                   2732:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2733:     my $items;
                   2734:     foreach my $item (@what) {
                   2735:         $items.=&escape($item).'&';
                   2736:     }
                   2737:     $items=~s/\&$//;
1.70      www      2738:     my %returnhash=();
1.1009    raeburn  2739:     my $uhome = &homeserver($unam,$udom);
                   2740:     unless ($uhome eq 'no_host') {
                   2741:         my @answer=split(/\&/, 
                   2742:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2743:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2744:             return %returnhash;
                   2745:         }
1.1009    raeburn  2746:         my $i;
                   2747:         for ($i=0;$i<=$#what;$i++) {
                   2748: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2749:         }
1.70      www      2750:     }
                   2751:     return %returnhash;
1.1       albertel 2752: }
                   2753: 
1.617     albertel 2754: # ---------------------------------------------------------- Get a studentphoto
                   2755: sub studentphoto {
                   2756:     my ($udom,$unam,$ext) = @_;
                   2757:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2758:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2759:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2760:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2761:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2762:             } else {
                   2763:                 my ($result,$perm_reqd)=
1.707     albertel 2764: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2765:                 if ($result eq 'ok') {
                   2766:                     if (!($perm_reqd eq 'yes')) {
                   2767:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2768:                     }
                   2769:                 }
                   2770:             }
                   2771:         }
                   2772:     } else {
                   2773:         my ($result,$perm_reqd) = 
1.707     albertel 2774: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2775:         if ($result eq 'ok') {
                   2776:             if (!($perm_reqd eq 'yes')) {
                   2777:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2778:             }
                   2779:         }
                   2780:     }
                   2781:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2782: }
                   2783: 
                   2784: sub retrievestudentphoto {
                   2785:     my ($udom,$unam,$ext,$type) = @_;
                   2786:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2787:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2788:     if ($ret eq 'ok') {
                   2789:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2790:         if ($type eq 'thumbnail') {
                   2791:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2792:         }
                   2793:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2794:         return $tokenurl;
                   2795:     } else {
                   2796:         if ($type eq 'thumbnail') {
                   2797:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2798:         } else { 
                   2799:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2800:         }
1.617     albertel 2801:     }
                   2802: }
                   2803: 
1.263     www      2804: # -------------------------------------------------------------------- New chat
                   2805: 
                   2806: sub chatsend {
1.724     raeburn  2807:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2808:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2809:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2810:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2811:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2812: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2813: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2814: }
                   2815: 
                   2816: # ------------------------------------------ Find current version of a resource
                   2817: 
                   2818: sub getversion {
                   2819:     my $fname=&clutter(shift);
1.1189    raeburn  2820:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2821:     return &currentversion(&filelocation('',$fname));
                   2822: }
                   2823: 
                   2824: sub currentversion {
                   2825:     my $fname=shift;
                   2826:     my $author=$fname;
                   2827:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2828:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2829:     my $home=&homeserver($uname,$udom);
1.292     www      2830:     if ($home eq 'no_host') { 
                   2831:         return -1; 
                   2832:     }
1.1112    www      2833:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2834:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2835: 	return -1;
                   2836:     }
1.1112    www      2837:     return $answer;
1.263     www      2838: }
                   2839: 
1.1111    www      2840: #
                   2841: # Return special version number of resource if set by override, empty otherwise
                   2842: #
                   2843: sub usedversion {
                   2844:     my $fname=shift;
                   2845:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2846:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2847:     if ($urlversion) { return $urlversion; }
                   2848:     return '';
                   2849: }
                   2850: 
1.1       albertel 2851: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2852: 
1.1       albertel 2853: sub subscribe {
                   2854:     my $fname=shift;
1.761     raeburn  2855:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2856:     $fname=~s/[\n\r]//g;
1.1       albertel 2857:     my $author=$fname;
                   2858:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2859:     my ($udom,$uname)=split(/\//,$author);
                   2860:     my $home=homeserver($uname,$udom);
1.335     albertel 2861:     if ($home eq 'no_host') {
                   2862:         return 'not_found';
1.1       albertel 2863:     }
                   2864:     my $answer=reply("sub:$fname",$home);
1.64      www      2865:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2866: 	$answer.=' by '.$home;
                   2867:     }
1.1       albertel 2868:     return $answer;
                   2869: }
                   2870:     
1.8       www      2871: # -------------------------------------------------------------- Replicate file
                   2872: 
                   2873: sub repcopy {
                   2874:     my $filename=shift;
1.23      www      2875:     $filename=~s/\/+/\//g;
1.1142    raeburn  2876:     my $londocroot = $perlvar{'lonDocRoot'};
                   2877:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2878:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2879:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2880: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2881: 	return &repcopy_userfile($filename);
                   2882:     }
1.532     albertel 2883:     $filename=~s/[\n\r]//g;
1.8       www      2884:     my $transname="$filename.in.transfer";
1.828     www      2885: # FIXME: this should flock
1.607     raeburn  2886:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2887:     my $remoteurl=subscribe($filename);
1.64      www      2888:     if ($remoteurl =~ /^con_lost by/) {
                   2889: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2890:            return 'unavailable';
1.8       www      2891:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2892: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2893: 	   return 'not_found';
1.64      www      2894:     } elsif ($remoteurl =~ /^rejected by/) {
                   2895: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2896:            return 'forbidden';
1.20      www      2897:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2898:            return 'ok';
1.8       www      2899:     } else {
1.290     www      2900:         my $author=$filename;
                   2901:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2902:         my ($udom,$uname)=split(/\//,$author);
                   2903:         my $home=homeserver($uname,$udom);
                   2904:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2905:            my @parts=split(/\//,$filename);
                   2906:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2907:            if ($path ne "$londocroot/res") {
1.8       www      2908:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2909: 	       return 'bad_request';
1.8       www      2910:            }
                   2911:            my $count;
                   2912:            for ($count=5;$count<$#parts;$count++) {
                   2913:                $path.="/$parts[$count]";
                   2914:                if ((-e $path)!=1) {
                   2915: 		   mkdir($path,0777);
                   2916:                }
                   2917:            }
                   2918:            my $ua=new LWP::UserAgent;
                   2919:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2920:            my $response=$ua->request($request,$transname);
                   2921:            if ($response->is_error()) {
                   2922: 	       unlink($transname);
                   2923:                my $message=$response->status_line;
1.672     albertel 2924:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2925:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2926:                return 'unavailable';
1.8       www      2927:            } else {
1.16      www      2928: 	       if ($remoteurl!~/\.meta$/) {
                   2929:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2930:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2931:                   if ($mresponse->is_error()) {
                   2932: 		      unlink($filename.'.meta');
                   2933:                       &logthis(
1.672     albertel 2934:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2935:                   }
                   2936: 	       }
1.8       www      2937:                rename($transname,$filename);
1.607     raeburn  2938:                return 'ok';
1.8       www      2939:            }
1.290     www      2940:        }
1.8       www      2941:     }
1.330     www      2942: }
                   2943: 
                   2944: # ------------------------------------------------ Get server side include body
                   2945: sub ssi_body {
1.381     albertel 2946:     my ($filelink,%form)=@_;
1.606     matthew  2947:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2948:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2949:     }
1.953     www      2950:     my $output='';
                   2951:     my $response;
1.980     raeburn  2952:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2953:        ($output,$response)=&externalssi($filelink);
1.953     www      2954:     } else {
1.1004    droeschl 2955:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2956:        $filelink .= 'inhibitmenu=yes';
1.953     www      2957:        ($output,$response)=&ssi($filelink,%form);
                   2958:     }
1.778     albertel 2959:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2960:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2961:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2962:     if (wantarray) {
                   2963:         return ($output, $response);
                   2964:     } else {
                   2965:         return $output;
                   2966:     }
1.8       www      2967: }
                   2968: 
1.15      www      2969: # --------------------------------------------------------- Server Side Include
                   2970: 
1.782     albertel 2971: sub absolute_url {
                   2972:     my ($host_name) = @_;
                   2973:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2974:     if ($host_name eq '') {
                   2975: 	$host_name = $ENV{'SERVER_NAME'};
                   2976:     }
                   2977:     return $protocol.$host_name;
                   2978: }
                   2979: 
1.942     foxr     2980: #
                   2981: #   Server side include.
                   2982: # Parameters:
                   2983: #  fn     Possibly encrypted resource name/id.
                   2984: #  form   Hash that describes how the rendering should be done
                   2985: #         and other things.
1.944     foxr     2986: # Returns:
1.950     raeburn  2987: #   Scalar context: The content of the response.
                   2988: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2989: #     
1.15      www      2990: sub ssi {
                   2991: 
1.944     foxr     2992:     my ($fn,%form)=@_;
1.15      www      2993:     my $ua=new LWP::UserAgent;
1.23      www      2994:     my $request;
1.711     albertel 2995: 
                   2996:     $form{'no_update_last_known'}=1;
1.895     albertel 2997:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2998:     if (%form) {
1.782     albertel 2999:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 3000:       $request->content(join('&',map { 
                   3001:             my $name = escape($_);
                   3002:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3003:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3004:             : &escape($form{$_}) );    
                   3005:         } keys(%form)));
1.23      www      3006:     } else {
1.782     albertel 3007:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3008:     }
                   3009: 
1.15      www      3010:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173    foxr     3011:     my $response= $ua->request($request);
1.1182    foxr     3012:     my $content = $response->content;
                   3013: 
                   3014: 
1.944     foxr     3015:     if (wantarray) {
1.1173    foxr     3016: 	return ($content, $response);
1.944     foxr     3017:     } else {
1.1173    foxr     3018: 	return $content;
1.942     foxr     3019:     }
1.324     www      3020: }
                   3021: 
                   3022: sub externalssi {
                   3023:     my ($url)=@_;
                   3024:     my $ua=new LWP::UserAgent;
                   3025:     my $request=new HTTP::Request('GET',$url);
                   3026:     my $response=$ua->request($request);
1.954     raeburn  3027:     if (wantarray) {
                   3028:         return ($response->content, $response);
                   3029:     } else {
                   3030:         return $response->content;
                   3031:     }
1.15      www      3032: }
1.254     www      3033: 
1.492     albertel 3034: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3035: 
                   3036: sub allowuploaded {
                   3037:     my ($srcurl,$url)=@_;
                   3038:     $url=&clutter(&declutter($url));
                   3039:     my $dir=$url;
                   3040:     $dir=~s/\/[^\/]+$//;
                   3041:     my %httpref=();
                   3042:     my $httpurl=&hreflocation('',$url);
                   3043:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3044:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3045: }
1.477     raeburn  3046: 
1.1193    raeburn  3047: #
                   3048: # Determine if the current user should be able to edit a particular resource,
                   3049: # when viewing in course context.
                   3050: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3051: #     Functions.
                   3052: # (b) When displaying folder contents in course editor, used to determine if
                   3053: #     "Edit" link will be displayed alongside resource.
                   3054: #
1.1196    raeburn  3055: #  input: six args -- filename (decluttered), course number, course domain,
                   3056: #                   url, symb (if registered) and group (if this is a group
                   3057: #                   item -- e.g., bulletin board, group page etc.).
                   3058: #  output: array of five scalars -- 
1.1193    raeburn  3059: #          $cfile -- url for file editing if editable on current server
                   3060: #          $home -- homeserver of resource (i.e., for author if published,
                   3061: #                                           or course if uploaded.).
                   3062: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3063: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3064: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3065: #
                   3066: 
                   3067: sub can_edit_resource {
1.1194    raeburn  3068:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3069:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3070: #
                   3071: # For aboutme pages user can only edit his/her own.
                   3072: #
1.1199    raeburn  3073:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3074:         my ($sdom,$sname) = ($1,$2);
                   3075:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3076:             $home = $env{'user.home'};
                   3077:             $cfile = $resurl;
                   3078:             if ($env{'form.forceedit'}) {
                   3079:                 $forceview = 1;
                   3080:             } else {
                   3081:                 $forceedit = 1;
                   3082:             }
                   3083:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3084:         } else {
                   3085:             return;
                   3086:         }
                   3087:     }
                   3088: 
                   3089:     if ($env{'request.course.id'}) {
                   3090:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3091:         if ($group ne '') {
                   3092: # if this is a group homepage or group bulletin board, check group privs
                   3093:             my $allowed = 0;
1.1197    raeburn  3094:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3095:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3096:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3097:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3098:                     $allowed = 1;
                   3099:                 }
1.1197    raeburn  3100:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3101:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3102:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3103:                     $allowed = 1;
                   3104:                 }
                   3105:             }
                   3106:             if ($allowed) {
                   3107:                 $home=&homeserver($cnum,$cdom);
                   3108:                 if ($env{'form.forceedit'}) {
                   3109:                     $forceview = 1;
                   3110:                 } else {
                   3111:                     $forceedit = 1;
                   3112:                 }
                   3113:                 $cfile = $resurl;
                   3114:             } else {
                   3115:                 return;
                   3116:             }
                   3117:         } else {
1.1208    raeburn  3118:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3119:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3120:                     return;
                   3121:                 }
                   3122:             } elsif (!$crsedit) {
1.1194    raeburn  3123: #
                   3124: # No edit allowed where CC has switched to student role.
                   3125: #
                   3126:                 return;
                   3127:             }
                   3128:         }
                   3129:     }
                   3130: 
1.1193    raeburn  3131:     if ($file ne '') {
                   3132:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3133:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3134:                 $uploaded = 1;
                   3135:                 $incourse = 1;
1.1193    raeburn  3136:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3137:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3138:                     if ($env{'form.forceedit'}) {
                   3139:                         $forceview = 1;
                   3140:                     } else {
                   3141:                         $forceedit = 1;
                   3142:                     }
1.1194    raeburn  3143:                 }
                   3144:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3145:                 $incourse = 1;
                   3146:                 if ($env{'form.forceedit'}) {
                   3147:                     $forceview = 1;
                   3148:                 } else {
                   3149:                     $forceedit = 1;
                   3150:                 }
                   3151:                 $cfile = $resurl;
                   3152:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3153:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3154:                     $incourse = 1;
                   3155:                     if ($env{'form.forceedit'}) {
                   3156:                         $forceview = 1;
                   3157:                     } else {
                   3158:                         $forceedit = 1;
                   3159:                     }
                   3160:                     $cfile = $resurl;
1.1199    raeburn  3161:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3162:                     $incourse = 1;
                   3163:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3164:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3165:                     $incourse = 1;
1.1199    raeburn  3166:                     if ($env{'form.forceedit'}) {
                   3167:                         $forceview = 1;
                   3168:                     } else {
                   3169:                         $forceedit = 1;
                   3170:                     }
                   3171:                     $cfile = $resurl;
1.1298    raeburn  3172:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) {
                   3173:                     $incourse = 1;
                   3174:                     if ($env{'form.forceedit'}) {
                   3175:                         $forceview = 1;
                   3176:                     } else {
                   3177:                         $forceedit = 1;
                   3178:                     }
                   3179:                     $cfile = $resurl;
1.1208    raeburn  3180:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3181:                     $incourse = 1;
                   3182:                     if ($env{'form.forceedit'}) {
                   3183:                         $forceview = 1;
                   3184:                     } else {
                   3185:                         $forceedit = 1;
                   3186:                     }
                   3187:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3188:                 }
                   3189:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3190:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3191:                 if (&is_on_map($template)) { 
                   3192:                     $incourse = 1;
                   3193:                     $forceview = 1;
                   3194:                     $cfile = $template;
1.1193    raeburn  3195:                 }
1.1199    raeburn  3196:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3197:                     $incourse = 1;
                   3198:                     if ($env{'form.forceedit'}) {
                   3199:                         $forceview = 1;
                   3200:                     } else {
                   3201:                         $forceedit = 1;
                   3202:                     }
                   3203:                     $cfile = $resurl;
1.1298    raeburn  3204:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3205:                 $incourse = 1;
                   3206:                 if ($env{'form.forceedit'}) {
                   3207:                     $forceview = 1;
                   3208:                 } else {
                   3209:                     $forceedit = 1;
                   3210:                 }
                   3211:                 $cfile = $resurl;
1.1199    raeburn  3212:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3213:                 $incourse = 1;
                   3214:                 $forceview = 1;
                   3215:                 if ($symb) {
                   3216:                     my ($map,$id,$res)=&decode_symb($symb);
                   3217:                     $env{'request.symb'} = $symb;
                   3218:                     $cfile = &clutter($res);
                   3219:                 } else {
                   3220:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3221:                     my $escfile = &unescape($cfile);
                   3222:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/exttools?$}) {
                   3223:                         $cfile = '/adm/wrapper'.$escfile;
                   3224:                     } else {
                   3225:                         $escfile =~ s{^http://}{};
                   3226:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3227:                     }
1.1199    raeburn  3228:                 }
1.1234    raeburn  3229:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3230:                 if ($env{'form.forceedit'}) {
                   3231:                     $forceview = 1;
                   3232:                 } else {
                   3233:                     $forceedit = 1;
                   3234:                 }
                   3235:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3236:             }
                   3237:         }
1.1194    raeburn  3238:         if ($uploaded || $incourse) {
                   3239:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3240:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3241:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3242:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3243:             # Check that the user has permission to edit this resource
                   3244:             my $setpriv = 1;
                   3245:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3246:             if (defined($cfudom)) {
                   3247:                 $home=&homeserver($cfuname,$cfudom);
                   3248:                 $cfile=$file;
                   3249:             }
                   3250:         }
1.1194    raeburn  3251:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3252:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3253:             my @ids=&current_machine_ids();
                   3254:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3255:                 $switchserver=1;
                   3256:             }
                   3257:         }
                   3258:     }
1.1194    raeburn  3259:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3260: }
                   3261: 
                   3262: sub is_course_upload {
                   3263:     my ($file,$cnum,$cdom) = @_;
                   3264:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3265:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3266:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3267:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3268:         return 1;
                   3269:     }
                   3270:     return;
                   3271: }
                   3272: 
1.1194    raeburn  3273: sub in_course {
1.1195    raeburn  3274:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3275:     if ($hideprivileged) {
                   3276:         my $skipuser;
1.1219    raeburn  3277:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3278:         my @possdoms = ($cdom);  
                   3279:         if ($coursehash{'checkforpriv'}) { 
                   3280:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3281:         }
                   3282:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3283:             $skipuser = 1;
                   3284:             if ($coursehash{'nothideprivileged'}) {
                   3285:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3286:                     my $user;
                   3287:                     if ($item =~ /:/) {
                   3288:                         $user = $item;
                   3289:                     } else {
                   3290:                         $user = join(':',split(/[\@]/,$item));
                   3291:                     }
                   3292:                     if ($user eq $uname.':'.$udom) {
                   3293:                         undef($skipuser);
                   3294:                         last;
                   3295:                     }
                   3296:                 }
                   3297:             }
                   3298:             if ($skipuser) {
                   3299:                 return 0;
                   3300:             }
                   3301:         }
                   3302:     }
1.1194    raeburn  3303:     $type ||= 'any';
                   3304:     if (!defined($cdom) || !defined($cnum)) {
                   3305:         my $cid  = $env{'request.course.id'};
                   3306:         $cdom = $env{'course.'.$cid.'.domain'};
                   3307:         $cnum = $env{'course.'.$cid.'.num'};
                   3308:     }
                   3309:     my $typesref;
1.1195    raeburn  3310:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3311:         $typesref = ['active','previous','future'];
                   3312:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3313:         $typesref = [$type];
                   3314:     }
                   3315:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3316:                               $typesref,undef,[$cdom]);
                   3317:     my ($tmp) = keys(%roles);
                   3318:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3319:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3320:     if (@course_roles > 0) {
                   3321:         return 1;
                   3322:     }
                   3323:     return 0;
                   3324: }
                   3325: 
1.478     albertel 3326: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3327: # input: action, courseID, current domain, intended
1.637     raeburn  3328: #        path to file, source of file, instruction to parse file for objects,
                   3329: #        ref to hash for embedded objects,
                   3330: #        ref to hash for codebase of java objects.
1.1095    raeburn  3331: #        reference to scalar to accommodate mime type determined
                   3332: #          from File::MMagic if $parser = parse.
1.637     raeburn  3333: #
1.485     raeburn  3334: # output: url to file (if action was uploaddoc), 
                   3335: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3336: #
1.478     albertel 3337: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3338: # course.
1.477     raeburn  3339: #
1.478     albertel 3340: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3341: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3342: #          course's home server.
1.477     raeburn  3343: #
1.478     albertel 3344: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3345: #          be copied from $source (current location) to 
                   3346: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3347: #         and will then be copied to
                   3348: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3349: #         course's home server.
1.485     raeburn  3350: #
1.481     raeburn  3351: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3352: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3353: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3354: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3355: #         in course's home server.
1.637     raeburn  3356: #
1.477     raeburn  3357: 
                   3358: sub process_coursefile {
1.1095    raeburn  3359:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3360:         $mimetype)=@_;
1.477     raeburn  3361:     my $fetchresult;
1.638     albertel 3362:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3363:     if ($action eq 'propagate') {
1.638     albertel 3364:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3365: 			     $home);
1.481     raeburn  3366:     } else {
1.477     raeburn  3367:         my $fpath = '';
                   3368:         my $fname = $file;
1.478     albertel 3369:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3370:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3371:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3372:         if ($action eq 'copy') {
                   3373:             if ($source eq '') {
                   3374:                 $fetchresult = 'no source file';
                   3375:                 return $fetchresult;
                   3376:             } else {
                   3377:                 my $destination = $filepath.'/'.$fname;
                   3378:                 rename($source,$destination);
                   3379:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3380:                                  $home);
1.481     raeburn  3381:             }
                   3382:         } elsif ($action eq 'uploaddoc') {
                   3383:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3384:             print $fh $env{'form.'.$source};
1.481     raeburn  3385:             close($fh);
1.637     raeburn  3386:             if ($parser eq 'parse') {
1.1024    raeburn  3387:                 my $mm = new File::MMagic;
1.1095    raeburn  3388:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3389:                 if ($type eq 'text/html') {
1.1024    raeburn  3390:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3391:                     unless ($parse_result eq 'ok') {
                   3392:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3393:                     }
1.637     raeburn  3394:                 }
1.1095    raeburn  3395:                 if (ref($mimetype)) {
                   3396:                     $$mimetype = $type;
                   3397:                 } 
1.637     raeburn  3398:             }
1.477     raeburn  3399:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3400:                                  $home);
1.481     raeburn  3401:             if ($fetchresult eq 'ok') {
                   3402:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3403:             } else {
                   3404:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3405:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3406:                 return '/adm/notfound.html';
                   3407:             }
1.477     raeburn  3408:         }
                   3409:     }
1.485     raeburn  3410:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3411:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3412:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3413:     }
                   3414:     return $fetchresult;
                   3415: }
                   3416: 
1.637     raeburn  3417: sub build_filepath {
                   3418:     my ($fpath) = @_;
                   3419:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3420:     unless ($fpath eq '') {
                   3421:         my @parts=split('/',$fpath);
                   3422:         foreach my $part (@parts) {
                   3423:             $filepath.= '/'.$part;
                   3424:             if ((-e $filepath)!=1) {
                   3425:                 mkdir($filepath,0777);
                   3426:             }
                   3427:         }
                   3428:     }
                   3429:     return $filepath;
                   3430: }
                   3431: 
                   3432: sub store_edited_file {
1.638     albertel 3433:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3434:     my $file = $primary_url;
                   3435:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3436:     my $fpath = '';
                   3437:     my $fname = $file;
                   3438:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3439:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3440:     my $filepath = &build_filepath($fpath);
                   3441:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3442:     print $fh $content;
                   3443:     close($fh);
1.638     albertel 3444:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3445:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3446: 			  $home);
1.637     raeburn  3447:     if ($$fetchresult eq 'ok') {
                   3448:         return '/uploaded/'.$fpath.'/'.$fname;
                   3449:     } else {
1.638     albertel 3450:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3451: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3452:         return '/adm/notfound.html';
                   3453:     }
                   3454: }
                   3455: 
1.531     albertel 3456: sub clean_filename {
1.831     albertel 3457:     my ($fname,$args)=@_;
1.315     www      3458: # Replace Windows backslashes by forward slashes
1.257     www      3459:     $fname=~s/\\/\//g;
1.831     albertel 3460:     if (!$args->{'keep_path'}) {
                   3461:         # Get rid of everything but the actual filename
                   3462: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3463:     }
1.315     www      3464: # Replace spaces by underscores
                   3465:     $fname=~s/\s+/\_/g;
                   3466: # Replace all other weird characters by nothing
1.831     albertel 3467:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3468: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3469: # numbers
                   3470:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3471:     return $fname;
                   3472: }
1.1051    raeburn  3473: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3474: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3475: # image with the same aspect ratio as the original, but with dimensions which do 
                   3476: # not exceed $resizewidth and $resizeheight.
                   3477:  
1.984     neumanie 3478: sub resizeImage {
1.1051    raeburn  3479:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3480:     my $ima = Image::Magick->new;
                   3481:     my $resized;
                   3482:     if (-e $img_path) {
                   3483:         $ima->Read($img_path);
                   3484:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3485:             my $width = $ima->Get('width');
                   3486:             my $height = $ima->Get('height');
                   3487:             if ($width > $resizewidth) {
                   3488: 	        my $factor = $width/$resizewidth;
                   3489:                 my $newheight = $height/$factor;
                   3490:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3491:                 $resized = 1;
                   3492:             }
                   3493:         }
                   3494:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3495:             my $width = $ima->Get('width');
                   3496:             my $height = $ima->Get('height');
                   3497:             if ($height > $resizeheight) {
                   3498:                 my $factor = $height/$resizeheight;
                   3499:                 my $newwidth = $width/$factor;
                   3500:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3501:                 $resized = 1;
                   3502:             }
                   3503:         }
                   3504:         if ($resized) {
                   3505:             $ima->Write($img_path);
                   3506:         }
                   3507:     }
                   3508:     return;
1.977     amueller 3509: }
                   3510: 
1.608     albertel 3511: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3512: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3513: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3514: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3515: #                                    canceloverwrite, or ''. 
                   3516: #                   if 'coursedoc': upload to the current course
                   3517: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3518: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3519: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3520: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3521: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3522: #        $allfiles - reference to hash for embedded objects
                   3523: #        $codebase - reference to hash for codebase of java objects
                   3524: #        $desuname - username for permanent storage of uploaded file
                   3525: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3526: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3527: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3528: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3529: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3530: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3531: #                    from File::MMagic.
1.858     raeburn  3532: # 
1.686     albertel 3533: # output: url of file in userspace, or error: <message> 
                   3534: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3535: 
1.531     albertel 3536: sub userfileupload {
1.1090    raeburn  3537:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3538:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3539:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3540:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3541:     $fname=&clean_filename($fname);
1.1090    raeburn  3542:     # See if there is anything left
1.257     www      3543:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3544:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3545:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3546:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3547:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3548:         my $now = time;
1.1090    raeburn  3549:         my $filepath;
1.1095    raeburn  3550:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3551:              $filepath = 'tmp/helprequests/'.$now;
                   3552:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3553:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3554:                          '_'.$env{'user.domain'}.'/pending';
                   3555:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3556:             my ($docuname,$docudom);
                   3557:             if ($destudom) {
                   3558:                 $docudom = $destudom;
                   3559:             } else {
                   3560:                 $docudom = $env{'user.domain'};
                   3561:             }
                   3562:             if ($destuname) {
                   3563:                 $docuname = $destuname;
                   3564:             } else {
                   3565:                 $docuname = $env{'user.name'};
                   3566:             }
                   3567:             if (exists($env{'form.group'})) {
                   3568:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3569:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3570:             }
                   3571:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3572:             if ($context eq 'canceloverwrite') {
                   3573:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3574:                 if (-e  $tempfile) {
                   3575:                     my @info = stat($tempfile);
                   3576:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3577:                         unlink($tempfile);
                   3578:                     }
                   3579:                 }
                   3580:                 return;
1.523     raeburn  3581:             }
                   3582:         }
1.1090    raeburn  3583:         # Create the directory if not present
1.741     raeburn  3584:         my @parts=split(/\//,$filepath);
                   3585:         my $fullpath = $perlvar{'lonDaemons'};
                   3586:         for (my $i=0;$i<@parts;$i++) {
                   3587:             $fullpath .= '/'.$parts[$i];
                   3588:             if ((-e $fullpath)!=1) {
                   3589:                 mkdir($fullpath,0777);
                   3590:             }
                   3591:         }
                   3592:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3593:         print $fh $env{'form.'.$formname};
                   3594:         close($fh);
1.1090    raeburn  3595:         if ($context eq 'existingfile') {
                   3596:             my @info = stat($fullpath.'/'.$fname);
                   3597:             return ($fullpath.'/'.$fname,$info[9]);
                   3598:         } else {
                   3599:             return $fullpath.'/'.$fname;
                   3600:         }
1.523     raeburn  3601:     }
1.995     raeburn  3602:     if ($subdir eq 'scantron') {
                   3603:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3604:     } else {
1.995     raeburn  3605:         $fname="$subdir/$fname";
                   3606:     }
1.1090    raeburn  3607:     if ($context eq 'coursedoc') {
1.638     albertel 3608: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3609: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3610:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3611:             return &finishuserfileupload($docuname,$docudom,
                   3612: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3613: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3614:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3615:         } else {
1.1218    raeburn  3616:             if ($env{'form.folder'}) {
                   3617:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3618:             }
1.638     albertel 3619:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3620: 				       $fname,$formname,$parser,
1.1095    raeburn  3621: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3622:         }
1.719     banghart 3623:     } elsif (defined($destuname)) {
                   3624:         my $docuname=$destuname;
                   3625:         my $docudom=$destudom;
1.860     raeburn  3626: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3627: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3628:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3629:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3630:     } else {
1.638     albertel 3631:         my $docuname=$env{'user.name'};
                   3632:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3633:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3634:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3635:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3636:         }
1.860     raeburn  3637: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3638: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3639:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3640:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3641:     }
1.271     www      3642: }
                   3643: 
                   3644: sub finishuserfileupload {
1.860     raeburn  3645:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3646:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3647:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3648:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3649:   
1.860     raeburn  3650:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3651:     $file=$fname;
                   3652:     if ($fname=~m|/|) {
                   3653:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3654: 	$path.=$fnamepath.'/';
                   3655:     }
1.259     www      3656:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3657:     my $count;
                   3658:     for ($count=4;$count<=$#parts;$count++) {
                   3659:         $filepath.="/$parts[$count]";
                   3660:         if ((-e $filepath)!=1) {
                   3661: 	    mkdir($filepath,0777);
                   3662:         }
                   3663:     }
1.984     neumanie 3664: 
1.258     www      3665: # Save the file
                   3666:     {
1.701     albertel 3667: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3668: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3669: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3670: 	    return '/adm/notfound.html';
                   3671: 	}
1.1090    raeburn  3672:         if ($context eq 'overwrite') {
1.1117    foxr     3673:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3674:             my $target = $filepath.'/'.$file;
                   3675:             if (-e $source) {
                   3676:                 my @info = stat($source);
                   3677:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3678:                     unless (&File::Copy::move($source,$target)) {
                   3679:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3680:                         return "Moving from $source failed";
                   3681:                     }
                   3682:                 } else {
                   3683:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3684:                 }
                   3685:             } else {
                   3686:                 return "Temporary file: $source missing";
                   3687:             }
                   3688:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3689: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3690: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3691: 	    return '/adm/notfound.html';
                   3692: 	}
1.570     albertel 3693: 	close(FH);
1.1051    raeburn  3694:         if ($resizewidth && $resizeheight) {
                   3695:             my $mm = new File::MMagic;
                   3696:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3697:             if ($mime_type =~ m{^image/}) {
                   3698: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3699:             }  
1.977     amueller 3700: 	}
1.258     www      3701:     }
1.1152    raeburn  3702:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3703:         if (ref($mimetype)) {
                   3704:             if ($$mimetype eq '') {
                   3705:                 my $mm = new File::MMagic;
                   3706:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3707:                 $$mimetype = $type;
                   3708:             }
                   3709:         }
                   3710:     }
1.637     raeburn  3711:     if ($parser eq 'parse') {
1.1152    raeburn  3712:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3713:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3714:                                                        $allfiles,$codebase);
                   3715:             unless ($parse_result eq 'ok') {
                   3716:                 &logthis('Failed to parse '.$filepath.$file.
                   3717: 	   	         ' for embedded media: '.$parse_result); 
                   3718:             }
1.637     raeburn  3719:         }
                   3720:     }
1.860     raeburn  3721:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3722:         my $input = $filepath.'/'.$file;
                   3723:         my $output = $filepath.'/'.'tn-'.$file;
                   3724:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3725:         system("convert -sample $thumbsize $input $output");
                   3726:         if (-e $filepath.'/'.'tn-'.$file) {
                   3727:             $fetchthumb  = 1; 
                   3728:         }
                   3729:     }
1.858     raeburn  3730:  
1.259     www      3731: # Notify homeserver to grep it
                   3732: #
1.984     neumanie 3733:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3734:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3735:     if ($fetchresult eq 'ok') {
1.860     raeburn  3736:         if ($fetchthumb) {
                   3737:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3738:             if ($thumbresult ne 'ok') {
                   3739:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3740:                          $docuhome.': '.$thumbresult);
                   3741:             }
                   3742:         }
1.259     www      3743: #
1.258     www      3744: # Return the URL to it
1.494     albertel 3745:         return '/uploaded/'.$path.$file;
1.263     www      3746:     } else {
1.494     albertel 3747:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3748: 		 ': '.$fetchresult);
1.263     www      3749:         return '/adm/notfound.html';
1.858     raeburn  3750:     }
1.493     albertel 3751: }
                   3752: 
1.637     raeburn  3753: sub extract_embedded_items {
1.961     raeburn  3754:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3755:     my @state = ();
1.1164    raeburn  3756:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3757:     my %javafiles = (
                   3758:                       codebase => '',
                   3759:                       code => '',
                   3760:                       archive => ''
                   3761:                     );
                   3762:     my %mediafiles = (
                   3763:                       src => '',
                   3764:                       movie => '',
                   3765:                      );
1.648     raeburn  3766:     my $p;
                   3767:     if ($content) {
                   3768:         $p = HTML::LCParser->new($content);
                   3769:     } else {
1.961     raeburn  3770:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3771:     }
1.641     albertel 3772:     while (my $t=$p->get_token()) {
1.640     albertel 3773: 	if ($t->[0] eq 'S') {
                   3774: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3775: 	    push(@state, $tagname);
1.648     raeburn  3776:             if (lc($tagname) eq 'allow') {
                   3777:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3778:             }
1.640     albertel 3779: 	    if (lc($tagname) eq 'img') {
                   3780: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3781: 	    }
1.886     albertel 3782: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  3783:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  3784:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3785:                 }
1.886     albertel 3786: 	    }
1.645     raeburn  3787:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3788:                 my $src;
1.645     raeburn  3789:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3790:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3791:                 } else {
1.1164    raeburn  3792:                     if ($attr->{'src'} ne '') {
                   3793:                         $src = $attr->{'src'};
                   3794:                         &add_filetype($allfiles,$src,'src');
                   3795:                     }
                   3796:                 }
                   3797:                 my $text = $p->get_trimmed_text();
                   3798:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3799:                     my @swfargs = split(/,/,$1);
                   3800:                     foreach my $item (@swfargs) {
                   3801:                         $item =~ s/["']//g;
                   3802:                         $item =~ s/^\s+//;
                   3803:                         $item =~ s/\s+$//;
                   3804:                     }
                   3805:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3806:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3807:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3808:                         } else {
                   3809:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3810:                         }
                   3811:                     }
1.645     raeburn  3812:                 }
                   3813:             }
                   3814:             if (lc($tagname) eq 'link') {
                   3815:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3816:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3817:                 }
                   3818:             }
1.640     albertel 3819: 	    if (lc($tagname) eq 'object' ||
                   3820: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3821: 		foreach my $item (keys(%javafiles)) {
                   3822: 		    $javafiles{$item} = '';
                   3823: 		}
1.1164    raeburn  3824:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3825:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3826:                 }
1.640     albertel 3827: 	    }
                   3828: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3829: 		my $name = lc($attr->{'name'});
                   3830: 		foreach my $item (keys(%javafiles)) {
                   3831: 		    if ($name eq $item) {
                   3832: 			$javafiles{$item} = $attr->{'value'};
                   3833: 			last;
                   3834: 		    }
                   3835: 		}
1.1164    raeburn  3836:                 my $pathfrom;
1.640     albertel 3837: 		foreach my $item (keys(%mediafiles)) {
                   3838: 		    if ($name eq $item) {
1.1164    raeburn  3839:                         $pathfrom = $attr->{'value'};
                   3840:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3841: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3842: 			last;
                   3843: 		    }
                   3844: 		}
1.1164    raeburn  3845:                 if ($name eq 'flashvars') {
                   3846:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3847:                 }
                   3848:                 if ($pathfrom ne '') {
                   3849:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3850:                                          $pathfrom);
                   3851:                 }
1.640     albertel 3852: 	    }
                   3853: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3854: 		foreach my $item (keys(%javafiles)) {
                   3855: 		    if ($attr->{$item}) {
                   3856: 			$javafiles{$item} = $attr->{$item};
                   3857: 			last;
                   3858: 		    }
                   3859: 		}
                   3860: 		foreach my $item (keys(%mediafiles)) {
                   3861: 		    if ($attr->{$item}) {
                   3862: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3863: 			last;
                   3864: 		    }
                   3865: 		}
1.1164    raeburn  3866:                 if (lc($tagname) eq 'embed') {
                   3867:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3868:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3869:                                              $attr->{'src'});
                   3870:                     }
                   3871:                 }
1.640     albertel 3872: 	    }
1.1243    raeburn  3873:             if (lc($tagname) eq 'iframe') {
                   3874:                 my $src = $attr->{'src'} ;
                   3875:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3876:                     &add_filetype($allfiles,$src,'src');
                   3877:                 } elsif ($src =~ m{^/}) {
                   3878:                     if ($env{'request.course.id'}) {
                   3879:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3880:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3881:                         my $url = &hreflocation('',$fullpath);
                   3882:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3883:                             my $relpath = $1;
                   3884:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3885:                                 &add_filetype($allfiles,$1,'src');
                   3886:                             }
                   3887:                         }
                   3888:                     }
                   3889:                 }
                   3890:             }
1.1164    raeburn  3891:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  3892:                 pop(@state);
1.1164    raeburn  3893:             }
1.640     albertel 3894: 	} elsif ($t->[0] eq 'E') {
                   3895: 	    my ($tagname) = ($t->[1]);
                   3896: 	    if ($javafiles{'codebase'} ne '') {
                   3897: 		$javafiles{'codebase'} .= '/';
                   3898: 	    }  
                   3899: 	    if (lc($tagname) eq 'applet' ||
                   3900: 		lc($tagname) eq 'object' ||
                   3901: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3902: 		) {
                   3903: 		foreach my $item (keys(%javafiles)) {
                   3904: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3905: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3906: 			&add_filetype($allfiles,$file,$item);
                   3907: 		    }
                   3908: 		}
                   3909: 	    } 
                   3910: 	    pop @state;
                   3911: 	}
                   3912:     }
1.1164    raeburn  3913:     foreach my $id (sort(keys(%flashvars))) {
                   3914:         if ($shockwave{$id} ne '') {
                   3915:             my @pairs = split(/\&/,$flashvars{$id});
                   3916:             foreach my $pair (@pairs) {
                   3917:                 my ($key,$value) = split(/\=/,$pair);
                   3918:                 if ($key eq 'thumb') {
                   3919:                     &add_filetype($allfiles,$value,$key);
                   3920:                 } elsif ($key eq 'content') {
                   3921:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3922:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3923:                     if ($ext ne '') {
                   3924:                         &add_filetype($allfiles,$path.$value,$ext);
                   3925:                     }
                   3926:                 }
                   3927:             }
                   3928:         }
                   3929:     }
1.637     raeburn  3930:     return 'ok';
                   3931: }
                   3932: 
1.639     albertel 3933: sub add_filetype {
                   3934:     my ($allfiles,$file,$type)=@_;
                   3935:     if (exists($allfiles->{$file})) {
                   3936: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3937: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3938: 	}
                   3939:     } else {
                   3940: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3941:     }
                   3942: }
                   3943: 
1.1164    raeburn  3944: sub embedded_dependency {
                   3945:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3946:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3947:         if (($identifier ne '') &&
                   3948:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3949:             ($pathfrom ne '')) {
                   3950:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3951:             foreach my $dep (@{$related->{$identifier}}) {
                   3952:                 &add_filetype($allfiles,$path.$dep,'object');
                   3953:             }
                   3954:         }
                   3955:     }
                   3956:     return;
                   3957: }
                   3958: 
1.493     albertel 3959: sub removeuploadedurl {
1.984     neumanie 3960:     my ($url)=@_;	
                   3961:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3962:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3963: }
                   3964: 
                   3965: sub removeuserfile {
                   3966:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3967:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3968:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3969:     if ($result eq 'ok') {	
1.798     raeburn  3970:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3971:             my $metafile = $fname.'.meta';
                   3972:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3973: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3974:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3975:             my $sqlresult = 
1.823     albertel 3976:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3977:                                         'portfolio_metadata',$group,
                   3978:                                         'delete');
1.798     raeburn  3979:         }
                   3980:     }
                   3981:     return $result;
1.257     www      3982: }
1.15      www      3983: 
1.530     albertel 3984: sub mkdiruserfile {
                   3985:     my ($docuname,$docudom,$dir)=@_;
                   3986:     my $home=&homeserver($docuname,$docudom);
                   3987:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3988: }
                   3989: 
1.531     albertel 3990: sub renameuserfile {
                   3991:     my ($docuname,$docudom,$old,$new)=@_;
                   3992:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3993:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3994:                         &escape("$old").':'.&escape("$new"),$home);
                   3995:     if ($result eq 'ok') {
                   3996:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3997:             my $oldmeta = $old.'.meta';
                   3998:             my $newmeta = $new.'.meta';
                   3999:             my $metaresult = 
                   4000:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4001: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4002:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4003:             my $sqlresult = 
1.823     albertel 4004:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4005:                                         'portfolio_metadata',$group,
                   4006:                                         'delete');
1.798     raeburn  4007:         }
                   4008:     }
                   4009:     return $result;
1.531     albertel 4010: }
                   4011: 
1.14      www      4012: # ------------------------------------------------------------------------- Log
                   4013: 
                   4014: sub log {
                   4015:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4016:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4017: }
                   4018: 
                   4019: # ------------------------------------------------------------------ Course Log
1.352     www      4020: #
                   4021: # This routine flushes several buffers of non-mission-critical nature
                   4022: #
1.157     www      4023: 
                   4024: sub flushcourselogs {
1.352     www      4025:     &logthis('Flushing log buffers');
                   4026: #
                   4027: # course logs
                   4028: # This is a log of all transactions in a course, which can be used
                   4029: # for data mining purposes
                   4030: #
                   4031: # It also collects the courseid database, which lists last transaction
                   4032: # times and course titles for all courseids
                   4033: #
                   4034:     my %courseidbuffer=();
1.921     raeburn  4035:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4036:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4037: 		          &escape($courselogs{$crsid}),
                   4038: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4039: 	    delete $courselogs{$crsid};
                   4040:         } else {
                   4041:             &logthis('Failed to flush log buffer for '.$crsid);
                   4042:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4043:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4044:                         " exceeded maximum size, deleting.</font>");
                   4045:                delete $courselogs{$crsid};
                   4046:             }
1.352     www      4047:         }
1.920     raeburn  4048:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4049:             'description' => $coursedescrbuf{$crsid},
                   4050:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4051:             'type'        => $coursetypebuf{$crsid},
                   4052:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4053:         };
1.191     harris41 4054:     }
1.352     www      4055: #
                   4056: # Write course id database (reverse lookup) to homeserver of courses 
                   4057: # Is used in pickcourse
                   4058: #
1.840     albertel 4059:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4060:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4061:                                     $courseidbuffer{$crs_home},
                   4062:                                     $crs_home,'timeonly');
1.352     www      4063:     }
                   4064: #
                   4065: # File accesses
                   4066: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4067: #
1.449     matthew  4068:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4069:         if ($entry =~ /___count$/) {
                   4070:             my ($dom,$name);
1.807     albertel 4071:             ($dom,$name,undef)=
1.811     albertel 4072: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4073:             if (! defined($dom) || $dom eq '' || 
                   4074:                 ! defined($name) || $name eq '') {
1.620     albertel 4075:                 my $cid = $env{'request.course.id'};
                   4076:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4077:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4078:             }
1.450     matthew  4079:             my $value = $accesshash{$entry};
                   4080:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4081:             my %temphash=($url => $value);
1.449     matthew  4082:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4083:             if ($result eq 'ok') {
                   4084:                 delete $accesshash{$entry};
                   4085:             }
                   4086:         } else {
1.811     albertel 4087:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4088:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4089:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4090:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4091:                 delete $accesshash{$entry};
                   4092:             }
1.185     www      4093:         }
1.191     harris41 4094:     }
1.352     www      4095: #
                   4096: # Roles
                   4097: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4098: #
1.800     albertel 4099:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4100:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4101: 	    split(/\:/,$entry);
                   4102:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4103:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4104:                 $rudom,$runame) eq 'ok') {
                   4105: 	    delete $userrolehash{$entry};
                   4106:         }
                   4107:     }
1.662     raeburn  4108: #
                   4109: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   4110: #
                   4111:     my %domrolebuffer = ();
1.1000    raeburn  4112:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4113:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4114:         if ($domrolebuffer{$rudom}) {
                   4115:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4116:                       '='.&escape($domainrolehash{$entry});
                   4117:         } else {
                   4118:             $domrolebuffer{$rudom}.=&escape($entry).
                   4119:                       '='.&escape($domainrolehash{$entry});
                   4120:         }
                   4121:         delete $domainrolehash{$entry};
                   4122:     }
                   4123:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 4124: 	my %servers = &get_servers($dom,'library');
                   4125: 	foreach my $tryserver (keys(%servers)) {
                   4126: 	    unless (&reply('domroleput:'.$dom.':'.
                   4127: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4128: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4129: 	    }
1.662     raeburn  4130:         }
                   4131:     }
1.186     www      4132:     $dumpcount++;
1.157     www      4133: }
                   4134: 
                   4135: sub courselog {
                   4136:     my $what=shift;
1.158     www      4137:     $what=time.':'.$what;
1.620     albertel 4138:     unless ($env{'request.course.id'}) { return ''; }
                   4139:     $coursedombuf{$env{'request.course.id'}}=
                   4140:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4141:     $coursenumbuf{$env{'request.course.id'}}=
                   4142:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4143:     $coursehombuf{$env{'request.course.id'}}=
                   4144:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4145:     $coursedescrbuf{$env{'request.course.id'}}=
                   4146:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4147:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4148:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4149:     $courseownerbuf{$env{'request.course.id'}}=
                   4150:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4151:     $coursetypebuf{$env{'request.course.id'}}=
                   4152:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4153:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4154: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4155:     } else {
1.620     albertel 4156: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4157:     }
1.620     albertel 4158:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4159: 	&flushcourselogs();
                   4160:     }
1.158     www      4161: }
                   4162: 
                   4163: sub courseacclog {
                   4164:     my $fnsymb=shift;
1.620     albertel 4165:     unless ($env{'request.course.id'}) { return ''; }
                   4166:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4167:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4168:         $what.=':POST';
1.583     matthew  4169:         # FIXME: Probably ought to escape things....
1.800     albertel 4170: 	foreach my $key (keys(%env)) {
                   4171:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4172:                 my $formitem = $1;
                   4173:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4174:                     $what.=':'.$formitem.'='.$env{$key};
                   4175:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4176:                     $what.=':'.$formitem.'='.$env{$key};
                   4177:                 }
1.158     www      4178:             }
1.191     harris41 4179:         }
1.583     matthew  4180:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4181:         # FIXME: We should not be depending on a form parameter that someone
                   4182:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4183:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4184:             $what.= ':POST';
                   4185:             # FIXME: Probably ought to escape things....
                   4186:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4187:                                  'crsdiscuss') {
1.620     albertel 4188:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4189:             }
                   4190:         }
1.158     www      4191:     }
                   4192:     &courselog($what);
1.149     www      4193: }
                   4194: 
1.185     www      4195: sub countacc {
                   4196:     my $url=&declutter(shift);
1.458     matthew  4197:     return if (! defined($url) || $url eq '');
1.620     albertel 4198:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4199: #
                   4200: # Mark that this url was used in this course
                   4201: #
1.620     albertel 4202:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4203: #
                   4204: # Increase the access count for this resource in this child process
                   4205: #
1.281     www      4206:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4207:     $accesshash{$key}++;
1.185     www      4208: }
1.349     www      4209: 
1.361     www      4210: sub linklog {
                   4211:     my ($from,$to)=@_;
                   4212:     $from=&declutter($from);
                   4213:     $to=&declutter($to);
                   4214:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4215:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4216: }
1.1160    www      4217: 
                   4218: sub statslog {
                   4219:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4220:     if ($users<2) { return; }
                   4221:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4222:             'course'       => $env{'request.course.id'},
                   4223:             'sections'     => '"all"',
                   4224:             'num_students' => $users,
                   4225:             'part'         => $part,
                   4226:             'symb'         => $symb,
                   4227:             'mean_tries'   => $av_attempts,
                   4228:             'deg_of_diff'  => $degdiff});
                   4229:     foreach my $key (keys(%dynstore)) {
                   4230:         $accesshash{$key}=$dynstore{$key};
                   4231:     }
                   4232: }
1.361     www      4233:   
1.349     www      4234: sub userrolelog {
                   4235:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4236:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4237:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4238:        $userrolehash
                   4239:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4240:                     =$tend.':'.$tstart;
1.662     raeburn  4241:     }
1.1169    droeschl 4242:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4243:        $userrolehash
                   4244:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4245:                     =$tend.':'.$tstart;
                   4246:     }
1.1169    droeschl 4247:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  4248:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4249:        $domainrolehash
                   4250:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4251:                     = $tend.':'.$tstart;
                   4252:     }
1.351     www      4253: }
                   4254: 
1.957     raeburn  4255: sub courserolelog {
                   4256:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4257:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4258:         my $cdom = $1;
                   4259:         my $cnum = $2;
                   4260:         my $sec = $3;
                   4261:         my $namespace = 'rolelog';
                   4262:         my %storehash = (
                   4263:                            role    => $trole,
                   4264:                            start   => $tstart,
                   4265:                            end     => $tend,
                   4266:                            selfenroll => $selfenroll,
                   4267:                            context    => $context,
                   4268:                         );
                   4269:         if ($trole eq 'gr') {
                   4270:             $namespace = 'groupslog';
                   4271:             $storehash{'group'} = $sec;
                   4272:         } else {
                   4273:             $storehash{'section'} = $sec;
                   4274:         }
1.1188    raeburn  4275:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4276:                    $domain,$cnum,$cdom);
1.1184    raeburn  4277:         if (($trole ne 'st') || ($sec ne '')) {
                   4278:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4279:         }
                   4280:     }
                   4281:     return;
                   4282: }
                   4283: 
1.1184    raeburn  4284: sub domainrolelog {
                   4285:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4286:     if ($area =~ m{^/($match_domain)/$}) {
                   4287:         my $cdom = $1;
                   4288:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4289:         my $namespace = 'rolelog';
                   4290:         my %storehash = (
                   4291:                            role    => $trole,
                   4292:                            start   => $tstart,
                   4293:                            end     => $tend,
                   4294:                            context => $context,
                   4295:                         );
1.1188    raeburn  4296:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4297:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4298:     }
                   4299:     return;
                   4300: 
                   4301: }
                   4302: 
                   4303: sub coauthorrolelog {
                   4304:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4305:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4306:         my $audom = $1;
                   4307:         my $auname = $2;
                   4308:         my $namespace = 'rolelog';
                   4309:         my %storehash = (
                   4310:                            role    => $trole,
                   4311:                            start   => $tstart,
                   4312:                            end     => $tend,
                   4313:                            context => $context,
                   4314:                         );
1.1188    raeburn  4315:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4316:                    $domain,$auname,$audom);
1.1184    raeburn  4317:     }
                   4318:     return;
                   4319: }
                   4320: 
1.351     www      4321: sub get_course_adv_roles {
1.948     raeburn  4322:     my ($cid,$codes) = @_;
1.620     albertel 4323:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4324:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4325:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4326:     my %nothide=();
1.800     albertel 4327:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4328:         if ($user !~ /:/) {
                   4329: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4330:         } else {
                   4331:             $nothide{$user}=1;
                   4332:         }
1.470     www      4333:     }
1.1219    raeburn  4334:     my @possdoms = ($coursehash{'domain'});
                   4335:     if ($coursehash{'checkforpriv'}) {
                   4336:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4337:     }
1.351     www      4338:     my %returnhash=();
                   4339:     my %dumphash=
                   4340:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4341:     my $now=time;
1.997     raeburn  4342:     my %privileged;
1.1000    raeburn  4343:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4344: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4345:         if (($tstart) && ($tstart<0)) { next; }
                   4346:         if (($tend) && ($tend<$now)) { next; }
                   4347:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4348:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4349: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4350:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4351:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4352: 	if ($role eq 'cr') { next; }
1.948     raeburn  4353:         if ($codes) {
                   4354:             if ($section) { $role .= ':'.$section; }
                   4355:             if ($returnhash{$role}) {
                   4356:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4357:             } else {
                   4358:                 $returnhash{$role}=$username.':'.$domain;
                   4359:             }
1.351     www      4360:         } else {
1.988     raeburn  4361:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4362:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4363:             if ($returnhash{$key}) {
                   4364: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4365:             } else {
                   4366:                 $returnhash{$key}=$username.':'.$domain;
                   4367:             }
1.351     www      4368:         }
1.948     raeburn  4369:     }
1.400     www      4370:     return %returnhash;
                   4371: }
                   4372: 
                   4373: sub get_my_roles {
1.937     raeburn  4374:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4375:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4376:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4377:     my (%dumphash,%nothide);
1.1086    raeburn  4378:     if ($context eq 'userroles') {
1.1166    raeburn  4379:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4380:     } else {
1.1219    raeburn  4381:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4382:         if ($hidepriv) {
                   4383:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4384:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4385:                 if ($user !~ /:/) {
                   4386:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4387:                 } else {
                   4388:                     $nothide{$user} = 1;
                   4389:                 }
                   4390:             }
                   4391:         }
1.858     raeburn  4392:     }
1.400     www      4393:     my %returnhash=();
                   4394:     my $now=time;
1.999     raeburn  4395:     my %privileged;
1.800     albertel 4396:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4397:         my ($role,$tend,$tstart);
                   4398:         if ($context eq 'userroles') {
1.1149    raeburn  4399:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4400: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4401:         } else {
                   4402:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4403:         }
1.400     www      4404:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4405:         my $status = 'active';
1.939     raeburn  4406:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4407:             $status = 'previous';
                   4408:         } 
                   4409:         if (($tstart) && ($now<$tstart)) {
                   4410:             $status = 'future';
                   4411:         }
                   4412:         if (ref($types) eq 'ARRAY') {
                   4413:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4414:                 next;
                   4415:             } 
                   4416:         } else {
                   4417:             if ($status ne 'active') {
                   4418:                 next;
                   4419:             }
                   4420:         }
1.867     raeburn  4421:         my ($rolecode,$username,$domain,$section,$area);
                   4422:         if ($context eq 'userroles') {
1.1186    raeburn  4423:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4424:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4425:         } else {
                   4426:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4427:         }
1.832     raeburn  4428:         if (ref($roledoms) eq 'ARRAY') {
                   4429:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4430:                 next;
                   4431:             }
                   4432:         }
                   4433:         if (ref($roles) eq 'ARRAY') {
                   4434:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4435:                 if ($role =~ /^cr\//) {
                   4436:                     if (!grep(/^cr$/,@{$roles})) {
                   4437:                         next;
                   4438:                     }
1.1104    raeburn  4439:                 } elsif ($role =~ /^gr\//) {
                   4440:                     if (!grep(/^gr$/,@{$roles})) {
                   4441:                         next;
                   4442:                     }
1.922     raeburn  4443:                 } else {
                   4444:                     next;
                   4445:                 }
1.832     raeburn  4446:             }
1.867     raeburn  4447:         }
1.937     raeburn  4448:         if ($hidepriv) {
1.1219    raeburn  4449:             my @privroles = ('dc','su');
1.999     raeburn  4450:             if ($context eq 'userroles') {
1.1219    raeburn  4451:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4452:             } else {
1.1219    raeburn  4453:                 my $possdoms = [$domain];
                   4454:                 if (ref($roledoms) eq 'ARRAY') {
                   4455:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4456:                 }
1.1219    raeburn  4457:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4458:                     if (!$nothide{$username.':'.$domain}) {
                   4459:                         next;
                   4460:                     }
                   4461:                 }
1.937     raeburn  4462:             }
                   4463:         }
1.933     raeburn  4464:         if ($withsec) {
                   4465:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4466:                 $tstart.':'.$tend;
                   4467:         } else {
                   4468:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4469:         }
1.832     raeburn  4470:     }
1.373     www      4471:     return %returnhash;
1.399     www      4472: }
                   4473: 
                   4474: # ----------------------------------------------------- Frontpage Announcements
                   4475: #
                   4476: #
                   4477: 
                   4478: sub postannounce {
                   4479:     my ($server,$text)=@_;
1.844     albertel 4480:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4481:     unless ($text=~/\w/) { $text=''; }
                   4482:     return &reply('setannounce:'.&escape($text),$server);
                   4483: }
                   4484: 
                   4485: sub getannounce {
1.448     albertel 4486: 
                   4487:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4488: 	my $announcement='';
1.800     albertel 4489: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4490: 	close($fh);
1.399     www      4491: 	if ($announcement=~/\w/) { 
                   4492: 	    return 
                   4493:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4494:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4495: 	} else {
                   4496: 	    return '';
                   4497: 	}
                   4498:     } else {
                   4499: 	return '';
                   4500:     }
1.351     www      4501: }
1.353     www      4502: 
                   4503: # ---------------------------------------------------------- Course ID routines
                   4504: # Deal with domain's nohist_courseid.db files
                   4505: #
                   4506: 
                   4507: sub courseidput {
1.921     raeburn  4508:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4509:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4510:     my $outcome;
                   4511:     if ($caller eq 'timeonly') {
                   4512:         my $cids = '';
                   4513:         foreach my $item (keys(%$storehash)) {
                   4514:             $cids.=&escape($item).'&';
                   4515:         }
                   4516:         $cids=~s/\&$//;
                   4517:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4518:                           $coursehome);       
                   4519:     } else {
                   4520:         my $items = '';
                   4521:         foreach my $item (keys(%$storehash)) {
                   4522:             $items.= &escape($item).'='.
                   4523:                      &freeze_escape($$storehash{$item}).'&';
                   4524:         }
                   4525:         $items=~s/\&$//;
                   4526:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4527:                           $coursehome);
1.918     raeburn  4528:     }
                   4529:     if ($outcome eq 'unknown_cmd') {
                   4530:         my $what;
                   4531:         foreach my $cid (keys(%$storehash)) {
                   4532:             $what .= &escape($cid).'=';
1.921     raeburn  4533:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4534:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4535:             }
                   4536:             $what =~ s/\:$/&/;
                   4537:         }
                   4538:         $what =~ s/\&$//;  
                   4539:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4540:     } else {
                   4541:         return $outcome;
                   4542:     }
1.353     www      4543: }
                   4544: 
                   4545: sub courseiddump {
1.921     raeburn  4546:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4547:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4548:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  4549:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  4550:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4551:     my $as_hash = 1;
                   4552:     my %returnhash;
                   4553:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4554:     my %libserv = &all_library();
                   4555:     foreach my $tryserver (keys(%libserv)) {
                   4556:         if ( (  $hostidflag == 1 
                   4557: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4558: 	     || (!defined($hostidflag)) ) {
                   4559: 
1.918     raeburn  4560: 	    if (($domfilter eq '') ||
                   4561: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4562:                 my $rep;
                   4563:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4564:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4565:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   4566:                                 &escape($descfilter), &escape($instcodefilter), 
                   4567:                                 &escape($ownerfilter), &escape($coursefilter),
                   4568:                                 &escape($typefilter), &escape($regexp_ok), 
                   4569:                                 $as_hash, &escape($selfenrollonly), 
                   4570:                                 &escape($catfilter), $showhidden, $caller, 
                   4571:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   4572:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  4573:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   4574:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 4575:                 } else {
                   4576:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4577:                              $sincefilter.':'.&escape($descfilter).':'.
                   4578:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4579:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4580:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4581:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4582:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4583:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4584:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  4585:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   4586:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 4587:                 }
                   4588:                      
1.918     raeburn  4589:                 my @pairs=split(/\&/,$rep);
                   4590:                 foreach my $item (@pairs) {
                   4591:                     my ($key,$value)=split(/\=/,$item,2);
                   4592:                     $key = &unescape($key);
                   4593:                     next if ($key =~ /^error: 2 /);
                   4594:                     my $result = &thaw_unescape($value);
                   4595:                     if (ref($result) eq 'HASH') {
                   4596:                         $returnhash{$key}=$result;
                   4597:                     } else {
1.921     raeburn  4598:                         my @responses = split(/:/,$value);
                   4599:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4600:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4601:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4602:                         }
1.1008    raeburn  4603:                     }
1.353     www      4604:                 }
                   4605:             }
                   4606:         }
                   4607:     }
                   4608:     return %returnhash;
                   4609: }
                   4610: 
1.1055    raeburn  4611: sub courselastaccess {
                   4612:     my ($cdom,$cnum,$hostidref) = @_;
                   4613:     my %returnhash;
                   4614:     if ($cdom && $cnum) {
                   4615:         my $chome = &homeserver($cnum,$cdom);
                   4616:         if ($chome ne 'no_host') {
                   4617:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4618:             &extract_lastaccess(\%returnhash,$rep);
                   4619:         }
                   4620:     } else {
                   4621:         if (!$cdom) { $cdom=''; }
                   4622:         my %libserv = &all_library();
                   4623:         foreach my $tryserver (keys(%libserv)) {
                   4624:             if (ref($hostidref) eq 'ARRAY') {
                   4625:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4626:             } 
                   4627:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4628:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4629:                 &extract_lastaccess(\%returnhash,$rep);
                   4630:             }
                   4631:         }
                   4632:     }
                   4633:     return %returnhash;
                   4634: }
                   4635: 
                   4636: sub extract_lastaccess {
                   4637:     my ($returnhash,$rep) = @_;
                   4638:     if (ref($returnhash) eq 'HASH') {
                   4639:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4640:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4641:                  $rep eq '') {
                   4642:             my @pairs=split(/\&/,$rep);
                   4643:             foreach my $item (@pairs) {
                   4644:                 my ($key,$value)=split(/\=/,$item,2);
                   4645:                 $key = &unescape($key);
                   4646:                 next if ($key =~ /^error: 2 /);
                   4647:                 $returnhash->{$key} = &thaw_unescape($value);
                   4648:             }
                   4649:         }
                   4650:     }
                   4651:     return;
                   4652: }
                   4653: 
1.658     raeburn  4654: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4655: 
                   4656: sub dcmailput {
1.685     raeburn  4657:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4658:     my $status = &Apache::lonnet::critical(
1.740     www      4659:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4660:        &escape($message),$server);
1.662     raeburn  4661:     return $status;
                   4662: }
                   4663: 
1.658     raeburn  4664: sub dcmaildump {
                   4665:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4666:     my %returnhash=();
1.846     albertel 4667: 
                   4668:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4669:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4670:                                                          &escape($enddate).':';
                   4671: 	my @esc_senders=map { &escape($_)} @$senders;
                   4672: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4673: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4674:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4675:             if (($key) && ($value)) {
                   4676:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4677:             }
                   4678:         }
                   4679:     }
                   4680:     return %returnhash;
                   4681: }
1.662     raeburn  4682: # ---------------------------------------------------------- Domain roles
                   4683: 
                   4684: sub get_domain_roles {
                   4685:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4686:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4687:         $startdate = '.';
                   4688:     }
1.1018    raeburn  4689:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4690:         $enddate = '.';
                   4691:     }
1.922     raeburn  4692:     my $rolelist;
                   4693:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  4694:         $rolelist = join('&',@{$roles});
1.922     raeburn  4695:     }
1.662     raeburn  4696:     my %personnel = ();
1.841     albertel 4697: 
                   4698:     my %servers = &get_servers($dom,'library');
                   4699:     foreach my $tryserver (keys(%servers)) {
                   4700: 	%{$personnel{$tryserver}}=();
                   4701: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4702: 					    &escape($startdate).':'.
                   4703: 					    &escape($enddate).':'.
                   4704: 					    &escape($rolelist), $tryserver))) {
                   4705: 	    my ($key,$value) = split(/\=/,$line,2);
                   4706: 	    if (($key) && ($value)) {
                   4707: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4708: 	    }
                   4709: 	}
1.662     raeburn  4710:     }
                   4711:     return %personnel;
                   4712: }
1.658     raeburn  4713: 
1.1057    www      4714: # ----------------------------------------------------------- Interval timing 
1.149     www      4715: 
1.1153    www      4716: {
                   4717: # Caches needed for speedup of navmaps
                   4718: # We don't want to cache this for very long at all (5 seconds at most)
                   4719: # 
                   4720: # The user for whom we cache
                   4721: my $cachedkey='';
                   4722: # The cached times for this user
                   4723: my %cachedtimes=();
                   4724: # When this was last done
1.1282    raeburn  4725: my $cachedtime='';
1.1153    www      4726: 
                   4727: sub load_all_first_access {
1.1308    raeburn  4728:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      4729:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  4730:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   4731:         (!$ignorecache)) {
1.1154    raeburn  4732:         return;
                   4733:     }
                   4734:     $cachedtime=time;
                   4735:     $cachedkey=$uname.':'.$udom;
                   4736:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4737: }
                   4738: 
1.504     albertel 4739: sub get_first_access {
1.1308    raeburn  4740:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 4741:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4742:     if ($argsymb) { $symb=$argsymb; }
                   4743:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4744:     if ($argmap) { $map = $argmap; }
1.926     albertel 4745:     if ($type eq 'course') {
                   4746: 	$res='course';
                   4747:     } elsif ($type eq 'map') {
1.588     albertel 4748: 	$res=&symbread($map);
                   4749:     } else {
                   4750: 	$res=$symb;
                   4751:     }
1.1308    raeburn  4752:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      4753:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4754: }
                   4755: 
                   4756: sub set_first_access {
1.1162    raeburn  4757:     my ($type,$interval)=@_;
1.790     albertel 4758:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4759:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4760:     if ($type eq 'course') {
                   4761: 	$res='course';
                   4762:     } elsif ($type eq 'map') {
1.588     albertel 4763: 	$res=&symbread($map);
                   4764:     } else {
                   4765: 	$res=$symb;
                   4766:     }
1.1153    www      4767:     $cachedkey='';
1.1162    raeburn  4768:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4769:     if (!$firstaccess) {
1.1162    raeburn  4770:         my $start = time;
                   4771: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4772:                           $udom,$uname);
                   4773:         if ($putres eq 'ok') {
                   4774:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4775:                  $udom,$uname); 
                   4776:             &appenv(
                   4777:                      {
                   4778:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4779:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4780:                      }
                   4781:                   );
                   4782:         }
                   4783:         return $putres;
1.505     albertel 4784:     }
                   4785:     return 'already_set';
1.504     albertel 4786: }
1.1153    www      4787: }
1.1282    raeburn  4788: 
1.110     www      4789: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4790: 
                   4791: sub expirespread {
                   4792:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4793:     my $cid=$env{'request.course.id'}; 
1.110     www      4794:     if ($cid) {
                   4795:        my $now=time;
                   4796:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4797:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4798:                             $env{'course.'.$cid.'.num'}.
1.110     www      4799: 	        	    ':nohist_expirationdates:'.
                   4800:                             &escape($key).'='.$now,
1.620     albertel 4801:                             $env{'course.'.$cid.'.home'})
1.110     www      4802:     }
                   4803:     return 'ok';
1.14      www      4804: }
                   4805: 
1.109     www      4806: # ----------------------------------------------------- Devalidate Spreadsheets
                   4807: 
                   4808: sub devalidate {
1.325     www      4809:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4810:     my $cid=$env{'request.course.id'}; 
1.109     www      4811:     if ($cid) {
1.391     matthew  4812:         # delete the stored spreadsheets for
                   4813:         # - the student level sheet of this user in course's homespace
                   4814:         # - the assessment level sheet for this resource 
                   4815:         #   for this user in user's homespace
1.553     albertel 4816: 	# - current conditional state info
1.325     www      4817: 	my $key=$uname.':'.$udom.':';
1.109     www      4818:         my $status=
1.299     matthew  4819: 	    &del('nohist_calculatedsheets',
1.391     matthew  4820: 		 [$key.'studentcalc:'],
1.620     albertel 4821: 		 $env{'course.'.$cid.'.domain'},
                   4822: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4823: 		.' '.
                   4824: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4825: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4826:         unless ($status eq 'ok ok') {
                   4827:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4828:                     $uname.' at '.$udom.' for '.
1.109     www      4829: 		    $symb.': '.$status);
1.133     albertel 4830:         }
1.553     albertel 4831: 	&delenv('user.state.'.$cid);
1.109     www      4832:     }
                   4833: }
                   4834: 
1.265     albertel 4835: sub get_scalar {
                   4836:     my ($string,$end) = @_;
                   4837:     my $value;
                   4838:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4839: 	$value = $1;
                   4840:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4841: 	$value = $1;
                   4842:     }
                   4843:     return &unescape($value);
                   4844: }
                   4845: 
                   4846: sub array2str {
                   4847:   my (@array) = @_;
                   4848:   my $result=&arrayref2str(\@array);
                   4849:   $result=~s/^__ARRAY_REF__//;
                   4850:   $result=~s/__END_ARRAY_REF__$//;
                   4851:   return $result;
                   4852: }
                   4853: 
1.204     albertel 4854: sub arrayref2str {
                   4855:   my ($arrayref) = @_;
1.265     albertel 4856:   my $result='__ARRAY_REF__';
1.204     albertel 4857:   foreach my $elem (@$arrayref) {
1.265     albertel 4858:     if(ref($elem) eq 'ARRAY') {
                   4859:       $result.=&arrayref2str($elem).'&';
                   4860:     } elsif(ref($elem) eq 'HASH') {
                   4861:       $result.=&hashref2str($elem).'&';
                   4862:     } elsif(ref($elem)) {
                   4863:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4864:     } else {
                   4865:       $result.=&escape($elem).'&';
                   4866:     }
                   4867:   }
                   4868:   $result=~s/\&$//;
1.265     albertel 4869:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4870:   return $result;
                   4871: }
                   4872: 
1.168     albertel 4873: sub hash2str {
1.204     albertel 4874:   my (%hash) = @_;
                   4875:   my $result=&hashref2str(\%hash);
1.265     albertel 4876:   $result=~s/^__HASH_REF__//;
                   4877:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4878:   return $result;
                   4879: }
                   4880: 
                   4881: sub hashref2str {
                   4882:   my ($hashref)=@_;
1.265     albertel 4883:   my $result='__HASH_REF__';
1.800     albertel 4884:   foreach my $key (sort(keys(%$hashref))) {
                   4885:     if (ref($key) eq 'ARRAY') {
                   4886:       $result.=&arrayref2str($key).'=';
                   4887:     } elsif (ref($key) eq 'HASH') {
                   4888:       $result.=&hashref2str($key).'=';
                   4889:     } elsif (ref($key)) {
1.265     albertel 4890:       $result.='=';
1.800     albertel 4891:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4892:     } else {
1.1132    raeburn  4893: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4894:     }
                   4895: 
1.800     albertel 4896:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4897:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4898:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4899:       $result.=&hashref2str($hashref->{$key}).'&';
                   4900:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4901:        $result.='&';
1.800     albertel 4902:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4903:     } else {
1.800     albertel 4904:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4905:     }
                   4906:   }
1.168     albertel 4907:   $result=~s/\&$//;
1.265     albertel 4908:   $result .= '__END_HASH_REF__';
1.168     albertel 4909:   return $result;
                   4910: }
                   4911: 
                   4912: sub str2hash {
1.265     albertel 4913:     my ($string)=@_;
                   4914:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4915:     return %$hash;
                   4916: }
                   4917: 
                   4918: sub str2hashref {
1.168     albertel 4919:   my ($string) = @_;
1.265     albertel 4920: 
                   4921:   my %hash;
                   4922: 
                   4923:   if($string !~ /^__HASH_REF__/) {
                   4924:       if (! ($string eq '' || !defined($string))) {
                   4925: 	  $hash{'error'}='Not hash reference';
                   4926:       }
                   4927:       return (\%hash, $string);
                   4928:   }
                   4929: 
                   4930:   $string =~ s/^__HASH_REF__//;
                   4931: 
                   4932:   while($string !~ /^__END_HASH_REF__/) {
                   4933:       #key
                   4934:       my $key='';
                   4935:       if($string =~ /^__HASH_REF__/) {
                   4936:           ($key, $string)=&str2hashref($string);
                   4937:           if(defined($key->{'error'})) {
                   4938:               $hash{'error'}='Bad data';
                   4939:               return (\%hash, $string);
                   4940:           }
                   4941:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4942:           ($key, $string)=&str2arrayref($string);
                   4943:           if($key->[0] eq 'Array reference error') {
                   4944:               $hash{'error'}='Bad data';
                   4945:               return (\%hash, $string);
                   4946:           }
                   4947:       } else {
                   4948:           $string =~ s/^(.*?)=//;
1.267     albertel 4949: 	  $key=&unescape($1);
1.265     albertel 4950:       }
                   4951:       $string =~ s/^=//;
                   4952: 
                   4953:       #value
                   4954:       my $value='';
                   4955:       if($string =~ /^__HASH_REF__/) {
                   4956:           ($value, $string)=&str2hashref($string);
                   4957:           if(defined($value->{'error'})) {
                   4958:               $hash{'error'}='Bad data';
                   4959:               return (\%hash, $string);
                   4960:           }
                   4961:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4962:           ($value, $string)=&str2arrayref($string);
                   4963:           if($value->[0] eq 'Array reference error') {
                   4964:               $hash{'error'}='Bad data';
                   4965:               return (\%hash, $string);
                   4966:           }
                   4967:       } else {
                   4968: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4969:       }
                   4970:       $string =~ s/^&//;
                   4971: 
                   4972:       $hash{$key}=$value;
1.204     albertel 4973:   }
1.265     albertel 4974: 
                   4975:   $string =~ s/^__END_HASH_REF__//;
                   4976: 
                   4977:   return (\%hash, $string);
1.204     albertel 4978: }
                   4979: 
                   4980: sub str2array {
1.265     albertel 4981:     my ($string)=@_;
                   4982:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4983:     return @$array;
                   4984: }
                   4985: 
                   4986: sub str2arrayref {
1.204     albertel 4987:   my ($string) = @_;
1.265     albertel 4988:   my @array;
                   4989: 
                   4990:   if($string !~ /^__ARRAY_REF__/) {
                   4991:       if (! ($string eq '' || !defined($string))) {
                   4992: 	  $array[0]='Array reference error';
                   4993:       }
                   4994:       return (\@array, $string);
                   4995:   }
                   4996: 
                   4997:   $string =~ s/^__ARRAY_REF__//;
                   4998: 
                   4999:   while($string !~ /^__END_ARRAY_REF__/) {
                   5000:       my $value='';
                   5001:       if($string =~ /^__HASH_REF__/) {
                   5002:           ($value, $string)=&str2hashref($string);
                   5003:           if(defined($value->{'error'})) {
                   5004:               $array[0] ='Array reference error';
                   5005:               return (\@array, $string);
                   5006:           }
                   5007:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5008:           ($value, $string)=&str2arrayref($string);
                   5009:           if($value->[0] eq 'Array reference error') {
                   5010:               $array[0] ='Array reference error';
                   5011:               return (\@array, $string);
                   5012:           }
                   5013:       } else {
                   5014: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5015:       }
                   5016:       $string =~ s/^&//;
                   5017: 
                   5018:       push(@array, $value);
1.191     harris41 5019:   }
1.265     albertel 5020: 
                   5021:   $string =~ s/^__END_ARRAY_REF__//;
                   5022: 
                   5023:   return (\@array, $string);
1.168     albertel 5024: }
                   5025: 
1.167     albertel 5026: # -------------------------------------------------------------------Temp Store
                   5027: 
1.168     albertel 5028: sub tmpreset {
                   5029:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5030:   if (!$symb) {
                   5031:     $symb=&symbread();
1.620     albertel 5032:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5033:   }
                   5034:   $symb=escape($symb);
                   5035: 
1.620     albertel 5036:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5037:   $namespace=~s/\//\_/g;
                   5038:   $namespace=~s/\W//g;
                   5039: 
1.620     albertel 5040:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5041:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5042:   if ($domain eq 'public' && $stuname eq 'public') {
                   5043:       $stuname=$ENV{'REMOTE_ADDR'};
                   5044:   }
1.1117    foxr     5045:   my $path=LONCAPA::tempdir();
1.168     albertel 5046:   my %hash;
                   5047:   if (tie(%hash,'GDBM_File',
                   5048: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5049: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5050:     foreach my $key (keys(%hash)) {
1.180     albertel 5051:       if ($key=~ /:$symb/) {
1.168     albertel 5052: 	delete($hash{$key});
                   5053:       }
                   5054:     }
                   5055:   }
                   5056: }
                   5057: 
1.167     albertel 5058: sub tmpstore {
1.168     albertel 5059:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5060: 
                   5061:   if (!$symb) {
                   5062:     $symb=&symbread();
1.620     albertel 5063:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5064:   }
                   5065:   $symb=escape($symb);
                   5066: 
                   5067:   if (!$namespace) {
                   5068:     # I don't think we would ever want to store this for a course.
                   5069:     # it seems this will only be used if we don't have a course.
1.620     albertel 5070:     #$namespace=$env{'request.course.id'};
1.168     albertel 5071:     #if (!$namespace) {
1.620     albertel 5072:       $namespace=$env{'request.state'};
1.168     albertel 5073:     #}
                   5074:   }
                   5075:   $namespace=~s/\//\_/g;
                   5076:   $namespace=~s/\W//g;
1.620     albertel 5077:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5078:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5079:   if ($domain eq 'public' && $stuname eq 'public') {
                   5080:       $stuname=$ENV{'REMOTE_ADDR'};
                   5081:   }
1.168     albertel 5082:   my $now=time;
                   5083:   my %hash;
1.1117    foxr     5084:   my $path=LONCAPA::tempdir();
1.168     albertel 5085:   if (tie(%hash,'GDBM_File',
                   5086: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5087: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5088:     $hash{"version:$symb"}++;
                   5089:     my $version=$hash{"version:$symb"};
                   5090:     my $allkeys=''; 
                   5091:     foreach my $key (keys(%$storehash)) {
                   5092:       $allkeys.=$key.':';
1.591     albertel 5093:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5094:     }
                   5095:     $hash{"$version:$symb:timestamp"}=$now;
                   5096:     $allkeys.='timestamp';
                   5097:     $hash{"$version:keys:$symb"}=$allkeys;
                   5098:     if (untie(%hash)) {
                   5099:       return 'ok';
                   5100:     } else {
                   5101:       return "error:$!";
                   5102:     }
                   5103:   } else {
                   5104:     return "error:$!";
                   5105:   }
                   5106: }
1.167     albertel 5107: 
1.168     albertel 5108: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5109: 
1.168     albertel 5110: sub tmprestore {
                   5111:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5112: 
1.168     albertel 5113:   if (!$symb) {
                   5114:     $symb=&symbread();
1.620     albertel 5115:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5116:   }
                   5117:   $symb=escape($symb);
                   5118: 
1.620     albertel 5119:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5120: 
1.620     albertel 5121:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5122:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5123:   if ($domain eq 'public' && $stuname eq 'public') {
                   5124:       $stuname=$ENV{'REMOTE_ADDR'};
                   5125:   }
1.168     albertel 5126:   my %returnhash;
                   5127:   $namespace=~s/\//\_/g;
                   5128:   $namespace=~s/\W//g;
                   5129:   my %hash;
1.1117    foxr     5130:   my $path=LONCAPA::tempdir();
1.168     albertel 5131:   if (tie(%hash,'GDBM_File',
                   5132: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5133: 	  &GDBM_READER(),0640)) {
1.168     albertel 5134:     my $version=$hash{"version:$symb"};
                   5135:     $returnhash{'version'}=$version;
                   5136:     my $scope;
                   5137:     for ($scope=1;$scope<=$version;$scope++) {
                   5138:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5139:       my @keys=split(/:/,$vkeys);
                   5140:       my $key;
                   5141:       $returnhash{"$scope:keys"}=$vkeys;
                   5142:       foreach $key (@keys) {
1.591     albertel 5143: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5144: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5145:       }
                   5146:     }
1.168     albertel 5147:     if (!(untie(%hash))) {
                   5148:       return "error:$!";
                   5149:     }
                   5150:   } else {
                   5151:     return "error:$!";
                   5152:   }
                   5153:   return %returnhash;
1.167     albertel 5154: }
                   5155: 
1.9       www      5156: # ----------------------------------------------------------------------- Store
                   5157: 
                   5158: sub store {
1.1269    raeburn  5159:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5160:     my $home='';
                   5161: 
1.168     albertel 5162:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5163: 
1.213     www      5164:     $symb=&symbclean($symb);
1.122     albertel 5165:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5166: 
1.620     albertel 5167:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5168:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5169: 
                   5170:     &devalidate($symb,$stuname,$domain);
1.109     www      5171: 
                   5172:     $symb=escape($symb);
1.187     www      5173:     if (!$namespace) { 
1.620     albertel 5174:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5175:           return ''; 
                   5176:        } 
                   5177:     }
1.620     albertel 5178:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5179: 
                   5180:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5181:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5182: 
1.12      www      5183:     my $namevalue='';
1.800     albertel 5184:     foreach my $key (keys(%$storehash)) {
                   5185:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5186:     }
1.12      www      5187:     $namevalue=~s/\&$//;
1.187     www      5188:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  5189:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5190: }
                   5191: 
1.47      www      5192: # -------------------------------------------------------------- Critical Store
                   5193: 
                   5194: sub cstore {
1.1269    raeburn  5195:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5196:     my $home='';
                   5197: 
1.168     albertel 5198:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5199: 
1.213     www      5200:     $symb=&symbclean($symb);
1.122     albertel 5201:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5202: 
1.620     albertel 5203:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5204:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5205: 
                   5206:     &devalidate($symb,$stuname,$domain);
1.109     www      5207: 
                   5208:     $symb=escape($symb);
1.187     www      5209:     if (!$namespace) { 
1.620     albertel 5210:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5211:           return ''; 
                   5212:        } 
                   5213:     }
1.620     albertel 5214:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5215: 
                   5216:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5217:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5218: 
1.47      www      5219:     my $namevalue='';
1.800     albertel 5220:     foreach my $key (keys(%$storehash)) {
                   5221:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5222:     }
1.47      www      5223:     $namevalue=~s/\&$//;
1.187     www      5224:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5225:     return critical
1.1269    raeburn  5226:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5227: }
                   5228: 
1.9       www      5229: # --------------------------------------------------------------------- Restore
                   5230: 
                   5231: sub restore {
1.124     www      5232:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5233:     my $home='';
                   5234: 
1.168     albertel 5235:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5236: 
1.122     albertel 5237:     if (!$symb) {
1.1224    raeburn  5238:         return if ($namespace eq 'courserequests');
                   5239:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5240:     } else {
1.1224    raeburn  5241:         unless ($namespace eq 'courserequests') {
                   5242:             $symb=&escape(&symbclean($symb));
                   5243:         }
1.122     albertel 5244:     }
1.188     www      5245:     if (!$namespace) { 
1.620     albertel 5246:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5247:           return ''; 
                   5248:        } 
                   5249:     }
1.620     albertel 5250:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5251:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5252:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5253:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5254: 
1.12      www      5255:     my %returnhash=();
1.800     albertel 5256:     foreach my $line (split(/\&/,$answer)) {
                   5257: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5258:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5259:     }
1.75      www      5260:     my $version;
                   5261:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5262:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5263:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5264:        }
1.75      www      5265:     }
1.13      www      5266:     return %returnhash;
1.34      www      5267: }
                   5268: 
                   5269: # ---------------------------------------------------------- Course Description
1.1118    foxr     5270: #
                   5271: #  
1.34      www      5272: 
                   5273: sub coursedescription {
1.731     albertel 5274:     my ($courseid,$args)=@_;
1.34      www      5275:     $courseid=~s/^\///;
1.49      www      5276:     $courseid=~s/\_/\//g;
1.34      www      5277:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5278:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5279:     my $normalid=$cdomain.'_'.$cnum;
                   5280:     # need to always cache even if we get errors otherwise we keep 
                   5281:     # trying and trying and trying to get the course description.
                   5282:     my %envhash=();
                   5283:     my %returnhash=();
1.731     albertel 5284:     
                   5285:     my $expiretime=600;
                   5286:     if ($env{'request.course.id'} eq $normalid) {
                   5287: 	$expiretime=120;
                   5288:     }
                   5289: 
                   5290:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5291:     if (!$args->{'freshen_cache'}
                   5292: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5293: 	foreach my $key (keys(%env)) {
                   5294: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5295: 	    my ($setting) = $1;
                   5296: 	    $returnhash{$setting} = $env{$key};
                   5297: 	}
                   5298: 	return %returnhash;
                   5299:     }
                   5300: 
1.1118    foxr     5301:     # get the data again
                   5302: 
1.731     albertel 5303:     if (!$args->{'one_time'}) {
                   5304: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5305:     }
1.811     albertel 5306: 
1.34      www      5307:     if ($chome ne 'no_host') {
1.302     albertel 5308:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5309:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5310: 	   my $username = $env{'user.name'}; # Defult username
                   5311: 	   if(defined $args->{'user'}) {
                   5312: 	       $username = $args->{'user'};
                   5313: 	   }
1.129     albertel 5314:            $returnhash{'home'}= $chome;
                   5315: 	   $returnhash{'domain'} = $cdomain;
                   5316: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5317:            if (!defined($returnhash{'type'})) {
                   5318:                $returnhash{'type'} = 'Course';
                   5319:            }
1.130     albertel 5320:            while (my ($name,$value) = each %returnhash) {
1.53      www      5321:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5322:            }
1.270     www      5323:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5324:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5325: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5326:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5327:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5328:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5329:        }
                   5330:     }
1.731     albertel 5331:     if (!$args->{'one_time'}) {
1.949     raeburn  5332: 	&appenv(\%envhash);
1.731     albertel 5333:     }
1.302     albertel 5334:     return %returnhash;
1.461     www      5335: }
                   5336: 
1.1080    raeburn  5337: sub update_released_required {
                   5338:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5339:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5340:         $cid = $env{'request.course.id'};
                   5341:         $cdom = $env{'course.'.$cid.'.domain'};
                   5342:         $cnum = $env{'course.'.$cid.'.num'};
                   5343:         $chome = $env{'course.'.$cid.'.home'};
                   5344:     }
                   5345:     if ($needsrelease) {
                   5346:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5347:         my $needsupdate;
                   5348:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5349:             $needsupdate = 1;
                   5350:         } else {
                   5351:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5352:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5353:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5354:                 $needsupdate = 1;
                   5355:             }
                   5356:         }
                   5357:         if ($needsupdate) {
                   5358:             my %needshash = (
                   5359:                              'internal.releaserequired' => $needsrelease,
                   5360:                             );
                   5361:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5362:             if ($putresult eq 'ok') {
                   5363:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5364:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5365:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5366:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5367:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5368:                 }
                   5369:             }
                   5370:         }
                   5371:     }
                   5372:     return;
                   5373: }
                   5374: 
1.461     www      5375: # -------------------------------------------------See if a user is privileged
                   5376: 
                   5377: sub privileged {
1.1219    raeburn  5378:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5379:     my $now = time;
1.1219    raeburn  5380:     my $roles;
                   5381:     if (ref($possroles) eq 'ARRAY') {
                   5382:         $roles = $possroles; 
                   5383:     } else {
                   5384:         $roles = ['dc','su'];
                   5385:     }
                   5386:     if (ref($possdomains) eq 'ARRAY') {
                   5387:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5388:         foreach my $dom (@{$possdomains}) {
                   5389:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5390:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5391:                 foreach my $role (@{$roles}) {
                   5392:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5393:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5394:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5395:                             return 1 unless (($end && $end < $now) ||
                   5396:                                              ($start && $start > $now));
                   5397:                         }
                   5398:                     }
                   5399:                 }
                   5400:             }
                   5401:         }
                   5402:     } else {
                   5403:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5404:         my $now = time;
1.1170    droeschl 5405: 
1.1275    musolffc 5406:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5407:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5408:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5409:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5410:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5411:             }
1.1219    raeburn  5412:         }
                   5413:     }
                   5414:     return 0;
                   5415: }
1.1170    droeschl 5416: 
1.1219    raeburn  5417: sub privileged_by_domain {
                   5418:     my ($domains,$roles) = @_;
                   5419:     my %privileged = ();
                   5420:     my $cachetime = 60*60*24;
                   5421:     my $now = time;
                   5422:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5423:         return %privileged;
                   5424:     }
                   5425:     foreach my $dom (@{$domains}) {
                   5426:         next if (ref($privileged{$dom}) eq 'HASH');
                   5427:         my $needroles;
                   5428:         foreach my $role (@{$roles}) {
                   5429:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5430:             if (defined($cached)) {
                   5431:                 if (ref($result) eq 'HASH') {
                   5432:                     $privileged{$dom}{$role} = $result;
                   5433:                 }
                   5434:             } else {
                   5435:                 $needroles = 1;
                   5436:             }
                   5437:         }
                   5438:         if ($needroles) {
                   5439:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5440:             $privileged{$dom} = {};
                   5441:             foreach my $server (keys(%dompersonnel)) {
                   5442:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5443:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5444:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5445:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5446:                         next if ($end && $end < $now);
                   5447:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5448:                             $dompersonnel{$server}{$item};
                   5449:                     }
                   5450:                 }
                   5451:             }
                   5452:             if (ref($privileged{$dom}) eq 'HASH') {
                   5453:                 foreach my $role (@{$roles}) {
                   5454:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5455:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5456:                     } else {
                   5457:                         my %hash = ();
                   5458:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5459:                     }
                   5460:                 }
                   5461:             }
                   5462:         }
                   5463:     }
                   5464:     return %privileged;
1.9       www      5465: }
1.1       albertel 5466: 
1.103     harris41 5467: # -------------------------------------------------------- Get user privileges
1.11      www      5468: 
                   5469: sub rolesinit {
1.1169    droeschl 5470:     my ($domain, $username) = @_;
                   5471:     my %userroles = ('user.login.time' => time);
                   5472:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5473: 
                   5474:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5475:     # also, blocking can be triggered by an activating timer
                   5476:     # it's saved in the user's %env.
                   5477:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5478:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5479:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5480:         %timerintchk, %timerintenv);
                   5481: 
1.1162    raeburn  5482:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5483:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5484:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5485:     }
1.1169    droeschl 5486: 
1.1162    raeburn  5487:     foreach my $key (keys(%timerinterval)) {
                   5488:         my ($cid,$rest) = split(/\0/,$key);
                   5489:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5490:     }
1.1169    droeschl 5491: 
1.11      www      5492:     my %allroles=();
1.1162    raeburn  5493:     my %allgroups=();
1.11      www      5494: 
1.1274    raeburn  5495:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5496:         my $role = $rolesdump{$area};
                   5497:         $area =~ s/\_\w\w$//;
                   5498: 
                   5499:         my ($trole, $tend, $tstart, $group_privs);
                   5500: 
                   5501:         if ($role =~ /^cr/) {
                   5502:         # Custom role, defined by a user 
                   5503:         # e.g., user.role.cr/msu/smith/mynewrole
                   5504:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5505:                 $trole = $1;
                   5506:                 ($tend, $tstart) = split('_', $2);
                   5507:             } else {
                   5508:                 $trole = $role;
                   5509:             }
                   5510:         } elsif ($role =~ m|^gr/|) {
                   5511:         # Role of member in a group, defined within a course/community
                   5512:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5513:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5514:             next if $tstart eq '-1';
                   5515:             ($trole, $group_privs) = split(/\//, $trole);
                   5516:             $group_privs = &unescape($group_privs);
                   5517:         } else {
                   5518:         # Just a normal role, defined in roles.tab
                   5519:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5520:         }
                   5521: 
                   5522:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5523:                  $username);
                   5524:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5525: 
                   5526:         # role expired or not available yet?
                   5527:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5528:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5529: 
                   5530:         next if $area eq '' or $trole eq '';
                   5531: 
                   5532:         my $spec = "$trole.$area";
                   5533:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5534: 
                   5535:         if ($trole =~ /^cr\//) {
                   5536:         # Custom role, defined by a user
                   5537:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5538:         } elsif ($trole eq 'gr') {
                   5539:         # Role of a member in a group, defined within a course/community
                   5540:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5541:             next;
                   5542:         } else {
                   5543:         # Normal role, defined in roles.tab
                   5544:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5545:         }
                   5546: 
                   5547:         my $cid = $tdomain.'_'.$trest;
                   5548:         unless ($firstaccchk{$cid}) {
                   5549:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5550:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5551:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5552:                         $coursetimerstarts{$cid}{$item}; 
                   5553:                 }
                   5554:             }
                   5555:             $firstaccchk{$cid} = 1;
                   5556:         }
                   5557:         unless ($timerintchk{$cid}) {
                   5558:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5559:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5560:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5561:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5562:                 }
1.12      www      5563:             }
1.1169    droeschl 5564:             $timerintchk{$cid} = 1;
1.191     harris41 5565:         }
1.11      www      5566:     }
1.1169    droeschl 5567: 
                   5568:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5569:         \%allroles, \%allgroups);
                   5570:     $env{'user.adv'} = $userroles{'user.adv'};
                   5571: 
1.1162    raeburn  5572:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5573: }
                   5574: 
1.567     raeburn  5575: sub set_arearole {
1.1215    raeburn  5576:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5577:     unless ($nolog) {
1.567     raeburn  5578: # log the associated role with the area
1.1215    raeburn  5579:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5580:     }
1.743     albertel 5581:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5582: }
                   5583: 
                   5584: sub custom_roleprivs {
                   5585:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5586:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  5587:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5588:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5589:         my ($rdummy,$roledef)=
                   5590:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5591:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5592:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5593:             if (defined($syspriv)) {
1.1043    raeburn  5594:                 if ($trest =~ /^$match_community$/) {
                   5595:                     $syspriv =~ s/bre\&S//; 
                   5596:                 }
1.567     raeburn  5597:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5598:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5599:             }
                   5600:             if ($tdomain ne '') {
                   5601:                 if (defined($dompriv)) {
                   5602:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5603:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5604:                 }
                   5605:                 if (($trest ne '') && (defined($coursepriv))) {
                   5606:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5607:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5608:                 }
                   5609:             }
                   5610:         }
                   5611:     }
                   5612: }
                   5613: 
1.678     raeburn  5614: sub group_roleprivs {
                   5615:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5616:     my $access = 1;
                   5617:     my $now = time;
                   5618:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5619:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5620:     if ($access) {
1.811     albertel 5621:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5622:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5623:     }
                   5624: }
1.567     raeburn  5625: 
                   5626: sub standard_roleprivs {
                   5627:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5628:     if (defined($pr{$trole.':s'})) {
                   5629:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5630:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5631:     }
                   5632:     if ($tdomain ne '') {
                   5633:         if (defined($pr{$trole.':d'})) {
                   5634:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5635:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5636:         }
                   5637:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5638:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5639:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5640:         }
                   5641:     }
                   5642: }
                   5643: 
                   5644: sub set_userprivs {
1.1064    raeburn  5645:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5646:     my $author=0;
                   5647:     my $adv=0;
1.678     raeburn  5648:     my %grouproles = ();
                   5649:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5650:         my @groupkeys; 
1.1000    raeburn  5651:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5652:             push(@groupkeys,$role);
                   5653:         }
                   5654:         if (ref($groups_roles) eq 'HASH') {
                   5655:             foreach my $key (keys(%{$groups_roles})) {
                   5656:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5657:                     push(@groupkeys,$key);
                   5658:                 }
                   5659:             }
                   5660:         }
                   5661:         if (@groupkeys > 0) {
                   5662:             foreach my $role (@groupkeys) {
                   5663:                 my ($trole,$area,$sec,$extendedarea);
                   5664:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5665:                     $trole = $1;
                   5666:                     $area = $2;
                   5667:                     $sec = $3;
                   5668:                     $extendedarea = $area.$sec;
                   5669:                     if (exists($$allgroups{$area})) {
                   5670:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5671:                             my $spec = $trole.'.'.$extendedarea;
                   5672:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5673:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5674:                         }
1.678     raeburn  5675:                     }
                   5676:                 }
                   5677:             }
                   5678:         }
                   5679:     }
1.800     albertel 5680:     foreach my $group (keys(%grouproles)) {
                   5681:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5682:     }
1.800     albertel 5683:     foreach my $role (keys(%{$allroles})) {
                   5684:         my %thesepriv;
1.941     raeburn  5685:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5686:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5687:             if ($item ne '') {
                   5688:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5689:                 if ($restrictions eq '') {
                   5690:                     $thesepriv{$privilege}='F';
                   5691:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5692:                     $thesepriv{$privilege}.=$restrictions;
                   5693:                 }
                   5694:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5695:             }
                   5696:         }
                   5697:         my $thesestr='';
1.1104    raeburn  5698:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5699: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5700: 	}
                   5701:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5702:     }
                   5703:     return ($author,$adv);
                   5704: }
                   5705: 
1.994     raeburn  5706: sub role_status {
1.1104    raeburn  5707:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5708:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  5709:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5710:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5711:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  5712:             $$where = '/'.$two;
1.994     raeburn  5713:             $$trolecode=$$role.'.'.$$where;
                   5714:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5715:             $$tstatus='is';
1.1104    raeburn  5716:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5717:                 $$tstatus='future';
1.1034    raeburn  5718:                 if ($$tstart<$now) {
                   5719:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5720:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5721:                             my (%allroles,%allgroups,$group_privs,
                   5722:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5723:                             my %userroles = (
                   5724:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5725:                             );
1.1064    raeburn  5726:                             @rolecodes = ('cm'); 
1.1002    raeburn  5727:                             my $spec=$$role.'.'.$$where;
                   5728:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5729:                             if ($$role =~ /^cr\//) {
                   5730:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5731:                                 push(@rolecodes,'cr');
1.1002    raeburn  5732:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5733:                                 push(@rolecodes,$$role);
1.1002    raeburn  5734:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5735:                                                     $env{'user.name'});
1.1064    raeburn  5736:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5737:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5738:                                 $group_privs = &unescape($group_privs);
                   5739:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5740:                                 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  5741:                                 &get_groups_roles($tdomain,$trest,
                   5742:                                                   \%course_roles,\@rolecodes,
                   5743:                                                   \%groups_roles);
1.1002    raeburn  5744:                             } else {
1.1064    raeburn  5745:                                 push(@rolecodes,$$role);
1.1002    raeburn  5746:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5747:                             }
1.1064    raeburn  5748:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5749:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5750:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5751:                         }
                   5752:                     }
1.1034    raeburn  5753:                     $$tstatus = 'is';
1.1002    raeburn  5754:                 }
1.994     raeburn  5755:             }
                   5756:             if ($$tend) {
1.1104    raeburn  5757:                 if ($$tend<$update) {
1.994     raeburn  5758:                     $$tstatus='expired';
                   5759:                 } elsif ($$tend<$now) {
                   5760:                     $$tstatus='will_not';
                   5761:                 }
                   5762:             }
                   5763:         }
                   5764:     }
                   5765: }
                   5766: 
1.1104    raeburn  5767: sub get_groups_roles {
                   5768:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5769:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5770:                   (ref($rolecodes) eq 'ARRAY') && 
                   5771:                   (ref($groups_roles) eq 'HASH')); 
                   5772:     if (keys(%{$cdom_courseroles}) > 0) {
                   5773:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5774:         if ($cdom ne '' && $cnum ne '') {
                   5775:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5776:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5777:                     my $crsrole = $1;
                   5778:                     my $crssec = $2;
                   5779:                     if ($crsrole =~ /^cr/) {
                   5780:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5781:                             push(@{$rolecodes},'cr');
                   5782:                         }
                   5783:                     } else {
                   5784:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5785:                             push(@{$rolecodes},$crsrole);
                   5786:                         }
                   5787:                     }
                   5788:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5789:                     if ($crssec ne '') {
                   5790:                         $rolekey .= "/$crssec";
                   5791:                     }
                   5792:                     $rolekey .= './';
                   5793:                     $groups_roles->{$rolekey} = $rolecodes;
                   5794:                 }
                   5795:             }
                   5796:         }
                   5797:     }
                   5798:     return;
                   5799: }
                   5800: 
                   5801: sub delete_env_groupprivs {
                   5802:     my ($where,$courseroles,$possroles) = @_;
                   5803:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5804:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5805:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5806:         %{$courseroles->{$udom}} =
                   5807:             &get_my_roles('','','userroles',['active'],
                   5808:                           $possroles,[$udom],1);
                   5809:     }
                   5810:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5811:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5812:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5813:             my $area = '/'.$cdom.'/'.$cnum;
                   5814:             my $privkey = "user.priv.$crsrole.$area";
                   5815:             if ($crssec ne '') {
                   5816:                 $privkey .= '/'.$crssec;
                   5817:             }
                   5818:             $privkey .= ".$area/$group";
                   5819:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5820:         }
                   5821:     }
                   5822:     return;
                   5823: }
                   5824: 
1.994     raeburn  5825: sub check_adhoc_privs {
1.1104    raeburn  5826:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5827:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185    raeburn  5828:     my $setprivs;
1.994     raeburn  5829:     if ($env{$cckey}) {
                   5830:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5831:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5832:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5833:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5834:             $setprivs = 1;
1.994     raeburn  5835:         }
                   5836:     } else {
1.1088    raeburn  5837:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5838:         $setprivs = 1;
1.994     raeburn  5839:     }
1.1185    raeburn  5840:     return $setprivs;
1.994     raeburn  5841: }
                   5842: 
                   5843: sub set_adhoc_privileges {
                   5844: # role can be cc or ca
1.1088    raeburn  5845:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5846:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5847:     my $spec = $role.'.'.$area;
                   5848:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  5849:                                   $env{'user.name'},1);
1.994     raeburn  5850:     my %ccrole = ();
                   5851:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5852:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5853:     &appenv(\%userroles,[$role,'cm']);
                   5854:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5855:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5856:         &appenv( {'request.role'        => $spec,
                   5857:                   'request.role.domain' => $dcdom,
                   5858:                   'request.course.sec'  => ''
                   5859:                  }
                   5860:                );
                   5861:         my $tadv=0;
                   5862:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5863:         &appenv({'request.role.adv'    => $tadv});
                   5864:     }
1.994     raeburn  5865: }
                   5866: 
1.12      www      5867: # --------------------------------------------------------------- get interface
                   5868: 
                   5869: sub get {
1.131     albertel 5870:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5871:    my $items='';
1.800     albertel 5872:    foreach my $item (@$storearr) {
                   5873:        $items.=&escape($item).'&';
1.191     harris41 5874:    }
1.12      www      5875:    $items=~s/\&$//;
1.620     albertel 5876:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5877:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5878:    my $uhome=&homeserver($uname,$udomain);
                   5879: 
1.133     albertel 5880:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5881:    my @pairs=split(/\&/,$rep);
1.273     albertel 5882:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5883:      return @pairs;
                   5884:    }
1.15      www      5885:    my %returnhash=();
1.42      www      5886:    my $i=0;
1.800     albertel 5887:    foreach my $item (@$storearr) {
                   5888:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5889:       $i++;
1.191     harris41 5890:    }
1.15      www      5891:    return %returnhash;
1.27      www      5892: }
                   5893: 
                   5894: # --------------------------------------------------------------- del interface
                   5895: 
                   5896: sub del {
1.133     albertel 5897:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5898:    my $items='';
1.800     albertel 5899:    foreach my $item (@$storearr) {
                   5900:        $items.=&escape($item).'&';
1.191     harris41 5901:    }
1.984     neumanie 5902: 
1.27      www      5903:    $items=~s/\&$//;
1.620     albertel 5904:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5905:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5906:    my $uhome=&homeserver($uname,$udomain);
                   5907:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5908: }
                   5909: 
                   5910: # -------------------------------------------------------------- dump interface
                   5911: 
1.1180    droeschl 5912: sub unserialize {
                   5913:     my ($rep, $escapedkeys) = @_;
                   5914: 
                   5915:     return {} if $rep =~ /^error/;
                   5916: 
                   5917:     my %returnhash=();
1.1252    raeburn  5918: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 5919: 	    my ($key, $value) = split(/=/, $item, 2);
                   5920: 	    $key = unescape($key) unless $escapedkeys;
                   5921: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  5922: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 5923: 	}
                   5924:     #return %returnhash;
                   5925:     return \%returnhash;
                   5926: }        
                   5927: 
                   5928: # see Lond::dump_with_regexp
                   5929: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5930: sub dump {
1.1180    droeschl 5931:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5932:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5933:     if (!$uname) { $uname=$env{'user.name'}; }
                   5934:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5935: 
1.1266    raeburn  5936:     if ($regexp) {
                   5937:         $regexp=&escape($regexp);
                   5938:     } else {
                   5939:         $regexp='.';
                   5940:     }
1.1180    droeschl 5941:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   5942:         # user is hosted on this machine
1.1266    raeburn  5943:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  5944:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 5945:         return %{unserialize($reply, $escapedkeys)};
                   5946:     }
1.1166    raeburn  5947:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5948:     my @pairs=split(/\&/,$rep);
                   5949:     my %returnhash=();
1.1098    foxr     5950:     if (!($rep =~ /^error/ )) {
                   5951: 	foreach my $item (@pairs) {
                   5952: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 5953:         $key = unescape($key) unless $escapedkeys;
                   5954:         #$key = &unescape($key);
1.1098    foxr     5955: 	    next if ($key =~ /^error: 2 /);
                   5956: 	    $returnhash{$key}=&thaw_unescape($value);
                   5957: 	}
1.755     albertel 5958:     }
                   5959:     return %returnhash;
1.407     www      5960: }
                   5961: 
1.1098    foxr     5962: 
1.717     albertel 5963: # --------------------------------------------------------- dumpstore interface
                   5964: 
                   5965: sub dumpstore {
                   5966:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 5967:    # same as dump but keys must be escaped. They may contain colon separated
                   5968:    # lists of values that may themself contain colons (e.g. symbs).
                   5969:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5970: }
                   5971: 
1.407     www      5972: # -------------------------------------------------------------- keys interface
                   5973: 
                   5974: sub getkeys {
                   5975:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5976:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5977:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5978:    my $uhome=&homeserver($uname,$udomain);
                   5979:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5980:    my @keyarray=();
1.800     albertel 5981:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5982:       next if ($key =~ /^error: 2 /);
1.800     albertel 5983:       push(@keyarray,&unescape($key));
1.407     www      5984:    }
                   5985:    return @keyarray;
1.318     matthew  5986: }
                   5987: 
1.319     matthew  5988: # --------------------------------------------------------------- currentdump
                   5989: sub currentdump {
1.328     matthew  5990:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5991:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5992:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5993:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5994:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 5995:    my $rep;
                   5996: 
                   5997:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5998:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   5999:                    $courseid)));
                   6000:    } else {
                   6001:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6002:    }
                   6003: 
1.318     matthew  6004:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6005:    #
1.318     matthew  6006:    my %returnhash=();
1.319     matthew  6007:    #
                   6008:    if ($rep eq "unknown_cmd") { 
                   6009:        # an old lond will not know currentdump
                   6010:        # Do a dump and make it look like a currentdump
1.822     albertel 6011:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6012:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6013:        my %hash = @tmp;
                   6014:        @tmp=();
1.424     matthew  6015:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6016:    } else {
                   6017:        my @pairs=split(/\&/,$rep);
1.800     albertel 6018:        foreach my $pair (@pairs) {
                   6019:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6020:            my ($symb,$param) = split(/:/,$key);
                   6021:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6022:                                                         &thaw_unescape($value);
1.319     matthew  6023:        }
1.191     harris41 6024:    }
1.12      www      6025:    return %returnhash;
1.424     matthew  6026: }
                   6027: 
                   6028: sub convert_dump_to_currentdump{
                   6029:     my %hash = %{shift()};
                   6030:     my %returnhash;
                   6031:     # Code ripped from lond, essentially.  The only difference
                   6032:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6033:     # we might run in to problems with parameter names =~ /^v\./
                   6034:     while (my ($key,$value) = each(%hash)) {
                   6035:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6036: 	$symb  = &unescape($symb);
                   6037: 	$param = &unescape($param);
1.424     matthew  6038:         next if ($v eq 'version' || $symb eq 'keys');
                   6039:         next if (exists($returnhash{$symb}) &&
                   6040:                  exists($returnhash{$symb}->{$param}) &&
                   6041:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6042:         $returnhash{$symb}->{$param}=$value;
                   6043:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6044:     }
                   6045:     #
                   6046:     # Remove all of the keys in the hashes which keep track of
                   6047:     # the version of the parameter.
                   6048:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6049:         # use a foreach because we are going to delete from the hash.
                   6050:         foreach my $key (keys(%$param_hash)) {
                   6051:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6052:         }
                   6053:     }
                   6054:     return \%returnhash;
1.12      www      6055: }
                   6056: 
1.627     albertel 6057: # ------------------------------------------------------ critical inc interface
                   6058: 
                   6059: sub cinc {
                   6060:     return &inc(@_,'critical');
                   6061: }
                   6062: 
1.449     matthew  6063: # --------------------------------------------------------------- inc interface
                   6064: 
                   6065: sub inc {
1.627     albertel 6066:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6067:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6068:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6069:     my $uhome=&homeserver($uname,$udomain);
                   6070:     my $items='';
                   6071:     if (! ref($store)) {
                   6072:         # got a single value, so use that instead
                   6073:         $items = &escape($store).'=&';
                   6074:     } elsif (ref($store) eq 'SCALAR') {
                   6075:         $items = &escape($$store).'=&';        
                   6076:     } elsif (ref($store) eq 'ARRAY') {
                   6077:         $items = join('=&',map {&escape($_);} @{$store});
                   6078:     } elsif (ref($store) eq 'HASH') {
                   6079:         while (my($key,$value) = each(%{$store})) {
                   6080:             $items.= &escape($key).'='.&escape($value).'&';
                   6081:         }
                   6082:     }
                   6083:     $items=~s/\&$//;
1.627     albertel 6084:     if ($critical) {
                   6085: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6086:     } else {
                   6087: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6088:     }
1.449     matthew  6089: }
                   6090: 
1.12      www      6091: # --------------------------------------------------------------- put interface
                   6092: 
                   6093: sub put {
1.134     albertel 6094:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6095:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6096:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6097:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6098:    my $items='';
1.800     albertel 6099:    foreach my $item (keys(%$storehash)) {
                   6100:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6101:    }
1.12      www      6102:    $items=~s/\&$//;
1.134     albertel 6103:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6104: }
                   6105: 
1.631     albertel 6106: # ------------------------------------------------------------ newput interface
                   6107: 
                   6108: sub newput {
                   6109:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6110:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6111:    if (!$uname) { $uname=$env{'user.name'}; }
                   6112:    my $uhome=&homeserver($uname,$udomain);
                   6113:    my $items='';
                   6114:    foreach my $key (keys(%$storehash)) {
                   6115:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6116:    }
                   6117:    $items=~s/\&$//;
                   6118:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6119: }
                   6120: 
                   6121: # ---------------------------------------------------------  putstore interface
                   6122: 
1.524     raeburn  6123: sub putstore {
1.1269    raeburn  6124:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6125:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6126:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6127:    my $uhome=&homeserver($uname,$udomain);
                   6128:    my $items='';
1.715     albertel 6129:    foreach my $key (keys(%$storehash)) {
                   6130:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6131:    }
1.715     albertel 6132:    $items=~s/\&$//;
1.716     albertel 6133:    my $esc_symb=&escape($symb);
                   6134:    my $esc_v=&escape($version);
1.715     albertel 6135:    my $reply =
1.716     albertel 6136:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6137: 	      $uhome);
1.1269    raeburn  6138:    if (($tolog) && ($reply eq 'ok')) {
                   6139:        my $namevalue='';
                   6140:        foreach my $key (keys(%{$storehash})) {
                   6141:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6142:        }
                   6143:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6144:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6145:                      '&version='.$esc_v.
                   6146:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6147:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6148:    }
1.715     albertel 6149:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6150:        # gfall back to way things use to be done
1.715     albertel 6151:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6152: 			    $uname);
1.524     raeburn  6153:    }
1.715     albertel 6154:    return $reply;
                   6155: }
                   6156: 
                   6157: sub old_putstore {
1.716     albertel 6158:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6159:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6160:     if (!$uname) { $uname=$env{'user.name'}; }
                   6161:     my $uhome=&homeserver($uname,$udomain);
                   6162:     my %newstorehash;
1.800     albertel 6163:     foreach my $item (keys(%$storehash)) {
                   6164: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6165: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6166:     }
                   6167:     my $items='';
                   6168:     my %allitems = ();
1.800     albertel 6169:     foreach my $item (keys(%newstorehash)) {
                   6170: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6171: 	    my $key = $1.':keys:'.$2;
                   6172: 	    $allitems{$key} .= $3.':';
                   6173: 	}
1.800     albertel 6174: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6175:     }
1.800     albertel 6176:     foreach my $item (keys(%allitems)) {
                   6177: 	$allitems{$item} =~ s/\:$//;
                   6178: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6179:     }
                   6180:     $items=~s/\&$//;
                   6181:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6182: }
                   6183: 
1.47      www      6184: # ------------------------------------------------------ critical put interface
                   6185: 
                   6186: sub cput {
1.134     albertel 6187:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6188:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6189:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6190:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6191:    my $items='';
1.800     albertel 6192:    foreach my $item (keys(%$storehash)) {
                   6193:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6194:    }
1.47      www      6195:    $items=~s/\&$//;
1.134     albertel 6196:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6197: }
                   6198: 
                   6199: # -------------------------------------------------------------- eget interface
                   6200: 
                   6201: sub eget {
1.133     albertel 6202:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6203:    my $items='';
1.800     albertel 6204:    foreach my $item (@$storearr) {
                   6205:        $items.=&escape($item).'&';
1.191     harris41 6206:    }
1.12      www      6207:    $items=~s/\&$//;
1.620     albertel 6208:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6209:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6210:    my $uhome=&homeserver($uname,$udomain);
                   6211:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6212:    my @pairs=split(/\&/,$rep);
                   6213:    my %returnhash=();
1.42      www      6214:    my $i=0;
1.800     albertel 6215:    foreach my $item (@$storearr) {
                   6216:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6217:       $i++;
1.191     harris41 6218:    }
1.12      www      6219:    return %returnhash;
                   6220: }
                   6221: 
1.667     albertel 6222: # ------------------------------------------------------------ tmpput interface
                   6223: sub tmpput {
1.802     raeburn  6224:     my ($storehash,$server,$context)=@_;
1.667     albertel 6225:     my $items='';
1.800     albertel 6226:     foreach my $item (keys(%$storehash)) {
                   6227: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6228:     }
                   6229:     $items=~s/\&$//;
1.802     raeburn  6230:     if (defined($context)) {
                   6231:         $items .= ':'.&escape($context);
                   6232:     }
1.667     albertel 6233:     return &reply("tmpput:$items",$server);
                   6234: }
                   6235: 
                   6236: # ------------------------------------------------------------ tmpget interface
                   6237: sub tmpget {
1.688     albertel 6238:     my ($token,$server)=@_;
                   6239:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6240:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6241:     my %returnhash;
                   6242:     foreach my $item (split(/\&/,$rep)) {
                   6243: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  6244:         next if ($key =~ /^error: 2 /);
1.667     albertel 6245: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6246:     }
                   6247:     return %returnhash;
                   6248: }
                   6249: 
1.1113    raeburn  6250: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6251: sub tmpdel {
                   6252:     my ($token,$server)=@_;
                   6253:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6254:     return &reply("tmpdel:$token",$server);
                   6255: }
                   6256: 
1.1198    raeburn  6257: # ------------------------------------------------------------ get_timebased_id 
                   6258: 
                   6259: sub get_timebased_id {
                   6260:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6261:         $maxtries) = @_;
                   6262:     my ($newid,$error,$dellock);
                   6263:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   6264:         return ('','ok','invalid call to get suffix');
                   6265:     }
                   6266: 
                   6267: # set defaults for any optional args for which values were not supplied
                   6268:     if ($who eq '') {
                   6269:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6270:     }
                   6271:     if (!$locktries) {
                   6272:         $locktries = 3;
                   6273:     }
                   6274:     if (!$maxtries) {
                   6275:         $maxtries = 10;
                   6276:     }
                   6277:     
                   6278:     if (($cdom eq '') || ($cnum eq '')) {
                   6279:         if ($env{'request.course.id'}) {
                   6280:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6281:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6282:         }
                   6283:         if (($cdom eq '') || ($cnum eq '')) {
                   6284:             return ('','ok','call to get suffix not in course context');
                   6285:         }
                   6286:     }
                   6287: 
                   6288: # construct locking item
                   6289:     my $lockhash = {
                   6290:                       $prefix."\0".'locked_'.$keyid => $who,
                   6291:                    };
                   6292:     my $tries = 0;
                   6293: 
                   6294: # attempt to get lock on nohist_$namespace file
                   6295:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6296:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6297:         $tries ++;
                   6298:         sleep 1;
                   6299:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6300:     }
                   6301: 
                   6302: # attempt to get unique identifier, based on current timestamp
                   6303:     if ($gotlock eq 'ok') {
                   6304:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6305:         my $id = time;
                   6306:         $newid = $id;
1.1268    raeburn  6307:         if ($idtype eq 'addcode') {
                   6308:             $newid .= &sixnum_code();
                   6309:         }
1.1198    raeburn  6310:         my $idtries = 0;
                   6311:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6312:             if ($idtype eq 'concat') {
                   6313:                 $newid = $id.$idtries;
1.1268    raeburn  6314:             } elsif ($idtype eq 'addcode') {
                   6315:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6316:             } else {
                   6317:                 $newid ++;
                   6318:             }
                   6319:             $idtries ++;
                   6320:         }
                   6321:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6322:             my %new_item =  (
                   6323:                               $prefix."\0".$newid => $who,
                   6324:                             );
                   6325:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6326:                                                  $cdom,$cnum);
                   6327:             if ($putresult ne 'ok') {
                   6328:                 undef($newid);
                   6329:                 $error = 'error saving new item: '.$putresult;
                   6330:             }
                   6331:         } else {
1.1268    raeburn  6332:              undef($newid);
1.1198    raeburn  6333:              $error = ('error: no unique suffix available for the new item ');
                   6334:         }
                   6335: #  remove lock
                   6336:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6337:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6338:     } else {
                   6339:         $error = "error: could not obtain lockfile\n";
                   6340:         $dellock = 'ok';
1.1276    raeburn  6341:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6342:             $dellock = 'nolock';
                   6343:         }
1.1198    raeburn  6344:     }
                   6345:     return ($newid,$dellock,$error);
                   6346: }
                   6347: 
1.1268    raeburn  6348: sub sixnum_code {
                   6349:     my $code;
                   6350:     for (0..6) {
                   6351:         $code .= int( rand(9) );
                   6352:     }
                   6353:     return $code;
                   6354: }
                   6355: 
1.765     albertel 6356: # -------------------------------------------------- portfolio access checking
                   6357: 
                   6358: sub portfolio_access {
1.1270    raeburn  6359:     my ($requrl,$clientip) = @_;
1.765     albertel 6360:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  6361:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6362:     if ($result) {
                   6363:         my %setters;
                   6364:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6365:             my ($startblock,$endblock) =
                   6366:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6367:             if ($startblock && $endblock) {
                   6368:                 return 'B';
                   6369:             }
                   6370:         } else {
                   6371:             my ($startblock,$endblock) =
                   6372:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6373:             if ($startblock && $endblock) {
                   6374:                 return 'B';
                   6375:             }
                   6376:         }
                   6377:     }
1.765     albertel 6378:     if ($result eq 'ok') {
1.766     albertel 6379:        return 'F';
1.765     albertel 6380:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6381:        return 'A';
1.765     albertel 6382:     }
1.766     albertel 6383:     return '';
1.765     albertel 6384: }
                   6385: 
                   6386: sub get_portfolio_access {
1.1270    raeburn  6387:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6388: 
                   6389:     if (!ref($access_hash)) {
                   6390: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6391: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6392: 						   $file_name);
                   6393: 	$access_hash = $access_controls{$file_name};
                   6394:     }
                   6395: 
1.1270    raeburn  6396:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6397:     my $now = time;
                   6398:     if (ref($access_hash) eq 'HASH') {
                   6399:         foreach my $key (keys(%{$access_hash})) {
                   6400:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6401:             if ($start > $now) {
                   6402:                 next;
                   6403:             }
                   6404:             if ($end && $end<$now) {
                   6405:                 next;
                   6406:             }
                   6407:             if ($scope eq 'public') {
                   6408:                 $public = $key;
                   6409:                 last;
                   6410:             } elsif ($scope eq 'guest') {
                   6411:                 $guest = $key;
                   6412:             } elsif ($scope eq 'domains') {
                   6413:                 push(@domains,$key);
                   6414:             } elsif ($scope eq 'users') {
                   6415:                 push(@users,$key);
                   6416:             } elsif ($scope eq 'course') {
                   6417:                 push(@courses,$key);
                   6418:             } elsif ($scope eq 'group') {
                   6419:                 push(@groups,$key);
1.1270    raeburn  6420:             } elsif ($scope eq 'ip') {
                   6421:                 push(@ips,$key);
1.765     albertel 6422:             }
                   6423:         }
                   6424:         if ($public) {
                   6425:             return 'ok';
1.1270    raeburn  6426:         } elsif (@ips > 0) {
                   6427:             my $allowed;
                   6428:             foreach my $ipkey (@ips) {
                   6429:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6430:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6431:                         $allowed = 1;
                   6432:                         last; 
                   6433:                     }
                   6434:                 }
                   6435:             }
                   6436:             if ($allowed) {
                   6437:                 return 'ok';
                   6438:             }
1.765     albertel 6439:         }
                   6440:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6441:             if ($guest) {
                   6442:                 return $guest;
                   6443:             }
                   6444:         } else {
                   6445:             if (@domains > 0) {
                   6446:                 foreach my $domkey (@domains) {
                   6447:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6448:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6449:                             return 'ok';
                   6450:                         }
                   6451:                     }
                   6452:                 }
                   6453:             }
                   6454:             if (@users > 0) {
                   6455:                 foreach my $userkey (@users) {
1.865     raeburn  6456:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6457:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6458:                             if (ref($item) eq 'HASH') {
                   6459:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6460:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6461:                                     return 'ok';
                   6462:                                 }
                   6463:                             }
                   6464:                         }
                   6465:                     } 
1.765     albertel 6466:                 }
                   6467:             }
                   6468:             my %roleshash;
                   6469:             my @courses_and_groups = @courses;
                   6470:             push(@courses_and_groups,@groups); 
                   6471:             if (@courses_and_groups > 0) {
                   6472:                 my (%allgroups,%allroles); 
                   6473:                 my ($start,$end,$role,$sec,$group);
                   6474:                 foreach my $envkey (%env) {
1.1060    raeburn  6475:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6476:                         my $cid = $2.'_'.$3; 
                   6477:                         if ($1 eq 'gr') {
                   6478:                             $group = $4;
                   6479:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6480:                         } else {
                   6481:                             if ($4 eq '') {
                   6482:                                 $sec = 'none';
                   6483:                             } else {
                   6484:                                 $sec = $4;
                   6485:                             }
                   6486:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6487:                         }
1.811     albertel 6488:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6489:                         my $cid = $2.'_'.$3;
                   6490:                         if ($4 eq '') {
                   6491:                             $sec = 'none';
                   6492:                         } else {
                   6493:                             $sec = $4;
                   6494:                         }
                   6495:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6496:                     }
                   6497:                 }
                   6498:                 if (keys(%allroles) == 0) {
                   6499:                     return;
                   6500:                 }
                   6501:                 foreach my $key (@courses_and_groups) {
                   6502:                     my %content = %{$$access_hash{$key}};
                   6503:                     my $cnum = $content{'number'};
                   6504:                     my $cdom = $content{'domain'};
                   6505:                     my $cid = $cdom.'_'.$cnum;
                   6506:                     if (!exists($allroles{$cid})) {
                   6507:                         next;
                   6508:                     }    
                   6509:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6510:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6511:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6512:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6513:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6514:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6515:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6516:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6517:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6518:                                         if (grep/^all$/,@sections) {
                   6519:                                             return 'ok';
                   6520:                                         } else {
                   6521:                                             if (grep/^$sec$/,@sections) {
                   6522:                                                 return 'ok';
                   6523:                                             }
                   6524:                                         }
                   6525:                                     }
                   6526:                                 }
                   6527:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6528:                                     if (grep/^none$/,@groups) {
                   6529:                                         return 'ok';
                   6530:                                     }
                   6531:                                 } else {
                   6532:                                     if (grep/^all$/,@groups) {
                   6533:                                         return 'ok';
                   6534:                                     } 
                   6535:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6536:                                         if (grep/^$group$/,@groups) {
                   6537:                                             return 'ok';
                   6538:                                         }
                   6539:                                     }
                   6540:                                 } 
                   6541:                             }
                   6542:                         }
                   6543:                     }
                   6544:                 }
                   6545:             }
                   6546:             if ($guest) {
                   6547:                 return $guest;
                   6548:             }
                   6549:         }
                   6550:     }
                   6551:     return;
                   6552: }
                   6553: 
                   6554: sub course_group_datechecker {
                   6555:     my ($dates,$now,$status) = @_;
                   6556:     my ($start,$end) = split(/\./,$dates);
                   6557:     if (!$start && !$end) {
                   6558:         return 'ok';
                   6559:     }
                   6560:     if (grep/^active$/,@{$status}) {
                   6561:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6562:             return 'ok';
                   6563:         }
                   6564:     }
                   6565:     if (grep/^previous$/,@{$status}) {
                   6566:         if ($end > $now ) {
                   6567:             return 'ok';
                   6568:         }
                   6569:     }
                   6570:     if (grep/^future$/,@{$status}) {
                   6571:         if ($start > $now) {
                   6572:             return 'ok';
                   6573:         }
                   6574:     }
                   6575:     return; 
                   6576: }
                   6577: 
                   6578: sub parse_portfolio_url {
                   6579:     my ($url) = @_;
                   6580: 
                   6581:     my ($type,$udom,$unum,$group,$file_name);
                   6582:     
1.823     albertel 6583:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6584: 	$type = 1;
                   6585:         $udom = $1;
                   6586:         $unum = $2;
                   6587:         $file_name = $3;
1.823     albertel 6588:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6589: 	$type = 2;
                   6590:         $udom = $1;
                   6591:         $unum = $2;
                   6592:         $group = $3;
                   6593:         $file_name = $3.'/'.$4;
                   6594:     }
                   6595:     if (wantarray) {
                   6596: 	return ($type,$udom,$unum,$file_name,$group);
                   6597:     }
                   6598:     return $type;
                   6599: }
                   6600: 
                   6601: sub is_portfolio_url {
                   6602:     my ($url) = @_;
                   6603:     return scalar(&parse_portfolio_url($url));
                   6604: }
                   6605: 
1.798     raeburn  6606: sub is_portfolio_file {
                   6607:     my ($file) = @_;
1.820     raeburn  6608:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6609:         return 1;
                   6610:     }
                   6611:     return;
                   6612: }
                   6613: 
1.976     raeburn  6614: sub usertools_access {
1.1084    raeburn  6615:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6616:     my ($access,%tools);
                   6617:     if ($context eq '') {
                   6618:         $context = 'tools';
                   6619:     }
                   6620:     if ($context eq 'requestcourses') {
                   6621:         %tools = (
                   6622:                       official   => 1,
                   6623:                       unofficial => 1,
1.1006    raeburn  6624:                       community  => 1,
1.1246    raeburn  6625:                       textbook   => 1,
1.1305    raeburn  6626:                       placement  => 1,
1.985     raeburn  6627:                  );
1.1183    raeburn  6628:     } elsif ($context eq 'requestauthor') {
                   6629:         %tools = (
                   6630:                       requestauthor => 1,
                   6631:                  );
1.985     raeburn  6632:     } else {
                   6633:         %tools = (
                   6634:                       aboutme   => 1,
                   6635:                       blog      => 1,
1.1177    raeburn  6636:                       webdav    => 1,
1.985     raeburn  6637:                       portfolio => 1,
                   6638:                  );
                   6639:     }
1.976     raeburn  6640:     return if (!defined($tools{$tool}));
                   6641: 
1.1242    raeburn  6642:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6643:         $udom = $env{'user.domain'};
                   6644:         $uname = $env{'user.name'};
                   6645:     }
                   6646: 
1.978     raeburn  6647:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6648:         if ($action ne 'reload') {
1.985     raeburn  6649:             if ($context eq 'requestcourses') {
                   6650:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  6651:             } elsif ($context eq 'requestauthor') {
                   6652:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6653:             } else {
                   6654:                 return $env{'environment.availabletools.'.$tool};
                   6655:             }
                   6656:         }
1.976     raeburn  6657:     }
                   6658: 
1.1183    raeburn  6659:     my ($toolstatus,$inststatus,$envkey);
                   6660:     if ($context eq 'requestauthor') {
                   6661:         $envkey = $context; 
                   6662:     } else {
                   6663:         $envkey = $context.'.'.$tool;
                   6664:     }
1.976     raeburn  6665: 
1.985     raeburn  6666:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6667:          ($action ne 'reload')) {
1.1183    raeburn  6668:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6669:         $inststatus = $env{'environment.inststatus'};
                   6670:     } else {
1.1084    raeburn  6671:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  6672:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6673:             $inststatus = $userenvref->{'inststatus'};
                   6674:         } else {
1.1183    raeburn  6675:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6676:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6677:             $inststatus = $userenv{'inststatus'};
                   6678:         }
1.976     raeburn  6679:     }
                   6680: 
                   6681:     if ($toolstatus ne '') {
                   6682:         if ($toolstatus) {
                   6683:             $access = 1;
                   6684:         } else {
                   6685:             $access = 0;
                   6686:         }
                   6687:         return $access;
                   6688:     }
                   6689: 
1.1084    raeburn  6690:     my ($is_adv,%domdef);
                   6691:     if (ref($is_advref) eq 'HASH') {
                   6692:         $is_adv = $is_advref->{'is_adv'};
                   6693:     } else {
                   6694:         $is_adv = &is_advanced_user($udom,$uname);
                   6695:     }
                   6696:     if (ref($domdefref) eq 'HASH') {
                   6697:         %domdef = %{$domdefref};
                   6698:     } else {
                   6699:         %domdef = &get_domain_defaults($udom);
                   6700:     }
1.976     raeburn  6701:     if (ref($domdef{$tool}) eq 'HASH') {
                   6702:         if ($is_adv) {
                   6703:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6704:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6705:                     $access = 1;
                   6706:                 } else {
                   6707:                     $access = 0;
                   6708:                 }
                   6709:                 return $access;
                   6710:             }
                   6711:         }
                   6712:         if ($inststatus ne '') {
                   6713:             my ($hasaccess,$hasnoaccess);
                   6714:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6715:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6716:                     if ($domdef{$tool}{$affiliation}) {
                   6717:                         $hasaccess = 1;
                   6718:                     } else {
                   6719:                         $hasnoaccess = 1;
                   6720:                     }
                   6721:                 }
                   6722:             }
                   6723:             if ($hasaccess || $hasnoaccess) {
                   6724:                 if ($hasaccess) {
                   6725:                     $access = 1;
                   6726:                 } elsif ($hasnoaccess) {
                   6727:                     $access = 0; 
                   6728:                 }
                   6729:                 return $access;
                   6730:             }
                   6731:         } else {
                   6732:             if ($domdef{$tool}{'default'} ne '') {
                   6733:                 if ($domdef{$tool}{'default'}) {
                   6734:                     $access = 1;
                   6735:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6736:                     $access = 0;
                   6737:                 }
                   6738:                 return $access;
                   6739:             }
                   6740:         }
                   6741:     } else {
1.1177    raeburn  6742:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6743:             $access = 1;
                   6744:         } else {
                   6745:             $access = 0;
                   6746:         }
1.976     raeburn  6747:         return $access;
                   6748:     }
                   6749: }
                   6750: 
1.1050    raeburn  6751: sub is_course_owner {
                   6752:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6753:     if (($udom eq '') || ($uname eq '')) {
                   6754:         $udom = $env{'user.domain'};
                   6755:         $uname = $env{'user.name'};
                   6756:     }
                   6757:     unless (($udom eq '') || ($uname eq '')) {
                   6758:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6759:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6760:                 return 1;
                   6761:             } else {
                   6762:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6763:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6764:                     return 1;
                   6765:                 }
                   6766:             }
                   6767:         }
                   6768:     }
                   6769:     return;
                   6770: }
                   6771: 
1.976     raeburn  6772: sub is_advanced_user {
                   6773:     my ($udom,$uname) = @_;
1.1085    raeburn  6774:     if ($udom ne '' && $uname ne '') {
                   6775:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6776:             if (wantarray) {
                   6777:                 return ($env{'user.adv'},$env{'user.author'});
                   6778:             } else {
                   6779:                 return $env{'user.adv'};
                   6780:             }
1.1085    raeburn  6781:         }
                   6782:     }
1.976     raeburn  6783:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6784:     my %allroles;
1.1128    raeburn  6785:     my ($is_adv,$is_author);
1.976     raeburn  6786:     foreach my $role (keys(%roleshash)) {
                   6787:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6788:         my $area = '/'.$tdomain.'/'.$trest;
                   6789:         if ($sec ne '') {
                   6790:             $area .= '/'.$sec;
                   6791:         }
                   6792:         if (($area ne '') && ($trole ne '')) {
                   6793:             my $spec=$trole.'.'.$area;
                   6794:             if ($trole =~ /^cr\//) {
                   6795:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6796:             } elsif ($trole ne 'gr') {
                   6797:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6798:             }
1.1128    raeburn  6799:             if ($trole eq 'au') {
                   6800:                 $is_author = 1;
                   6801:             }
1.976     raeburn  6802:         }
                   6803:     }
                   6804:     foreach my $role (keys(%allroles)) {
                   6805:         last if ($is_adv);
                   6806:         foreach my $item (split(/:/,$allroles{$role})) {
                   6807:             if ($item ne '') {
                   6808:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6809:                 if ($privilege eq 'adv') {
                   6810:                     $is_adv = 1;
                   6811:                     last;
                   6812:                 }
                   6813:             }
                   6814:         }
                   6815:     }
1.1128    raeburn  6816:     if (wantarray) {
                   6817:         return ($is_adv,$is_author);
                   6818:     }
1.976     raeburn  6819:     return $is_adv;
                   6820: }
1.798     raeburn  6821: 
1.1035    raeburn  6822: sub check_can_request {
1.1036    raeburn  6823:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6824:     my $canreq = 0;
                   6825:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6826:     my @options = ('approval','validate','autolimit');
                   6827:     my $optregex = join('|',@options);
                   6828:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6829:         foreach my $type (@{$types}) {
                   6830:             if (&usertools_access($env{'user.name'},
                   6831:                                   $env{'user.domain'},
                   6832:                                   $type,undef,'requestcourses')) {
                   6833:                 $canreq ++;
1.1036    raeburn  6834:                 if (ref($request_domains) eq 'HASH') {
                   6835:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6836:                 }
1.1035    raeburn  6837:                 if ($dom eq $env{'user.domain'}) {
                   6838:                     $can_request->{$type} = 1;
                   6839:                 }
                   6840:             }
                   6841:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6842:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6843:                 if (@curr > 0) {
1.1036    raeburn  6844:                     foreach my $item (@curr) {
                   6845:                         if (ref($request_domains) eq 'HASH') {
                   6846:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6847:                             if ($otherdom ne '') {
                   6848:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6849:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6850:                                         push(@{$request_domains->{$type}},$otherdom);
                   6851:                                     }
                   6852:                                 } else {
                   6853:                                     push(@{$request_domains->{$type}},$otherdom);
                   6854:                                 }
                   6855:                             }
                   6856:                         }
                   6857:                     }
                   6858:                     unless($dom eq $env{'user.domain'}) {
                   6859:                         $canreq ++;
1.1035    raeburn  6860:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6861:                             $can_request->{$type} = 1;
                   6862:                         }
                   6863:                     }
                   6864:                 }
                   6865:             }
                   6866:         }
                   6867:     }
                   6868:     return $canreq;
                   6869: }
                   6870: 
1.341     www      6871: # ---------------------------------------------- Custom access rule evaluation
                   6872: 
                   6873: sub customaccess {
                   6874:     my ($priv,$uri)=@_;
1.807     albertel 6875:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6876:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6877:     $udom = &LONCAPA::clean_domain($udom);
                   6878:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6879:     my $access=0;
1.800     albertel 6880:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6881: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6882: 	if ($type eq 'user') {
                   6883: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6884: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6885: 		if ($tdom) {
                   6886: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6887: 		}
1.896     albertel 6888: 		if ($tuname) {
                   6889: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6890: 		}
                   6891: 		$access=($effect eq 'allow');
                   6892: 		last;
                   6893: 	    }
                   6894: 	} else {
                   6895: 	    if ($role) {
                   6896: 		if ($role ne $urole) { next; }
                   6897: 	    }
                   6898: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6899: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6900: 		if ($tdom) {
                   6901: 		    if ($tdom ne $udom) { next; }
                   6902: 		}
                   6903: 		if ($tcrs) {
                   6904: 		    if ($tcrs ne $ucrs) { next; }
                   6905: 		}
                   6906: 		if ($tsec) {
                   6907: 		    if ($tsec ne $usec) { next; }
                   6908: 		}
                   6909: 		$access=($effect eq 'allow');
                   6910: 		last;
                   6911: 	    }
                   6912: 	    if ($realm eq '' && $role eq '') {
                   6913: 		$access=($effect eq 'allow');
                   6914: 	    }
1.402     bowersj2 6915: 	}
1.341     www      6916:     }
                   6917:     return $access;
                   6918: }
                   6919: 
1.103     harris41 6920: # ------------------------------------------------- Check for a user privilege
1.12      www      6921: 
                   6922: sub allowed {
1.1281    raeburn  6923:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 6924:     my $ver_orguri=$uri;
1.439     www      6925:     $uri=&deversion($uri);
1.152     www      6926:     my $orguri=$uri;
1.52      www      6927:     $uri=&declutter($uri);
1.809     raeburn  6928: 
1.810     raeburn  6929:     if ($priv eq 'evb') {
                   6930: # Evade communication block restrictions for specified role in a course
                   6931:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6932:             return $1;
                   6933:         } else {
                   6934:             return;
                   6935:         }
                   6936:     }
                   6937: 
1.620     albertel 6938:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6939: # Free bre access to adm and meta resources
1.775     albertel 6940:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6941: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6942: 	&& ($priv eq 'bre')) {
1.14      www      6943: 	return 'F';
1.159     www      6944:     }
                   6945: 
1.545     banghart 6946: # Free bre access to user's own portfolio contents
1.714     raeburn  6947:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6948:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6949: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6950:         my %setters;
                   6951:         my ($startblock,$endblock) = 
                   6952:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6953:         if ($startblock && $endblock) {
                   6954:             return 'B';
                   6955:         } else {
                   6956:             return 'F';
                   6957:         }
1.545     banghart 6958:     }
                   6959: 
1.762     raeburn  6960: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6961:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6962:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6963:         if (exists($env{'request.course.id'})) {
                   6964:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6965:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6966:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6967:                 my $courseprivid=$env{'request.course.id'};
                   6968:                 $courseprivid=~s/\_/\//;
                   6969:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6970:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6971:                     return $1; 
1.762     raeburn  6972:                 } else {
                   6973:                     if ($env{'request.course.sec'}) {
                   6974:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6975:                     }
                   6976:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6977:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6978:                         return $2;
                   6979:                     }
1.714     raeburn  6980:                 }
                   6981:             }
                   6982:         }
                   6983:     }
                   6984: 
1.159     www      6985: # Free bre to public access
                   6986: 
                   6987:     if ($priv eq 'bre') {
1.238     www      6988:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6989: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6990:            return 'F'; 
                   6991:         }
1.238     www      6992:         if ($copyright eq 'priv') {
                   6993:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6994: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6995: 		return '';
                   6996:             }
                   6997:         }
                   6998:         if ($copyright eq 'domain') {
                   6999:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7000: 	    unless (($env{'user.domain'} eq $1) ||
                   7001:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7002: 		return '';
                   7003:             }
1.262     matthew  7004:         }
1.620     albertel 7005:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7006:             # Library role, so allow browsing of resources in this domain.
                   7007:             return 'F';
1.238     www      7008:         }
1.341     www      7009:         if ($copyright eq 'custom') {
                   7010: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7011:         }
1.14      www      7012:     }
1.264     matthew  7013:     # Domain coordinator is trying to create a course
1.620     albertel 7014:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7015:         # uri is the requested domain in this case.
                   7016:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7017:         # a role of dc for the domain in question.
1.620     albertel 7018:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7019:     }
1.29      www      7020: 
1.52      www      7021:     my $thisallowed='';
                   7022:     my $statecond=0;
                   7023:     my $courseprivid='';
                   7024: 
1.1039    raeburn  7025:     my $ownaccess;
1.1043    raeburn  7026:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7027:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7028:         if ($uri eq '') {
                   7029:             $ownaccess = 1;
                   7030:         } else {
                   7031:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7032:                 my $udom = $env{'user.domain'};
                   7033:                 my $uname = $env{'user.name'};
                   7034:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7035:                     $ownaccess = 1;
1.1040    raeburn  7036:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7037:                     unless ($uri =~ m{\.\./}) {
                   7038:                         $ownaccess = 1;
                   7039:                     }
                   7040:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7041:                     my $now = time;
                   7042:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7043:                         my $adom = $1;
                   7044:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7045:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7046:                                 my ($start,$end) = split('.',$env{$key});
                   7047:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7048:                                     $ownaccess = 1;
                   7049:                                     last;
                   7050:                                 }
                   7051:                             }
                   7052:                         }
                   7053:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7054:                         my $adom = $1;
                   7055:                         my $aname = $2;
1.1042    raeburn  7056:                         foreach my $role ('ca','aa') { 
                   7057:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7058:                                 my ($start,$end) =
                   7059:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7060:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7061:                                     $ownaccess = 1;
                   7062:                                     last;
                   7063:                                 }
1.1039    raeburn  7064:                             }
                   7065:                         }
                   7066:                     }
                   7067:                 }
                   7068:             }
                   7069:         }
                   7070:     }
                   7071: 
1.52      www      7072: # Course
                   7073: 
1.620     albertel 7074:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7075:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7076:             $thisallowed.=$1;
                   7077:         }
1.52      www      7078:     }
1.29      www      7079: 
1.52      www      7080: # Domain
                   7081: 
1.620     albertel 7082:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7083:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7084:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7085:             $thisallowed.=$1;
                   7086:         }
1.12      www      7087:     }
1.52      www      7088: 
1.1141    raeburn  7089: # User who is not author or co-author might still be able to edit
                   7090: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7091:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7092:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7093:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7094:             $thisallowed.=$1;
                   7095:         }
                   7096:     }
                   7097: 
1.52      www      7098: # Course: uri itself is a course
1.66      www      7099:     my $courseuri=$uri;
                   7100:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7101:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7102: 
1.620     albertel 7103:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7104:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7105:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7106:             $thisallowed.=$1;
                   7107:         }
1.12      www      7108:     }
1.29      www      7109: 
1.665     albertel 7110: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7111: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7112:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7113: 	$thisallowed='';
1.671     raeburn  7114:         my ($match)=&is_on_map($uri);
                   7115:         if ($match) {
                   7116:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7117:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  7118:                 my $value = $1;
                   7119:                 if ($noblockcheck) {
                   7120:                     $thisallowed.=$value;
1.1162    raeburn  7121:                 } else {
1.1281    raeburn  7122:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7123:                     if (@blockers > 0) {
                   7124:                         $thisallowed = 'B';
                   7125:                     } else {
                   7126:                         $thisallowed.=$value;
                   7127:                     }
1.1162    raeburn  7128:                 }
1.671     raeburn  7129:             }
                   7130:         } else {
1.705     albertel 7131:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7132:             if ($refuri) {
                   7133:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7134:                     $thisallowed='F';
1.671     raeburn  7135:                 } else {
                   7136:                     $refuri=&declutter($refuri);
                   7137:                     my ($match) = &is_on_map($refuri);
                   7138:                     if ($match) {
1.1281    raeburn  7139:                         if ($noblockcheck) {
                   7140:                             $thisallowed='F';
1.1162    raeburn  7141:                         } else {
1.1281    raeburn  7142:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7143:                             if (@blockers > 0) {
                   7144:                                 $thisallowed = 'B';
                   7145:                             } else {
                   7146:                                 $thisallowed='F';
                   7147:                             }
1.1162    raeburn  7148:                         }
1.671     raeburn  7149:                     }
1.669     raeburn  7150:                 }
1.671     raeburn  7151:             }
                   7152:         }
1.314     www      7153:     }
1.492     albertel 7154: 
1.766     albertel 7155:     if ($priv eq 'bre'
                   7156: 	&& $thisallowed ne 'F' 
                   7157: 	&& $thisallowed ne '2'
                   7158: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  7159: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7160:     }
1.1250    raeburn  7161: 
1.52      www      7162: # Full access at system, domain or course-wide level? Exit.
1.29      www      7163:     if ($thisallowed=~/F/) {
                   7164: 	return 'F';
                   7165:     }
                   7166: 
1.52      www      7167: # If this is generating or modifying users, exit with special codes
1.29      www      7168: 
1.643     www      7169:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7170: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7171: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7172: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7173: 	    unless ($auname) { return $thisallowed; }
                   7174: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7175: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7176: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7177: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7178: 	}
1.52      www      7179: 	return $thisallowed;
                   7180:     }
                   7181: #
1.103     harris41 7182: # Gathered so far: system, domain and course wide privileges
1.52      www      7183: #
                   7184: # Course: See if uri or referer is an individual resource that is part of 
                   7185: # the course
                   7186: 
1.620     albertel 7187:     if ($env{'request.course.id'}) {
1.232     www      7188: 
1.620     albertel 7189:        $courseprivid=$env{'request.course.id'};
                   7190:        if ($env{'request.course.sec'}) {
                   7191:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7192:        }
                   7193:        $courseprivid=~s/\_/\//;
                   7194:        my $checkreferer=1;
1.232     www      7195:        my ($match,$cond)=&is_on_map($uri);
                   7196:        if ($match) {
                   7197:            $statecond=$cond;
1.620     albertel 7198:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7199:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7200:                my $value = $1;
                   7201:                if ($priv eq 'bre') {
1.1281    raeburn  7202:                    if ($noblockcheck) {
                   7203:                        $thisallowed.=$value;
1.1162    raeburn  7204:                    } else {
1.1281    raeburn  7205:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7206:                        if (@blockers > 0) {
                   7207:                            $thisallowed = 'B';
                   7208:                        } else {
                   7209:                            $thisallowed.=$value;
                   7210:                        }
1.1162    raeburn  7211:                    }
                   7212:                } else {
                   7213:                    $thisallowed.=$value;
                   7214:                }
1.52      www      7215:                $checkreferer=0;
                   7216:            }
1.29      www      7217:        }
1.83      www      7218:        
1.148     www      7219:        if ($checkreferer) {
1.620     albertel 7220: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7221:             unless ($refuri) {
1.800     albertel 7222:                 foreach my $key (keys(%env)) {
                   7223: 		    if ($key=~/^httpref\..*\*/) {
                   7224: 			my $pattern=$key;
1.156     www      7225:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7226:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7227:                         $pattern=~s/\//\\\//g;
1.152     www      7228:                         if ($orguri=~/$pattern/) {
1.800     albertel 7229: 			    $refuri=$env{$key};
1.148     www      7230:                         }
                   7231:                     }
1.191     harris41 7232:                 }
1.148     www      7233:             }
1.232     www      7234: 
1.148     www      7235:          if ($refuri) { 
1.152     www      7236: 	  $refuri=&declutter($refuri);
1.232     www      7237:           my ($match,$cond)=&is_on_map($refuri);
                   7238:             if ($match) {
                   7239:               my $refstatecond=$cond;
1.620     albertel 7240:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7241:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7242:                   my $value = $1;
                   7243:                   if ($priv eq 'bre') {
1.1281    raeburn  7244:                       if ($noblockcheck) {
                   7245:                           $thisallowed.=$value;
1.1162    raeburn  7246:                       } else {
1.1281    raeburn  7247:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7248:                           if (@blockers > 0) {
                   7249:                               $thisallowed = 'B';
                   7250:                           } else {
                   7251:                               $thisallowed.=$value;
                   7252:                           }
1.1162    raeburn  7253:                       }
                   7254:                   } else {
                   7255:                       $thisallowed.=$value;
                   7256:                   }
1.53      www      7257:                   $uri=$refuri;
                   7258:                   $statecond=$refstatecond;
1.52      www      7259:               }
                   7260:           }
1.148     www      7261:         }
1.29      www      7262:        }
1.52      www      7263:    }
1.29      www      7264: 
1.52      www      7265: #
1.103     harris41 7266: # Gathered now: all privileges that could apply, and condition number
1.52      www      7267: # 
                   7268: #
                   7269: # Full or no access?
                   7270: #
1.29      www      7271: 
1.52      www      7272:     if ($thisallowed=~/F/) {
                   7273: 	return 'F';
                   7274:     }
1.29      www      7275: 
1.52      www      7276:     unless ($thisallowed) {
                   7277:         return '';
                   7278:     }
1.29      www      7279: 
1.52      www      7280: # Restrictions exist, deal with them
                   7281: #
                   7282: #   C:according to course preferences
                   7283: #   R:according to resource settings
                   7284: #   L:unless locked
                   7285: #   X:according to user session state
                   7286: #
                   7287: 
                   7288: # Possibly locked functionality, check all courses
1.54      www      7289: # Locks might take effect only after 10 minutes cache expiration for other
                   7290: # courses, and 2 minutes for current course
1.52      www      7291: 
                   7292:     my $envkey;
                   7293:     if ($thisallowed=~/L/) {
1.1000    raeburn  7294:         foreach $envkey (keys(%env)) {
1.54      www      7295:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7296:                my $courseid=$2;
                   7297:                my $roleid=$1.'.'.$2;
1.92      www      7298:                $courseid=~s/^\///;
1.54      www      7299:                my $expiretime=600;
1.620     albertel 7300:                if ($env{'request.role'} eq $roleid) {
1.54      www      7301: 		  $expiretime=120;
                   7302:                }
                   7303: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7304:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7305:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7306: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7307:                }
1.620     albertel 7308:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7309:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7310: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7311:                        &log($env{'user.domain'},$env{'user.name'},
                   7312:                             $env{'user.home'},
1.57      www      7313:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7314:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7315:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7316: 		       return '';
                   7317:                    }
                   7318:                }
1.620     albertel 7319:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7320:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7321: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7322:                        &log($env{'user.domain'},$env{'user.name'},
                   7323:                             $env{'user.home'},
1.57      www      7324:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7325:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7326:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7327: 		       return '';
                   7328:                    }
                   7329:                }
                   7330: 	   }
1.29      www      7331:        }
1.52      www      7332:     }
                   7333:    
                   7334: #
                   7335: # Rest of the restrictions depend on selected course
                   7336: #
                   7337: 
1.620     albertel 7338:     unless ($env{'request.course.id'}) {
1.766     albertel 7339: 	if ($thisallowed eq 'A') {
                   7340: 	    return 'A';
1.814     raeburn  7341:         } elsif ($thisallowed eq 'B') {
                   7342:             return 'B';
1.766     albertel 7343: 	} else {
                   7344: 	    return '1';
                   7345: 	}
1.52      www      7346:     }
1.29      www      7347: 
1.52      www      7348: #
                   7349: # Now user is definitely in a course
                   7350: #
1.53      www      7351: 
                   7352: 
                   7353: # Course preferences
                   7354: 
                   7355:    if ($thisallowed=~/C/) {
1.620     albertel 7356:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7357:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7358:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7359: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  7360: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7361: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7362: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7363: 			$env{'request.course.id'});
                   7364: 	   }
1.237     www      7365:            return '';
                   7366:        }
                   7367: 
1.620     albertel 7368:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7369: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  7370: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7371: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7372: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7373: 			$env{'request.course.id'});
                   7374: 	   }
1.54      www      7375:            return '';
                   7376:        }
1.53      www      7377:    }
                   7378: 
                   7379: # Resource preferences
                   7380: 
                   7381:    if ($thisallowed=~/R/) {
1.620     albertel 7382:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7383:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7384: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7385: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7386: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7387: 	   }
                   7388: 	   return '';
1.54      www      7389:        }
1.53      www      7390:    }
1.30      www      7391: 
1.246     www      7392: # Restricted by state or randomout?
1.30      www      7393: 
1.52      www      7394:    if ($thisallowed=~/X/) {
1.620     albertel 7395:       if ($env{'acc.randomout'}) {
1.579     albertel 7396: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7397:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7398:             return ''; 
                   7399:          }
1.247     www      7400:       }
                   7401:       if (&condval($statecond)) {
1.52      www      7402: 	 return '2';
                   7403:       } else {
                   7404:          return '';
                   7405:       }
                   7406:    }
1.30      www      7407: 
1.766     albertel 7408:     if ($thisallowed eq 'A') {
                   7409: 	return 'A';
1.814     raeburn  7410:     } elsif ($thisallowed eq 'B') {
                   7411:         return 'B';
1.766     albertel 7412:     }
1.52      www      7413:    return 'F';
1.232     www      7414: }
1.1162    raeburn  7415: 
1.1192    raeburn  7416: # ------------------------------------------- Check construction space access
                   7417: 
                   7418: sub constructaccess {
                   7419:     my ($url,$setpriv)=@_;
                   7420: 
                   7421: # We do not allow editing of previous versions of files
                   7422:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7423: 
                   7424: # Get username and domain from URL
                   7425:     my ($ownername,$ownerdomain,$ownerhome);
                   7426: 
                   7427:     ($ownerdomain,$ownername) =
1.1297    damieng  7428:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)/});
1.1192    raeburn  7429: 
                   7430: # The URL does not really point to any authorspace, forget it
                   7431:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7432: 
                   7433: # Now we need to see if the user has access to the authorspace of
                   7434: # $ownername at $ownerdomain
                   7435: 
                   7436:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7437: # Real author for this?
                   7438:        $ownerhome = $env{'user.home'};
                   7439:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7440:           return ($ownername,$ownerdomain,$ownerhome);
                   7441:        }
                   7442:     } else {
                   7443: # Co-author for this?
                   7444:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7445:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7446:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7447:             return ($ownername,$ownerdomain,$ownerhome);
                   7448:         }
1.1312    raeburn  7449:         if ($env{'request.course.id'}) {
                   7450:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   7451:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   7452:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   7453:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   7454:                     return ($ownername,$ownerdomain,$ownerhome);
                   7455:                 }
                   7456:             }
                   7457:         }
1.1192    raeburn  7458:     }
                   7459: 
                   7460: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7461: # we might as well leave
                   7462:    unless ($setpriv) { return ''; }
                   7463: 
                   7464: # Backdoor access?
                   7465:     my $allowed=&allowed('eco',$ownerdomain);
                   7466: # Nope
                   7467:     unless ($allowed) { return ''; }
                   7468: # Looks like we may have access, but could be locked by the owner of the construction space
                   7469:     if ($allowed eq 'U') {
                   7470:         my %blocked=&get('environment',['domcoord.author'],
                   7471:                          $ownerdomain,$ownername);
                   7472: # Is blocked by owner
                   7473:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7474:     }
                   7475:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7476: # Grant temporary access
                   7477:         my $then=$env{'user.login.time'};
1.1209    raeburn  7478:         my $update=$env{'user.update.time'};
1.1192    raeburn  7479:         if (!$update) { $update = $then; }
                   7480:         my $refresh=$env{'user.refresh.time'};
                   7481:         if (!$refresh) { $refresh = $update; }
                   7482:         my $now = time;
                   7483:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7484:                            $now,'ca','constructaccess');
                   7485:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7486:         return($ownername,$ownerdomain,$ownerhome);
                   7487:     }
                   7488: # No business here
                   7489:     return '';
                   7490: }
                   7491: 
1.1282    raeburn  7492: # ----------------------------------------------------------- Content Blocking
                   7493: 
                   7494: {
                   7495: # Caches for faster Course Contents display where content blocking
                   7496: # is in operation (i.e., interval param set) for timed quiz.
                   7497: #
                   7498: # User for whom data are being temporarily cached.
                   7499: my $cacheduser='';
                   7500: # Cached blockers for this user (a hash of blocking items). 
                   7501: my %cachedblockers=();
                   7502: # When the data were last cached.
                   7503: my $cachedlast='';
                   7504: 
                   7505: sub load_all_blockers {
                   7506:     my ($uname,$udom,$blocks)=@_;
                   7507:     if (($uname ne '') && ($udom ne '')) { 
                   7508:         if (($cacheduser eq $uname.':'.$udom) &&
                   7509:             (abs($cachedlast-time)<5)) {
                   7510:             return;
                   7511:         }
                   7512:     }
                   7513:     $cachedlast=time;
                   7514:     $cacheduser=$uname.':'.$udom;
                   7515:     %cachedblockers = &get_commblock_resources($blocks);
                   7516: }
                   7517: 
1.1162    raeburn  7518: sub get_comm_blocks {
                   7519:     my ($cdom,$cnum) = @_;
                   7520:     if ($cdom eq '' || $cnum eq '') {
                   7521:         return unless ($env{'request.course.id'});
                   7522:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7523:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7524:     }
                   7525:     my %commblocks;
                   7526:     my $hashid=$cdom.'_'.$cnum;
                   7527:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7528:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7529:         %commblocks = %{$blocksref};
                   7530:     } else {
                   7531:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7532:         my $cachetime = 600;
                   7533:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7534:     }
                   7535:     return %commblocks;
                   7536: }
                   7537: 
1.1282    raeburn  7538: sub get_commblock_resources {
                   7539:     my ($blocks) = @_;
                   7540:     my %blockers = ();
                   7541:     return %blockers unless ($env{'request.course.id'});
                   7542:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7543:     my %commblocks;
                   7544:     if (ref($blocks) eq 'HASH') {
                   7545:         %commblocks = %{$blocks};
                   7546:     } else {
                   7547:         %commblocks = &get_comm_blocks();
                   7548:     }
1.1282    raeburn  7549:     return %blockers unless (keys(%commblocks) > 0); 
                   7550:     my $navmap = Apache::lonnavmaps::navmap->new();
                   7551:     return %blockers unless (ref($navmap));
1.1162    raeburn  7552:     my $now = time;
                   7553:     foreach my $block (keys(%commblocks)) {
                   7554:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7555:             my ($start,$end) = ($1,$2);
                   7556:             if ($start <= $now && $end >= $now) {
                   7557:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7558:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7559:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  7560:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7561:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  7562:                             }
                   7563:                         }
                   7564:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  7565:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7566:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  7567:                             }
                   7568:                         }
                   7569:                     }
                   7570:                 }
                   7571:             }
                   7572:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7573:             my $item = $1;
1.1163    raeburn  7574:             my @to_test;
1.1162    raeburn  7575:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7576:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  7577:                     my @interval;
                   7578:                     my $type = 'map';
                   7579:                     if ($item eq 'course') {
                   7580:                         $type = 'course';
                   7581:                         @interval=&EXT("resource.0.interval");
                   7582:                     } else {
                   7583:                         if ($item =~ /___\d+___/) {
                   7584:                             $type = 'resource';
                   7585:                             @interval=&EXT("resource.0.interval",$item);
                   7586:                             if (ref($navmap)) {                        
                   7587:                                 my $res = $navmap->getBySymb($item); 
                   7588:                                 push(@to_test,$res);
                   7589:                             }
1.1162    raeburn  7590:                         } else {
1.1282    raeburn  7591:                             my $mapsymb = &symbread($item,1);
                   7592:                             if ($mapsymb) {
                   7593:                                 if (ref($navmap)) {
                   7594:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   7595:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   7596:                                     foreach my $res (@to_test) {
                   7597:                                         my $symb = $res->symb();
                   7598:                                         next if ($symb eq $mapsymb);
                   7599:                                         if ($symb ne '') {
                   7600:                                             @interval=&EXT("resource.0.interval",$symb);
                   7601:                                             if ($interval[1] eq 'map') {
                   7602:                                                 last;
1.1162    raeburn  7603:                                             }
                   7604:                                         }
                   7605:                                     }
                   7606:                                 }
                   7607:                             }
                   7608:                         }
1.1282    raeburn  7609:                     }
1.1310    raeburn  7610:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  7611:                         my $timelimit = $1; 
1.1282    raeburn  7612:                         my $first_access;
                   7613:                         if ($type eq 'resource') {
                   7614:                             $first_access=&get_first_access($interval[1],$item);
                   7615:                         } elsif ($type eq 'map') {
                   7616:                             $first_access=&get_first_access($interval[1],undef,$item);
                   7617:                         } else {
                   7618:                             $first_access=&get_first_access($interval[1]);
                   7619:                         }
                   7620:                         if ($first_access) {
1.1292    raeburn  7621:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  7622:                             if ($timesup > $now) {
                   7623:                                 my $activeblock;
                   7624:                                 foreach my $res (@to_test) {
1.1283    raeburn  7625:                                     if ($res->answerable()) {
1.1282    raeburn  7626:                                         $activeblock = 1;
                   7627:                                         last;
                   7628:                                     }
                   7629:                                 }
                   7630:                                 if ($activeblock) {
                   7631:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7632:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7633:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   7634:                                          }
                   7635:                                     }
                   7636:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7637:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7638:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  7639:                                         }
1.1162    raeburn  7640:                                     }
                   7641:                                 }
                   7642:                             }
                   7643:                         }
                   7644:                     }
                   7645:                 }
                   7646:             }
                   7647:         }
                   7648:     }
1.1282    raeburn  7649:     return %blockers;
1.1162    raeburn  7650: }
                   7651: 
1.1282    raeburn  7652: sub has_comm_blocking {
                   7653:     my ($priv,$symb,$uri,$blocks) = @_;
                   7654:     my @blockers;
                   7655:     return unless ($env{'request.course.id'});
                   7656:     return unless ($priv eq 'bre');
                   7657:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7658:     return if ($env{'request.state'} eq 'construct');
                   7659:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   7660:     return unless (keys(%cachedblockers) > 0);
                   7661:     my (%possibles,@symbs);
                   7662:     if (!$symb) {
                   7663:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  7664:     }
1.1282    raeburn  7665:     if ($symb) {
                   7666:         @symbs = ($symb);
                   7667:     } elsif (keys(%possibles)) { 
                   7668:         @symbs = keys(%possibles);
                   7669:     }
                   7670:     my $noblock;
                   7671:     foreach my $symb (@symbs) {
                   7672:         last if ($noblock);
                   7673:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   7674:         foreach my $block (keys(%cachedblockers)) {
                   7675:             if ($block =~ /^firstaccess____(.+)$/) {
                   7676:                 my $item = $1;
                   7677:                 if (($item eq $map) || ($item eq $symb)) {
                   7678:                     $noblock = 1;
                   7679:                     last;
                   7680:                 }
                   7681:             }
                   7682:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   7683:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   7684:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   7685:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   7686:                             push(@blockers,$block);
                   7687:                         }
                   7688:                     }
                   7689:                 }
1.1162    raeburn  7690:             }
1.1282    raeburn  7691:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   7692:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   7693:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   7694:                         push(@blockers,$block);
                   7695:                     }
                   7696:                 }
1.1162    raeburn  7697:             }
                   7698:         }
                   7699:     }
1.1282    raeburn  7700:     return if ($noblock);
                   7701:     return @blockers;
                   7702: }
1.1162    raeburn  7703: }
                   7704: 
1.1282    raeburn  7705: # -------------------------------- Deversion and split uri into path an filename   
                   7706: 
1.1133    foxr     7707: #
1.1282    raeburn  7708: #   Removes the version from a URI and
1.1133    foxr     7709: #   splits it in to its filename and path to the filename.
                   7710: #   Seems like File::Basename could have done this more clearly.
                   7711: #   Parameters:
                   7712: #      $uri   - input URI
                   7713: #   Returns:
                   7714: #     Two element list consisting of 
                   7715: #     $pathname  - the URI up to and excluding the trailing /
                   7716: #     $filename  - The part of the URI following the last /
                   7717: #  NOTE:
                   7718: #    Another realization of this is simply:
                   7719: #    use File::Basename;
                   7720: #    ...
                   7721: #    $uri = shift;
                   7722: #    $filename = basename($uri);
                   7723: #    $path     = dirname($uri);
                   7724: #    return ($filename, $path);
                   7725: #
                   7726: #     The implementation below is probably faster however.
                   7727: #
1.710     albertel 7728: sub split_uri_for_cond {
                   7729:     my $uri=&deversion(&declutter(shift));
                   7730:     my @uriparts=split(/\//,$uri);
                   7731:     my $filename=pop(@uriparts);
                   7732:     my $pathname=join('/',@uriparts);
                   7733:     return ($pathname,$filename);
                   7734: }
1.232     www      7735: # --------------------------------------------------- Is a resource on the map?
                   7736: 
                   7737: sub is_on_map {
1.710     albertel 7738:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7739:     #Trying to find the conditional for the file
1.620     albertel 7740:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7741: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7742:     if ($match) {
1.289     bowersj2 7743: 	return (1,$1);
                   7744:     } else {
1.434     www      7745: 	return (0,0);
1.289     bowersj2 7746:     }
1.12      www      7747: }
                   7748: 
1.427     www      7749: # --------------------------------------------------------- Get symb from alias
                   7750: 
                   7751: sub get_symb_from_alias {
                   7752:     my $symb=shift;
                   7753:     my ($map,$resid,$url)=&decode_symb($symb);
                   7754: # Already is a symb
                   7755:     if ($url) { return $symb; }
                   7756: # Must be an alias
                   7757:     my $aliassymb='';
                   7758:     my %bighash;
1.620     albertel 7759:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7760:                             &GDBM_READER(),0640)) {
                   7761:         my $rid=$bighash{'mapalias_'.$symb};
                   7762: 	if ($rid) {
                   7763: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7764: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7765: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7766: 	}
                   7767:         untie %bighash;
                   7768:     }
                   7769:     return $aliassymb;
                   7770: }
                   7771: 
1.12      www      7772: # ----------------------------------------------------------------- Define Role
                   7773: 
                   7774: sub definerole {
                   7775:   if (allowed('mcr','/')) {
                   7776:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7777:     foreach my $role (split(':',$sysrole)) {
                   7778: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7779:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7780:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7781: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7782:                return "refused:s:$crole&$cqual"; 
                   7783:             }
                   7784:         }
1.191     harris41 7785:     }
1.800     albertel 7786:     foreach my $role (split(':',$domrole)) {
                   7787: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7788:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7789:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7790: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7791:                return "refused:d:$crole&$cqual"; 
                   7792:             }
                   7793:         }
1.191     harris41 7794:     }
1.800     albertel 7795:     foreach my $role (split(':',$courole)) {
                   7796: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7797:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7798:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7799: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7800:                return "refused:c:$crole&$cqual"; 
                   7801:             }
                   7802:         }
1.191     harris41 7803:     }
1.620     albertel 7804:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7805:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7806: 	        "rolesdef_$rolename=".
                   7807:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7808:     return reply($command,$env{'user.home'});
1.12      www      7809:   } else {
                   7810:     return 'refused';
                   7811:   }
1.105     harris41 7812: }
                   7813: 
                   7814: # ---------------- Make a metadata query against the network of library servers
                   7815: 
                   7816: sub metadata_query {
1.1237    raeburn  7817:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7818:     my %rhash;
1.845     albertel 7819:     my %libserv = &all_library();
1.244     matthew  7820:     my @server_list = (defined($server_array) ? @$server_array
                   7821:                                               : keys(%libserv) );
                   7822:     for my $server (@server_list) {
1.1237    raeburn  7823:         my $domains = ''; 
                   7824:         if (ref($domains_hash) eq 'HASH') {
                   7825:             $domains = $domains_hash->{$server}; 
                   7826:         }
1.118     harris41 7827: 	unless ($custom or $customshow) {
1.1237    raeburn  7828: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7829: 	    $rhash{$server}=$reply;
                   7830: 	}
                   7831: 	else {
                   7832: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  7833: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7834: 			     $server);
                   7835: 	    $rhash{$server}=$reply;
                   7836: 	}
1.112     harris41 7837:     }
1.118     harris41 7838:     return \%rhash;
1.240     www      7839: }
                   7840: 
                   7841: # ----------------------------------------- Send log queries and wait for reply
                   7842: 
                   7843: sub log_query {
                   7844:     my ($uname,$udom,$query,%filters)=@_;
                   7845:     my $uhome=&homeserver($uname,$udom);
                   7846:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7847:     my $uhost=&hostname($uhome);
1.800     albertel 7848:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7849:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7850:                        $uhome);
1.479     albertel 7851:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7852:     return get_query_reply($queryid);
                   7853: }
                   7854: 
1.818     raeburn  7855: # -------------------------- Update MySQL table for portfolio file
                   7856: 
                   7857: sub update_portfolio_table {
1.821     raeburn  7858:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7859:     if ($group ne '') {
                   7860:         $file_name =~s /^\Q$group\E//;
                   7861:     }
1.818     raeburn  7862:     my $homeserver = &homeserver($uname,$udom);
                   7863:     my $queryid=
1.821     raeburn  7864:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7865:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7866:     my $reply = &get_query_reply($queryid);
                   7867:     return $reply;
                   7868: }
                   7869: 
1.899     raeburn  7870: # -------------------------- Update MySQL allusers table
                   7871: 
                   7872: sub update_allusers_table {
                   7873:     my ($uname,$udom,$names) = @_;
                   7874:     my $homeserver = &homeserver($uname,$udom);
                   7875:     my $queryid=
                   7876:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7877:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7878:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7879:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7880:                'generation='.&escape($names->{'generation'}).'%%'.
                   7881:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7882:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7883:     return;
1.899     raeburn  7884: }
                   7885: 
1.508     raeburn  7886: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7887: 
                   7888: sub fetch_enrollment_query {
1.511     raeburn  7889:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  7890:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  7891:     my $maxtries = 1;
1.508     raeburn  7892:     if ($context eq 'automated') {
                   7893:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  7894:         $sleep = 2;
                   7895:         $loopmax = 100;
1.547     raeburn  7896:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7897:     } else {
                   7898:         $homeserver = &homeserver($cnum,$dom);
                   7899:     }
1.838     albertel 7900:     my $host=&hostname($homeserver);
1.506     raeburn  7901:     my $cmd = '';
1.1000    raeburn  7902:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7903:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7904:     }
                   7905:     $cmd =~ s/%%$//;
                   7906:     $cmd = &escape($cmd);
                   7907:     my $query = 'fetchenrollment';
1.620     albertel 7908:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7909:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7910:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7911:         return 'error: '.$queryid;
                   7912:     }
1.1317    raeburn  7913:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  7914:     my $tries = 1;
                   7915:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  7916:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  7917:         $tries ++;
                   7918:     }
1.526     raeburn  7919:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7920:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7921:     } else {
1.901     albertel 7922:         my @responses = split(/:/,$reply);
1.1321  ! raeburn  7923:         if (grep { $_ eq $homeserver } &current_machine_ids()) { 
1.800     albertel 7924:             foreach my $line (@responses) {
                   7925:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7926:                 $$replyref{$key} = $value;
                   7927:             }
                   7928:         } else {
1.1117    foxr     7929:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7930:             foreach my $line (@responses) {
                   7931:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7932:                 $$replyref{$key} = $value;
                   7933:                 if ($value > 0) {
1.800     albertel 7934:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7935:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7936:                         my $destname = $pathname.'/'.$filename;
                   7937:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7938:                         if ($xml_classlist =~ /^error/) {
                   7939:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7940:                         } else {
1.506     raeburn  7941:                             if ( open(FILE,">$destname") ) {
                   7942:                                 print FILE &unescape($xml_classlist);
                   7943:                                 close(FILE);
1.526     raeburn  7944:                             } else {
                   7945:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7946:                             }
                   7947:                         }
                   7948:                     }
                   7949:                 }
                   7950:             }
                   7951:         }
                   7952:         return 'ok';
                   7953:     }
                   7954:     return 'error';
                   7955: }
                   7956: 
1.242     www      7957: sub get_query_reply {
1.1317    raeburn  7958:     my ($queryid,$sleep,$loopmax) = @_;;
                   7959:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   7960:         $sleep = 0.2;
                   7961:     }
                   7962:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   7963:         $loopmax = 100;
                   7964:     }
1.1117    foxr     7965:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7966:     my $reply='';
1.1317    raeburn  7967:     for (1..$loopmax) {
                   7968: 	sleep($sleep);
1.240     www      7969:         if (-e $replyfile.'.end') {
1.448     albertel 7970: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7971: 		$reply = join('',<$fh>);
                   7972: 		close($fh);
1.240     www      7973: 	   } else { return 'error: reply_file_error'; }
1.242     www      7974:            return &unescape($reply);
                   7975: 	}
1.240     www      7976:     }
1.242     www      7977:     return 'timeout:'.$queryid;
1.240     www      7978: }
                   7979: 
                   7980: sub courselog_query {
1.241     www      7981: #
                   7982: # possible filters:
                   7983: # url: url or symb
                   7984: # username
                   7985: # domain
                   7986: # action: view, submit, grade
                   7987: # start: timestamp
                   7988: # end: timestamp
                   7989: #
1.240     www      7990:     my (%filters)=@_;
1.620     albertel 7991:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7992:     if ($filters{'url'}) {
                   7993: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7994:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7995:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7996:     }
1.620     albertel 7997:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7998:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7999:     return &log_query($cname,$cdom,'courselog',%filters);
                   8000: }
                   8001: 
                   8002: sub userlog_query {
1.858     raeburn  8003: #
                   8004: # possible filters:
                   8005: # action: log check role
                   8006: # start: timestamp
                   8007: # end: timestamp
                   8008: #
1.240     www      8009:     my ($uname,$udom,%filters)=@_;
                   8010:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8011: }
                   8012: 
1.506     raeburn  8013: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8014: 
                   8015: sub auto_run {
1.508     raeburn  8016:     my ($cnum,$cdom) = @_;
1.876     raeburn  8017:     my $response = 0;
                   8018:     my $settings;
                   8019:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8020:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8021:         $settings = $domconfig{'autoenroll'};
                   8022:         if ($settings->{'run'} eq '1') {
                   8023:             $response = 1;
                   8024:         }
                   8025:     } else {
1.934     raeburn  8026:         my $homeserver;
                   8027:         if (&is_course($cdom,$cnum)) {
                   8028:             $homeserver = &homeserver($cnum,$cdom);
                   8029:         } else {
                   8030:             $homeserver = &domain($cdom,'primary');
                   8031:         }
                   8032:         if ($homeserver ne 'no_host') {
                   8033:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8034:         }
1.876     raeburn  8035:     }
1.506     raeburn  8036:     return $response;
                   8037: }
1.776     albertel 8038: 
1.506     raeburn  8039: sub auto_get_sections {
1.508     raeburn  8040:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8041:     my $homeserver;
                   8042:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8043:         $homeserver = &homeserver($cnum,$cdom);
                   8044:     }
                   8045:     if (!defined($homeserver)) { 
                   8046:         if ($cdom =~ /^$match_domain$/) {
                   8047:             $homeserver = &domain($cdom,'primary');
                   8048:         }
                   8049:     }
                   8050:     my @secs;
                   8051:     if (defined($homeserver)) {
                   8052:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8053:         unless ($response eq 'refused') {
                   8054:             @secs = split(/:/,$response);
                   8055:         }
1.506     raeburn  8056:     }
                   8057:     return @secs;
                   8058: }
1.776     albertel 8059: 
1.506     raeburn  8060: sub auto_new_course {
1.1099    raeburn  8061:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8062:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8063:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8064:     return $response;
                   8065: }
1.776     albertel 8066: 
1.506     raeburn  8067: sub auto_validate_courseID {
1.508     raeburn  8068:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8069:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8070:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8071:     return $response;
                   8072: }
1.776     albertel 8073: 
1.1007    raeburn  8074: sub auto_validate_instcode {
1.1020    raeburn  8075:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8076:     my ($homeserver,$response);
                   8077:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8078:         $homeserver = &homeserver($cnum,$cdom);
                   8079:     }
                   8080:     if (!defined($homeserver)) {
                   8081:         if ($cdom =~ /^$match_domain$/) {
                   8082:             $homeserver = &domain($cdom,'primary');
                   8083:         }
                   8084:     }
1.1065    raeburn  8085:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8086:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  8087:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8088:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8089: }
                   8090: 
1.506     raeburn  8091: sub auto_create_password {
1.873     raeburn  8092:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8093:     my ($homeserver,$response);
1.506     raeburn  8094:     my $create_passwd = 0;
                   8095:     my $authchk = '';
1.873     raeburn  8096:     if ($udom =~ /^$match_domain$/) {
                   8097:         $homeserver = &domain($udom,'primary');
                   8098:     }
                   8099:     if ($homeserver eq '') {
                   8100:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8101:             $homeserver = &homeserver($cnum,$cdom);
                   8102:         }
                   8103:     }
                   8104:     if ($homeserver eq '') {
                   8105:         $authchk = 'nodomain';
1.506     raeburn  8106:     } else {
1.873     raeburn  8107:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8108:         if ($response eq 'refused') {
                   8109:             $authchk = 'refused';
                   8110:         } else {
1.901     albertel 8111:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8112:         }
1.506     raeburn  8113:     }
                   8114:     return ($authparam,$create_passwd,$authchk);
                   8115: }
                   8116: 
1.706     raeburn  8117: sub auto_photo_permission {
                   8118:     my ($cnum,$cdom,$students) = @_;
                   8119:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8120:     my ($outcome,$perm_reqd,$conditions) = 
                   8121: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8122:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8123: 	return (undef,undef);
                   8124:     }
1.706     raeburn  8125:     return ($outcome,$perm_reqd,$conditions);
                   8126: }
                   8127: 
                   8128: sub auto_checkphotos {
                   8129:     my ($uname,$udom,$pid) = @_;
                   8130:     my $homeserver = &homeserver($uname,$udom);
                   8131:     my ($result,$resulttype);
                   8132:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8133: 				   &escape($uname).':'.&escape($pid),
                   8134: 				   $homeserver));
1.709     albertel 8135:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8136: 	return (undef,undef);
                   8137:     }
1.706     raeburn  8138:     if ($outcome) {
                   8139:         ($result,$resulttype) = split(/:/,$outcome);
                   8140:     } 
                   8141:     return ($result,$resulttype);
                   8142: }
                   8143: 
                   8144: sub auto_photochoice {
                   8145:     my ($cnum,$cdom) = @_;
                   8146:     my $homeserver = &homeserver($cnum,$cdom);
                   8147:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8148: 						       &escape($cdom),
                   8149: 						       $homeserver)));
1.709     albertel 8150:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8151: 	return (undef,undef);
                   8152:     }
1.706     raeburn  8153:     return ($update,$comment);
                   8154: }
                   8155: 
                   8156: sub auto_photoupdate {
                   8157:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8158:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8159:     my $host=&hostname($homeserver);
1.706     raeburn  8160:     my $cmd = '';
                   8161:     my $maxtries = 1;
1.800     albertel 8162:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8163:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8164:     }
                   8165:     $cmd =~ s/%%$//;
                   8166:     $cmd = &escape($cmd);
                   8167:     my $query = 'institutionalphotos';
                   8168:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8169:     unless ($queryid=~/^\Q$host\E\_/) {
                   8170:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8171:         return 'error: '.$queryid;
                   8172:     }
                   8173:     my $reply = &get_query_reply($queryid);
                   8174:     my $tries = 1;
                   8175:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8176:         $reply = &get_query_reply($queryid);
                   8177:         $tries ++;
                   8178:     }
                   8179:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8180:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8181:     } else {
                   8182:         my @responses = split(/:/,$reply);
                   8183:         my $outcome = shift(@responses); 
                   8184:         foreach my $item (@responses) {
                   8185:             my ($key,$value) = split(/=/,$item);
                   8186:             $$photo{$key} = $value;
                   8187:         }
                   8188:         return $outcome;
                   8189:     }
                   8190:     return 'error';
                   8191: }
                   8192: 
1.521     raeburn  8193: sub auto_instcode_format {
1.793     albertel 8194:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8195: 	$cat_order) = @_;
1.521     raeburn  8196:     my $courses = '';
1.772     raeburn  8197:     my @homeservers;
1.521     raeburn  8198:     if ($caller eq 'global') {
1.841     albertel 8199: 	my %servers = &get_servers($codedom,'library');
                   8200: 	foreach my $tryserver (keys(%servers)) {
                   8201: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8202: 		push(@homeservers,$tryserver);
                   8203: 	    }
1.584     raeburn  8204:         }
1.1022    raeburn  8205:     } elsif ($caller eq 'requests') {
                   8206:         if ($codedom =~ /^$match_domain$/) {
                   8207:             my $chome = &domain($codedom,'primary');
                   8208:             unless ($chome eq 'no_host') {
                   8209:                 push(@homeservers,$chome);
                   8210:             }
                   8211:         }
1.521     raeburn  8212:     } else {
1.772     raeburn  8213:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8214:     }
1.793     albertel 8215:     foreach my $code (keys(%{$instcodes})) {
                   8216:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8217:     }
                   8218:     chop($courses);
1.772     raeburn  8219:     my $ok_response = 0;
                   8220:     my $response;
                   8221:     while (@homeservers > 0 && $ok_response == 0) {
                   8222:         my $server = shift(@homeservers); 
                   8223:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8224:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8225:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8226: 		split(/:/,$response);
1.772     raeburn  8227:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8228:             push(@{$codetitles},&str2array($codetitles_str));
                   8229:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8230:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8231:             $ok_response = 1;
                   8232:         }
                   8233:     }
                   8234:     if ($ok_response) {
1.521     raeburn  8235:         return 'ok';
1.772     raeburn  8236:     } else {
                   8237:         return $response;
1.521     raeburn  8238:     }
                   8239: }
                   8240: 
1.792     raeburn  8241: sub auto_instcode_defaults {
                   8242:     my ($domain,$returnhash,$code_order) = @_;
                   8243:     my @homeservers;
1.841     albertel 8244: 
                   8245:     my %servers = &get_servers($domain,'library');
                   8246:     foreach my $tryserver (keys(%servers)) {
                   8247: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8248: 	    push(@homeservers,$tryserver);
                   8249: 	}
1.792     raeburn  8250:     }
1.841     albertel 8251: 
1.792     raeburn  8252:     my $response;
1.841     albertel 8253:     foreach my $server (@homeservers) {
1.792     raeburn  8254:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8255:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8256: 	
                   8257: 	foreach my $pair (split(/\&/,$response)) {
                   8258: 	    my ($name,$value)=split(/\=/,$pair);
                   8259: 	    if ($name eq 'code_order') {
                   8260: 		@{$code_order} = split(/\&/,&unescape($value));
                   8261: 	    } else {
                   8262: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8263: 	    }
                   8264: 	}
                   8265: 	return 'ok';
1.792     raeburn  8266:     }
1.841     albertel 8267: 
                   8268:     return $response;
1.1003    raeburn  8269: }
                   8270: 
                   8271: sub auto_possible_instcodes {
1.1007    raeburn  8272:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8273:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8274:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8275:         return;
                   8276:     }
1.1003    raeburn  8277:     my (@homeservers,$uhome);
                   8278:     if (defined(&domain($domain,'primary'))) {
                   8279:         $uhome=&domain($domain,'primary');
                   8280:         push(@homeservers,&domain($domain,'primary'));
                   8281:     } else {
                   8282:         my %servers = &get_servers($domain,'library');
                   8283:         foreach my $tryserver (keys(%servers)) {
                   8284:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8285:                 push(@homeservers,$tryserver);
                   8286:             }
                   8287:         }
                   8288:     }
                   8289:     my $response;
                   8290:     foreach my $server (@homeservers) {
                   8291:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8292:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8293:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8294:             split(':',$response);
                   8295:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8296:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8297:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8298:             my ($name,$value)=split('=',$item);
                   8299:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8300:         }
                   8301:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8302:             my ($name,$value)=split('=',$item);
                   8303:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8304:         }
                   8305:         return 'ok';
                   8306:     }
                   8307:     return $response;
                   8308: }
1.792     raeburn  8309: 
1.1010    raeburn  8310: sub auto_courserequest_checks {
                   8311:     my ($dom) = @_;
1.1020    raeburn  8312:     my ($homeserver,%validations);
                   8313:     if ($dom =~ /^$match_domain$/) {
                   8314:         $homeserver = &domain($dom,'primary');
                   8315:     }
                   8316:     unless ($homeserver eq 'no_host') {
                   8317:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8318:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8319:             my @items = split(/&/,$response);
                   8320:             foreach my $item (@items) {
                   8321:                 my ($key,$value) = split('=',$item);
                   8322:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8323:             }
                   8324:         }
                   8325:     }
1.1010    raeburn  8326:     return %validations; 
                   8327: }
                   8328: 
1.1020    raeburn  8329: sub auto_courserequest_validation {
1.1255    raeburn  8330:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8331:     my ($homeserver,$response);
                   8332:     if ($dom =~ /^$match_domain$/) {
                   8333:         $homeserver = &domain($dom,'primary');
                   8334:     }
1.1255    raeburn  8335:     unless ($homeserver eq 'no_host') {
                   8336:         my $customdata;
                   8337:         if (ref($custominfo) eq 'HASH') {
                   8338:             $customdata = &freeze_escape($custominfo);
                   8339:         }
1.1020    raeburn  8340:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8341:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  8342:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8343:                                     $customdata,$homeserver));
1.1020    raeburn  8344:     }
                   8345:     return $response;
                   8346: }
                   8347: 
1.777     albertel 8348: sub auto_validate_class_sec {
1.918     raeburn  8349:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8350:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8351:     my $ownerlist;
                   8352:     if (ref($owners) eq 'ARRAY') {
                   8353:         $ownerlist = join(',',@{$owners});
                   8354:     } else {
                   8355:         $ownerlist = $owners;
                   8356:     }
1.773     raeburn  8357:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8358:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8359:     return $response;
                   8360: }
                   8361: 
1.1248    raeburn  8362: sub auto_crsreq_update {
                   8363:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  8364:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  8365:     my ($homeserver,%crsreqresponse);
                   8366:     if ($cdom =~ /^$match_domain$/) {
                   8367:         $homeserver = &domain($cdom,'primary');
                   8368:     }
                   8369:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8370:         my $info;
                   8371:         if (ref($inbound) eq 'HASH') {
                   8372:             $info = &freeze_escape($inbound);
                   8373:         }
                   8374:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8375:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8376:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  8377:                             &escape($title).':'.&escape($code).':'.
                   8378:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   8379:                             $homeserver);
1.1248    raeburn  8380:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8381:             my @items = split(/&/,$response);
                   8382:             foreach my $item (@items) {
                   8383:                 my ($key,$value) = split('=',$item);
                   8384:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8385:             }
                   8386:         }
                   8387:     }
                   8388:     return \%crsreqresponse;
                   8389: }
                   8390: 
1.1305    raeburn  8391: sub auto_export_grades {
1.1309    raeburn  8392:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8393:     my ($homeserver,%exportresponse);
                   8394:     if ($cdom =~ /^$match_domain$/) {
                   8395:         $homeserver = &domain($cdom,'primary');
                   8396:     }
                   8397:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8398:         my $info;
                   8399:         if (ref($inforef) eq 'HASH') {
                   8400:             $info = &freeze_escape($inforef);
                   8401:         }
                   8402:         if (ref($gradesref) eq 'HASH') {
                   8403:             my $grades = &freeze_escape($gradesref);
                   8404:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   8405:                                 $info.':'.$grades,$homeserver);
                   8406:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   8407:                 my @items = split(/&/,$response);
                   8408:                 foreach my $item (@items) {
                   8409:                     my ($key,$value) = split('=',$item);
                   8410:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   8411:                 }
                   8412:             }
                   8413:         }
                   8414:     }
                   8415:     return \%exportresponse;
1.1305    raeburn  8416: }
                   8417: 
1.1287    raeburn  8418: sub check_instcode_cloning {
                   8419:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8420:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8421:         return;
                   8422:     }
                   8423:     my $canclone;
                   8424:     if (@{$code_order} > 0) {
                   8425:         my $instcoderegexp ='^';
                   8426:         my @clonecodes = split(/\&/,$cloner);
                   8427:         foreach my $item (@{$code_order}) {
                   8428:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8429:                 foreach my $pair (@clonecodes) {
                   8430:                     my ($key,$val) = split(/\=/,$pair,2);
                   8431:                     $val = &unescape($val);
                   8432:                     if ($key eq $item) {
                   8433:                         $instcoderegexp .= '('.$val.')';
                   8434:                         last;
                   8435:                     }
                   8436:                 }
                   8437:             } else {
                   8438:                 $instcoderegexp .= $codedefaults->{$item};
                   8439:             }
                   8440:         }
                   8441:         $instcoderegexp .= '$';
                   8442:         my (@from,@to);
                   8443:         eval {
                   8444:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8445:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8446:         };
                   8447:         if ((@from > 0) && (@to > 0)) {
                   8448:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8449:             if (!@diffs) {
                   8450:                 $canclone = 1;
                   8451:             }
                   8452:         }
                   8453:     }
                   8454:     return $canclone;
                   8455: }
                   8456: 
                   8457: sub default_instcode_cloning {
                   8458:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8459:     my (%codedefaults,@code_order,$canclone);
                   8460:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8461:         %codedefaults = %{$codedefaultsref};
                   8462:         @code_order = @{$codeorderref};
                   8463:     } elsif ($clonedom) {
                   8464:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8465:     }
                   8466:     if (($domdefclone) && (@code_order)) {
                   8467:         my @clonecodes = split(/\+/,$domdefclone);
                   8468:         my $instcoderegexp ='^';
                   8469:         foreach my $item (@code_order) {
                   8470:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8471:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8472:             } else {
                   8473:                 $instcoderegexp .= $codedefaults{$item};
                   8474:             }
                   8475:         }
                   8476:         $instcoderegexp .= '$';
                   8477:         my (@from,@to);
                   8478:         eval {
                   8479:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8480:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8481:         };
                   8482:         if ((@from > 0) && (@to > 0)) {
                   8483:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8484:             if (!@diffs) {
                   8485:                 $canclone = 1;
                   8486:             }
                   8487:         }
                   8488:     }
                   8489:     return $canclone;
                   8490: }
                   8491: 
1.679     raeburn  8492: # ------------------------------------------------------- Course Group routines
                   8493: 
                   8494: sub get_coursegroups {
1.809     raeburn  8495:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8496:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8497: }
                   8498: 
1.679     raeburn  8499: sub modify_coursegroup {
                   8500:     my ($cdom,$cnum,$groupsettings) = @_;
                   8501:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8502: }
                   8503: 
1.809     raeburn  8504: sub toggle_coursegroup_status {
                   8505:     my ($cdom,$cnum,$group,$action) = @_;
                   8506:     my ($from_namespace,$to_namespace);
                   8507:     if ($action eq 'delete') {
                   8508:         $from_namespace = 'coursegroups';
                   8509:         $to_namespace = 'deleted_groups';
                   8510:     } else {
                   8511:         $from_namespace = 'deleted_groups';
                   8512:         $to_namespace = 'coursegroups';
                   8513:     }
                   8514:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8515:     if (my $tmp = &error(%curr_group)) {
                   8516:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8517:         return ('read error',$tmp);
                   8518:     } else {
                   8519:         my %savedsettings = %curr_group; 
1.809     raeburn  8520:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8521:         my $deloutcome;
                   8522:         if ($result eq 'ok') {
1.809     raeburn  8523:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8524:         } else {
                   8525:             return ('write error',$result);
                   8526:         }
                   8527:         if ($deloutcome eq 'ok') {
                   8528:             return 'ok';
                   8529:         } else {
                   8530:             return ('delete error',$deloutcome);
                   8531:         }
                   8532:     }
                   8533: }
                   8534: 
1.679     raeburn  8535: sub modify_group_roles {
1.957     raeburn  8536:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8537:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8538:     my $role = 'gr/'.&escape($userprivs);
                   8539:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8540:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8541:     if ($result eq 'ok') {
                   8542:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8543:     }
1.679     raeburn  8544:     return $result;
                   8545: }
                   8546: 
                   8547: sub modify_coursegroup_membership {
                   8548:     my ($cdom,$cnum,$membership) = @_;
                   8549:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8550:     return $result;
                   8551: }
                   8552: 
1.682     raeburn  8553: sub get_active_groups {
                   8554:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8555:     my $now = time;
                   8556:     my %groups = ();
                   8557:     foreach my $key (keys(%env)) {
1.811     albertel 8558:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8559:             my ($start,$end) = split(/\./,$env{$key});
                   8560:             if (($end!=0) && ($end<$now)) { next; }
                   8561:             if (($start!=0) && ($start>$now)) { next; }
                   8562:             if ($1 eq $cdom && $2 eq $cnum) {
                   8563:                 $groups{$3} = $env{$key} ;
                   8564:             }
                   8565:         }
                   8566:     }
                   8567:     return %groups;
                   8568: }
                   8569: 
1.683     raeburn  8570: sub get_group_membership {
                   8571:     my ($cdom,$cnum,$group) = @_;
                   8572:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8573: }
                   8574: 
                   8575: sub get_users_groups {
                   8576:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8577:     my @usersgroups;
1.683     raeburn  8578:     my $cachetime=1800;
                   8579: 
                   8580:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8581:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8582:     if (defined($cached)) {
1.734     albertel 8583:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8584:     } else {  
                   8585:         $grouplist = '';
1.816     raeburn  8586:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8587:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8588:         my $access_end = $env{'course.'.$courseid.
                   8589:                               '.default_enrollment_end_date'};
                   8590:         my $now = time;
                   8591:         foreach my $key (keys(%roleshash)) {
                   8592:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8593:                 my $group = $1;
                   8594:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8595:                     my $start = $2;
                   8596:                     my $end = $1;
                   8597:                     if ($start == -1) { next; } # deleted from group
                   8598:                     if (($start!=0) && ($start>$now)) { next; }
                   8599:                     if (($end!=0) && ($end<$now)) {
                   8600:                         if ($access_end && $access_end < $now) {
                   8601:                             if ($access_end - $end < 86400) {
                   8602:                                 push(@usersgroups,$group);
1.733     raeburn  8603:                             }
                   8604:                         }
1.817     raeburn  8605:                         next;
1.733     raeburn  8606:                     }
1.817     raeburn  8607:                     push(@usersgroups,$group);
1.683     raeburn  8608:                 }
                   8609:             }
                   8610:         }
1.817     raeburn  8611:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8612:         $grouplist = join(':',@usersgroups);
                   8613:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8614:     }
1.733     raeburn  8615:     return @usersgroups;
1.683     raeburn  8616: }
                   8617: 
                   8618: sub devalidate_getgroups_cache {
                   8619:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8620:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8621: 
1.683     raeburn  8622:     my $hashid="$udom:$uname:$courseid";
                   8623:     &devalidate_cache_new('getgroups',$hashid);
                   8624: }
                   8625: 
1.12      www      8626: # ------------------------------------------------------------------ Plain Text
                   8627: 
                   8628: sub plaintext {
1.988     raeburn  8629:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8630:     if ($short =~ m{^cr/}) {
1.758     albertel 8631: 	return (split('/',$short))[-1];
                   8632:     }
1.742     raeburn  8633:     if (!defined($cid)) {
                   8634:         $cid = $env{'request.course.id'};
                   8635:     }
                   8636:     my %rolenames = (
1.1008    raeburn  8637:                       Course    => 'std',
                   8638:                       Community => 'alt1',
1.1305    raeburn  8639:                       Placement => 'std',
1.742     raeburn  8640:                     );
1.1037    raeburn  8641:     if ($cid ne '') {
                   8642:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8643:             unless ($forcedefault) {
                   8644:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8645:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8646:                 return &Apache::lonlocal::mt($roletext);
                   8647:             }
                   8648:         }
                   8649:     }
                   8650:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8651:         (defined($rolenames{$type})) && 
                   8652:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8653:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8654:     } elsif ($cid ne '') {
                   8655:         my $crstype = $env{'course.'.$cid.'.type'};
                   8656:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8657:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8658:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8659:         }
1.742     raeburn  8660:     }
1.1037    raeburn  8661:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8662: }
                   8663: 
                   8664: # ----------------------------------------------------------------- Assign Role
                   8665: 
                   8666: sub assignrole {
1.957     raeburn  8667:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8668:         $context)=@_;
1.21      www      8669:     my $mrole;
                   8670:     if ($role =~ /^cr\//) {
1.393     www      8671:         my $cwosec=$url;
1.811     albertel 8672:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8673: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8674:            my $refused = 1;
                   8675:            if ($context eq 'requestcourses') {
                   8676:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8677:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8678:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8679:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8680:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8681:                            if ($crsenv{'internal.courseowner'} eq
                   8682:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8683:                                $refused = '';
                   8684:                            }
                   8685:                        }
                   8686:                    }
                   8687:                }
                   8688:            }
                   8689:            if ($refused) {
                   8690:                &logthis('Refused custom assignrole: '.
                   8691:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8692:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8693:                return 'refused';
                   8694:            }
1.104     www      8695:         }
1.21      www      8696:         $mrole='cr';
1.678     raeburn  8697:     } elsif ($role =~ /^gr\//) {
                   8698:         my $cwogrp=$url;
1.811     albertel 8699:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8700:         unless (&allowed('mdg',$cwogrp)) {
                   8701:             &logthis('Refused group assignrole: '.
                   8702:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8703:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8704:             return 'refused';
                   8705:         }
                   8706:         $mrole='gr';
1.21      www      8707:     } else {
1.82      www      8708:         my $cwosec=$url;
1.811     albertel 8709:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8710:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8711:             my $refused;
                   8712:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8713:                 if (!(&allowed('c'.$role,$url))) {
                   8714:                     $refused = 1;
                   8715:                 }
                   8716:             } else {
                   8717:                 $refused = 1;
                   8718:             }
1.947     raeburn  8719:             if ($refused) {
1.1045    raeburn  8720:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8721:                 if (!$selfenroll && $context eq 'course') {
                   8722:                     my %crsenv;
                   8723:                     if ($role eq 'cc' || $role eq 'co') {
                   8724:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8725:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8726:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8727:                                 if ($crsenv{'internal.courseowner'} eq 
                   8728:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8729:                                     $refused = '';
                   8730:                                 }
                   8731:                             }
                   8732:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8733:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8734:                                 if ($crsenv{'internal.courseowner'} eq 
                   8735:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8736:                                     $refused = '';
                   8737:                                 }
                   8738:                             }
                   8739:                         }
                   8740:                     }
                   8741:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8742:                     $refused = '';
1.1017    raeburn  8743:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8744:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8745:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8746:                         my $wrongcc;
                   8747:                         if ($cnum =~ /^$match_community$/) {
                   8748:                             $wrongcc = 1 if ($role eq 'cc');
                   8749:                         } else {
                   8750:                             $wrongcc = 1 if ($role eq 'co');
                   8751:                         }
                   8752:                         unless ($wrongcc) {
                   8753:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8754:                             if ($crsenv{'internal.courseowner'} eq 
                   8755:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8756:                                 $refused = '';
                   8757:                             }
1.1017    raeburn  8758:                         }
                   8759:                     }
1.1183    raeburn  8760:                 } elsif ($context eq 'requestauthor') {
                   8761:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   8762:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8763:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8764:                             $refused = '';
                   8765:                         } else {
                   8766:                             my %domdefaults = &get_domain_defaults($udom);
                   8767:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8768:                                 my $checkbystatus;
                   8769:                                 if ($env{'user.adv'}) { 
                   8770:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8771:                                     if ($disposition eq 'automatic') {
                   8772:                                         $refused = '';
                   8773:                                     } elsif ($disposition eq '') {
                   8774:                                         $checkbystatus = 1;
                   8775:                                     } 
                   8776:                                 } else {
                   8777:                                     $checkbystatus = 1;
                   8778:                                 }
                   8779:                                 if ($checkbystatus) {
                   8780:                                     if ($env{'environment.inststatus'}) {
                   8781:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8782:                                         foreach my $type (@inststatuses) {
                   8783:                                             if (($type ne '') &&
                   8784:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8785:                                                 $refused = '';
                   8786:                                             }
                   8787:                                         }
                   8788:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8789:                                         $refused = '';
                   8790:                                     }
                   8791:                                 }
                   8792:                             }
                   8793:                         }
                   8794:                     }
1.1017    raeburn  8795:                 }
                   8796:                 if ($refused) {
1.947     raeburn  8797:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8798:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8799: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8800:                     return 'refused';
                   8801:                 }
1.932     raeburn  8802:             }
1.1131    raeburn  8803:         } elsif ($role eq 'au') {
                   8804:             if ($url ne '/'.$udom.'/') {
                   8805:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8806:                          ' to assign author role for '.$uname.':'.$udom.
                   8807:                          ' in domain: '.$url.' refused (wrong domain).');
                   8808:                 return 'refused';
                   8809:             }
1.104     www      8810:         }
1.21      www      8811:         $mrole=$role;
                   8812:     }
1.620     albertel 8813:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8814:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8815:     if ($end) { $command.='_'.$end; }
1.21      www      8816:     if ($start) {
                   8817: 	if ($end) { 
1.81      www      8818:            $command.='_'.$start; 
1.21      www      8819:         } else {
1.81      www      8820:            $command.='_0_'.$start;
1.21      www      8821:         }
                   8822:     }
1.739     raeburn  8823:     my $origstart = $start;
                   8824:     my $origend = $end;
1.957     raeburn  8825:     my $delflag;
1.357     www      8826: # actually delete
                   8827:     if ($deleteflag) {
1.373     www      8828: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8829: # modify command to delete the role
1.620     albertel 8830:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8831:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8832: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8833: # set start and finish to negative values for userrolelog
                   8834:            $start=-1;
                   8835:            $end=-1;
1.957     raeburn  8836:            $delflag = 1;
1.357     www      8837:         }
                   8838:     }
                   8839: # send command
1.349     www      8840:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8841: # log new user role if status is ok
1.349     www      8842:     if ($answer eq 'ok') {
1.663     raeburn  8843: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  8844:         if (($role eq 'cc') || ($role eq 'in') ||
                   8845:             ($role eq 'ep') || ($role eq 'ad') ||
                   8846:             ($role eq 'ta') || ($role eq 'st') ||
                   8847:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8848:             ($role eq 'co')) {
1.1200    raeburn  8849: # for course roles, perform group memberships changes triggered by role change.
                   8850:             unless ($role =~ /^gr/) {
                   8851:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8852:                                                  $origstart,$selfenroll,$context);
                   8853:             }
1.1184    raeburn  8854:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8855:                            $selfenroll,$context);
                   8856:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8857:                  ($role eq 'au') || ($role eq 'dc')) {
                   8858:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8859:                            $context);
                   8860:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8861:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8862:                              $context); 
                   8863:         }
1.1053    raeburn  8864:         if ($role eq 'cc') {
                   8865:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8866:         }
1.349     www      8867:     }
                   8868:     return $answer;
1.169     harris41 8869: }
                   8870: 
1.1053    raeburn  8871: sub autoupdate_coowners {
                   8872:     my ($url,$end,$start,$uname,$udom) = @_;
                   8873:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8874:     if (($cdom ne '') && ($cnum ne '')) {
                   8875:         my $now = time;
                   8876:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8877:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8878:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8879:             my $instcode = $coursehash{'internal.coursecode'};
                   8880:             if ($instcode ne '') {
1.1056    raeburn  8881:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8882:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8883:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8884:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8885:                         if ($result eq 'valid') {
                   8886:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8887:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8888:                                     push(@newcoowners,$coowner);
                   8889:                                 }
                   8890:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8891:                                     push(@newcoowners,$uname.':'.$udom);
                   8892:                                 }
                   8893:                                 @newcoowners = sort(@newcoowners);
                   8894:                             } else {
                   8895:                                 push(@newcoowners,$uname.':'.$udom);
                   8896:                             }
                   8897:                         } else {
                   8898:                             if ($coursehash{'internal.co-owners'}) {
                   8899:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8900:                                     unless ($coowner eq $uname.':'.$udom) {
                   8901:                                         push(@newcoowners,$coowner);
                   8902:                                     }
                   8903:                                 }
                   8904:                                 unless (@newcoowners > 0) {
                   8905:                                     $delcoowners = 1;
                   8906:                                     $coowners = '';
                   8907:                                 }
                   8908:                             }
                   8909:                         }
                   8910:                         if (@newcoowners || $delcoowners) {
                   8911:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8912:                                             $delcoowners,@newcoowners);
                   8913:                         }
                   8914:                     }
                   8915:                 }
                   8916:             }
                   8917:         }
                   8918:     }
                   8919: }
                   8920: 
                   8921: sub store_coowners {
                   8922:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8923:     my $cid = $cdom.'_'.$cnum;
                   8924:     my ($coowners,$delresult,$putresult);
                   8925:     if (@newcoowners) {
                   8926:         $coowners = join(',',@newcoowners);
                   8927:         my %coownershash = (
                   8928:                             'internal.co-owners' => $coowners,
                   8929:                            );
                   8930:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8931:         if ($putresult eq 'ok') {
                   8932:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8933:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8934:             }
                   8935:         }
                   8936:     }
                   8937:     if ($delcoowners) {
                   8938:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8939:         if ($delresult eq 'ok') {
                   8940:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8941:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8942:             }
                   8943:         }
                   8944:     }
                   8945:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8946:         my %crsinfo =
                   8947:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8948:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8949:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8950:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8951:         }
                   8952:     }
                   8953: }
                   8954: 
1.169     harris41 8955: # -------------------------------------------------- Modify user authentication
1.197     www      8956: # Overrides without validation
                   8957: 
1.169     harris41 8958: sub modifyuserauth {
                   8959:     my ($udom,$uname,$umode,$upass)=@_;
                   8960:     my $uhome=&homeserver($uname,$udom);
1.197     www      8961:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8962:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8963:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8964:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8965:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8966: 		     &escape($upass),$uhome);
1.620     albertel 8967:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8968:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8969:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8970:     &log($udom,,$uname,$uhome,
1.620     albertel 8971:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8972:                                      $env{'user.name'}.', '.$umode.
1.197     www      8973:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8974:     unless ($reply eq 'ok') {
1.197     www      8975:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8976: 	return 'error: '.$reply;
                   8977:     }   
1.170     harris41 8978:     return 'ok';
1.80      www      8979: }
                   8980: 
1.81      www      8981: # --------------------------------------------------------------- Modify a user
1.80      www      8982: 
1.81      www      8983: sub modifyuser {
1.206     matthew  8984:     my ($udom,    $uname, $uid,
                   8985:         $umode,   $upass, $first,
                   8986:         $middle,  $last,  $gene,
1.1058    raeburn  8987:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8988:     $udom= &LONCAPA::clean_domain($udom);
                   8989:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8990:     my $showcandelete = 'none';
                   8991:     if (ref($candelete) eq 'ARRAY') {
                   8992:         if (@{$candelete} > 0) {
                   8993:             $showcandelete = join(', ',@{$candelete});
                   8994:         }
                   8995:     }
1.81      www      8996:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8997:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8998: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8999:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9000:                                      ' desiredhome not specified'). 
1.620     albertel 9001:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9002:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9003:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9004:     my $newuser;
                   9005:     if ($uhome eq 'no_host') {
                   9006:         $newuser = 1;
                   9007:     }
1.80      www      9008: # ----------------------------------------------------------------- Create User
1.406     albertel 9009:     if (($uhome eq 'no_host') && 
                   9010: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9011:         my $unhome='';
1.844     albertel 9012:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9013:             $unhome = $desiredhome;
1.620     albertel 9014: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9015: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9016:         } else { # load balancing routine for determining $unhome
1.81      www      9017:             my $loadm=10000000;
1.841     albertel 9018: 	    my %servers = &get_servers($udom,'library');
                   9019: 	    foreach my $tryserver (keys(%servers)) {
                   9020: 		my $answer=reply('load',$tryserver);
                   9021: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9022: 		    $loadm=$answer;
                   9023: 		    $unhome=$tryserver;
                   9024: 		}
1.80      www      9025: 	    }
                   9026:         }
                   9027:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9028: 	    return 'error: unable to find a home server for '.$uname.
                   9029:                    ' in domain '.$udom;
1.80      www      9030:         }
                   9031:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9032:                          &escape($upass),$unhome);
                   9033: 	unless ($reply eq 'ok') {
                   9034:             return 'error: '.$reply;
                   9035:         }   
1.230     stredwic 9036:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9037:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9038: 	    return 'error: unable verify users home machine.';
1.80      www      9039:         }
1.209     matthew  9040:     }   # End of creation of new user
1.80      www      9041: # ---------------------------------------------------------------------- Add ID
                   9042:     if ($uid) {
                   9043:        $uid=~tr/A-Z/a-z/;
                   9044:        my %uidhash=&idrget($udom,$uname);
1.196     www      9045:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9046:          && (!$forceid)) {
1.80      www      9047: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9048: 	      return 'error: user id "'.$uid.'" does not match '.
                   9049:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9050:           }
                   9051:        } else {
1.1300    raeburn  9052: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      9053:        }
                   9054:     }
                   9055: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9056:     my @tmp=&get('environment',
1.899     raeburn  9057: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9058:                     'permanentemail','inststatus'],
1.134     albertel 9059: 		   $udom,$uname);
1.1075    raeburn  9060:     my (%names,%oldnames);
1.313     matthew  9061:     if ($tmp[0] =~ m/^error:.*/) { 
                   9062:         %names=(); 
                   9063:     } else {
                   9064:         %names = @tmp;
1.1075    raeburn  9065:         %oldnames = %names;
1.313     matthew  9066:     }
1.388     www      9067: #
1.1058    raeburn  9068: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9069: # of users did not contain them), do not overwrite existing values
                   9070: # unless field is in $candelete array ref.  
                   9071: #
                   9072: 
                   9073:     my @fields = ('firstname','middlename','lastname','generation',
                   9074:                   'permanentemail','id');
                   9075:     my %newvalues;
                   9076:     if (ref($candelete) eq 'ARRAY') {
                   9077:         foreach my $field (@fields) {
                   9078:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9079:                 if ($field eq 'firstname') {
                   9080:                     $names{$field} = $first;
                   9081:                 } elsif ($field eq 'middlename') {
                   9082:                     $names{$field} = $middle;
                   9083:                 } elsif ($field eq 'lastname') {
                   9084:                     $names{$field} = $last;
                   9085:                 } elsif ($field eq 'generation') { 
                   9086:                     $names{$field} = $gene;
                   9087:                 } elsif ($field eq 'permanentemail') {
                   9088:                     $names{$field} = $email;
                   9089:                 } elsif ($field eq 'id') {
                   9090:                     $names{$field}  = $uid;
                   9091:                 }
                   9092:             }
                   9093:         }
                   9094:     }
1.388     www      9095:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9096:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9097:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9098:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9099:     if ($email) {
                   9100:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9101:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9102:     }
1.899     raeburn  9103:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9104:     if (defined($inststatus)) {
                   9105:         $names{'inststatus'} = '';
                   9106:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9107:         if (ref($usertypes) eq 'HASH') {
                   9108:             my @okstatuses; 
                   9109:             foreach my $item (split(/:/,$inststatus)) {
                   9110:                 if (defined($usertypes->{$item})) {
                   9111:                     push(@okstatuses,$item);  
                   9112:                 }
                   9113:             }
                   9114:             if (@okstatuses) {
                   9115:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9116:             }
                   9117:         }
                   9118:     }
1.1075    raeburn  9119:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9120:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9121:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9122:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9123:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9124:     } else {
                   9125:         $logmsg .= ' during self creation';
                   9126:     }
1.1075    raeburn  9127:     my $changed;
                   9128:     if ($newuser) {
                   9129:         $changed = 1;
                   9130:     } else {
                   9131:         foreach my $field (@fields) {
                   9132:             if ($names{$field} ne $oldnames{$field}) {
                   9133:                 $changed = 1;
                   9134:                 last;
                   9135:             }
                   9136:         }
                   9137:     }
                   9138:     unless ($changed) {
                   9139:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9140:         &logthis($logmsg);
                   9141:         return 'ok';
                   9142:     }
                   9143:     my $reply = &put('environment', \%names, $udom,$uname);
                   9144:     if ($reply ne 'ok') { 
                   9145:         return 'error: '.$reply;
                   9146:     }
1.1087    raeburn  9147:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9148:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9149:     }
1.1075    raeburn  9150:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9151:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9152:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9153:     &logthis($logmsg);
1.134     albertel 9154:     return 'ok';
1.80      www      9155: }
                   9156: 
1.81      www      9157: # -------------------------------------------------------------- Modify student
1.80      www      9158: 
1.81      www      9159: sub modifystudent {
                   9160:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9161:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  9162:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9163:     if (!$cid) {
1.620     albertel 9164: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9165: 	    return 'not_in_class';
                   9166: 	}
1.80      www      9167:     }
                   9168: # --------------------------------------------------------------- Make the user
1.81      www      9169:     my $reply=&modifyuser
1.209     matthew  9170: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9171:          $desiredhome,$email,$inststatus);
1.80      www      9172:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9173:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  9174:     # student's environment
1.297     matthew  9175:     $uid = undef if (!$forceid);
1.455     albertel 9176:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  9177:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  9178:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9179:     return $reply;
                   9180: }
                   9181: 
                   9182: sub modify_student_enrollment {
1.1216    raeburn  9183:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  9184:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9185:     my ($cdom,$cnum,$chome);
                   9186:     if (!$cid) {
1.620     albertel 9187: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9188: 	    return 'not_in_class';
                   9189: 	}
1.620     albertel 9190: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9191: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9192:     } else {
                   9193: 	($cdom,$cnum)=split(/_/,$cid);
                   9194:     }
1.620     albertel 9195:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9196:     if (!$chome) {
1.457     raeburn  9197: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9198:     }
1.455     albertel 9199:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9200:     # Make sure the user exists
1.81      www      9201:     my $uhome=&homeserver($uname,$udom);
                   9202:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9203: 	return 'error: no such user';
                   9204:     }
1.297     matthew  9205:     # Get student data if we were not given enough information
                   9206:     if (!defined($first)  || $first  eq '' || 
                   9207:         !defined($last)   || $last   eq '' || 
                   9208:         !defined($uid)    || $uid    eq '' || 
                   9209:         !defined($middle) || $middle eq '' || 
                   9210:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9211:         # They did not supply us with enough data to enroll the student, so
                   9212:         # we need to pick up more information.
1.297     matthew  9213:         my %tmp = &get('environment',
1.294     matthew  9214:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9215:                        ,$udom,$uname);
                   9216: 
1.800     albertel 9217:         #foreach my $key (keys(%tmp)) {
                   9218:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9219:         #}
1.294     matthew  9220:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9221:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9222:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9223:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9224:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9225:     }
1.556     albertel 9226:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9227:     my $user = "$uname:$udom";
                   9228:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9229:     my $reply=cput('classlist',
1.1148    raeburn  9230: 		   {$user => 
1.1314    raeburn  9231: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9232: 		   $cdom,$cnum);
1.1148    raeburn  9233:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9234:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9235:     } else { 
1.81      www      9236: 	return 'error: '.$reply;
                   9237:     }
1.297     matthew  9238:     # Add student role to user
1.83      www      9239:     my $uurl='/'.$cid;
1.81      www      9240:     $uurl=~s/\_/\//g;
                   9241:     if ($usec) {
                   9242: 	$uurl.='/'.$usec;
                   9243:     }
1.1148    raeburn  9244:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9245:                              $selfenroll,$context);
                   9246:     if ($result ne 'ok') {
                   9247:         if ($old_entry{$user} ne '') {
                   9248:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9249:         } else {
                   9250:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9251:         }
                   9252:     }
                   9253:     return $result; 
1.21      www      9254: }
                   9255: 
1.556     albertel 9256: sub format_name {
                   9257:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9258:     my $name;
                   9259:     if ($first ne 'lastname') {
                   9260: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9261:     } else {
                   9262: 	if ($lastname=~/\S/) {
                   9263: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9264: 	    $name=~s/\s+,/,/;
                   9265: 	} else {
                   9266: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9267: 	}
                   9268:     }
                   9269:     $name=~s/^\s+//;
                   9270:     $name=~s/\s+$//;
                   9271:     $name=~s/\s+/ /g;
                   9272:     return $name;
                   9273: }
                   9274: 
1.84      www      9275: # ------------------------------------------------- Write to course preferences
                   9276: 
                   9277: sub writecoursepref {
                   9278:     my ($courseid,%prefs)=@_;
                   9279:     $courseid=~s/^\///;
                   9280:     $courseid=~s/\_/\//g;
                   9281:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9282:     my $chome=homeserver($cnum,$cdomain);
                   9283:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9284: 	return 'error: no such course';
                   9285:     }
                   9286:     my $cstring='';
1.800     albertel 9287:     foreach my $pref (keys(%prefs)) {
                   9288: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9289:     }
1.84      www      9290:     $cstring=~s/\&$//;
                   9291:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9292: }
                   9293: 
                   9294: # ---------------------------------------------------------- Make/modify course
                   9295: 
                   9296: sub createcourse {
1.741     raeburn  9297:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9298:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9299:     $url=&declutter($url);
                   9300:     my $cid='';
1.1028    raeburn  9301:     if ($context eq 'requestcourses') {
                   9302:         my $can_create = 0;
                   9303:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9304:         if ($udom eq $ownerdom) {
                   9305:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9306:                                   $context)) {
                   9307:                 $can_create = 1;
                   9308:             }
                   9309:         } else {
                   9310:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9311:                                            $category);
                   9312:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9313:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9314:                 if (@curr > 0) {
                   9315:                     my @options = qw(approval validate autolimit);
                   9316:                     my $optregex = join('|',@options);
                   9317:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9318:                         $can_create = 1;
                   9319:                     }
                   9320:                 }
                   9321:             }
                   9322:         }
                   9323:         if ($can_create) {
                   9324:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9325:                 unless (&allowed('ccc',$udom)) {
                   9326:                     return 'refused'; 
                   9327:                 }
1.1017    raeburn  9328:             }
                   9329:         } else {
                   9330:             return 'refused';
                   9331:         }
1.1028    raeburn  9332:     } elsif (!&allowed('ccc',$udom)) {
                   9333:         return 'refused';
1.84      www      9334:     }
1.1011    raeburn  9335: # --------------------------------------------------------------- Get Unique ID
                   9336:     my $uname;
                   9337:     if ($cnum =~ /^$match_courseid$/) {
                   9338:         my $chome=&homeserver($cnum,$udom,'true');
                   9339:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9340:             $uname = $cnum;
                   9341:         } else {
1.1038    raeburn  9342:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9343:         }
                   9344:     } else {
1.1038    raeburn  9345:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9346:     }
                   9347:     return $uname if ($uname =~ /^error/);
                   9348: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9349:     if (!defined($course_server)) {
                   9350:         if (defined(&domain($udom,'primary'))) {
                   9351:             $course_server = &domain($udom,'primary');
                   9352:         } else {
                   9353:             $course_server = $env{'user.home'}; 
                   9354:         }
                   9355:     }
                   9356:     my %host_servers =
                   9357:         &Apache::lonnet::get_servers($udom,'library');
                   9358:     unless ($host_servers{$course_server}) {
                   9359:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9360:     }
1.84      www      9361: # ------------------------------------------------------------- Make the course
                   9362:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9363:                       $course_server);
1.84      www      9364:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9365:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9366:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9367: 	return 'error: no such course';
                   9368:     }
1.271     www      9369: # ----------------------------------------------------------------- Course made
1.516     raeburn  9370: # log existence
1.1029    raeburn  9371:     my $now = time;
1.918     raeburn  9372:     my $newcourse = {
                   9373:                     $udom.'_'.$uname => {
1.921     raeburn  9374:                                      description => $description,
                   9375:                                      inst_code   => $inst_code,
                   9376:                                      owner       => $course_owner,
                   9377:                                      type        => $crstype,
1.1029    raeburn  9378:                                      creator     => $env{'user.name'}.':'.
                   9379:                                                     $env{'user.domain'},
                   9380:                                      created     => $now,
                   9381:                                      context     => $context,
1.918     raeburn  9382:                                                 },
                   9383:                     };
1.921     raeburn  9384:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9385: # set toplevel url
1.271     www      9386:     my $topurl=$url;
                   9387:     unless ($nonstandard) {
                   9388: # ------------------------------------------ For standard courses, make top url
                   9389:         my $mapurl=&clutter($url);
1.278     www      9390:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9391:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9392: <map>
                   9393: <resource id="1" type="start"></resource>
                   9394: <resource id="2" src="$mapurl"></resource>
                   9395: <resource id="3" type="finish"></resource>
                   9396: <link index="1" from="1" to="2"></link>
                   9397: <link index="2" from="2" to="3"></link>
                   9398: </map>
                   9399: ENDINITMAP
                   9400:         $topurl=&declutter(
1.638     albertel 9401:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9402:                           );
                   9403:     }
                   9404: # ----------------------------------------------------------- Write preferences
1.84      www      9405:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9406:                      ('description'              => $description,
                   9407:                       'url'                      => $topurl,
                   9408:                       'internal.creator'         => $env{'user.name'}.':'.
                   9409:                                                     $env{'user.domain'},
                   9410:                       'internal.created'         => $now,
                   9411:                       'internal.creationcontext' => $context)
                   9412:                     );
1.84      www      9413:     return '/'.$udom.'/'.$uname;
                   9414: }
                   9415: 
1.1011    raeburn  9416: # ------------------------------------------------------------------- Create ID
                   9417: sub generate_coursenum {
1.1038    raeburn  9418:     my ($udom,$crstype) = @_;
1.1011    raeburn  9419:     my $domdesc = &domain($udom);
                   9420:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9421:     my $first;
                   9422:     if ($crstype eq 'Community') {
                   9423:         $first = '0';
                   9424:     } else {
                   9425:         $first = int(1+rand(9)); 
                   9426:     } 
                   9427:     my $uname=$first.
1.1011    raeburn  9428:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9429:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9430:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9431: # ----------------------------------------------- Make sure that does not exist
                   9432:     my $uhome=&homeserver($uname,$udom,'true');
                   9433:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9434:         if ($crstype eq 'Community') {
                   9435:             $first = '0';
                   9436:         } else {
                   9437:             $first = int(1+rand(9));
                   9438:         }
                   9439:         $uname=$first.
1.1011    raeburn  9440:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9441:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9442:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9443:         $uhome=&homeserver($uname,$udom,'true');
                   9444:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9445:             return 'error: unable to generate unique course-ID';
                   9446:         }
                   9447:     }
                   9448:     return $uname;
                   9449: }
                   9450: 
1.813     albertel 9451: sub is_course {
1.1167    droeschl 9452:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9453:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   9454: 
                   9455:     return unless $cdom and $cnum;
                   9456: 
                   9457:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   9458:         '.');
                   9459: 
1.1219    raeburn  9460:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 9461:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9462: }
                   9463: 
1.1015    raeburn  9464: sub store_userdata {
                   9465:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9466:     my $result;
1.1016    raeburn  9467:     if ($datakey ne '') {
1.1013    raeburn  9468:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9469:             if ($udom eq '' || $uname eq '') {
                   9470:                 $udom = $env{'user.domain'};
                   9471:                 $uname = $env{'user.name'};
                   9472:             }
                   9473:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9474:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9475:                 $result = 'error: no_host';
                   9476:             } else {
                   9477:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9478:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9479: 
                   9480:                 my $namevalue='';
                   9481:                 foreach my $key (keys(%{$storehash})) {
                   9482:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9483:                 }
                   9484:                 $namevalue=~s/\&$//;
1.1224    raeburn  9485:                 unless ($namespace eq 'courserequests') {
                   9486:                     $datakey = &escape($datakey);
                   9487:                 }
1.1105    raeburn  9488:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9489:                                   $namevalue,$uhome);
1.1013    raeburn  9490:             }
                   9491:         } else {
                   9492:             $result = 'error: data to store was not a hash reference'; 
                   9493:         }
                   9494:     } else {
                   9495:         $result= 'error: invalid requestkey'; 
                   9496:     }
                   9497:     return $result;
                   9498: }
                   9499: 
1.21      www      9500: # ---------------------------------------------------------- Assign Custom Role
                   9501: 
                   9502: sub assigncustomrole {
1.957     raeburn  9503:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9504:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9505:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9506: }
                   9507: 
                   9508: # ----------------------------------------------------------------- Revoke Role
                   9509: 
                   9510: sub revokerole {
1.957     raeburn  9511:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9512:     my $now=time;
1.965     raeburn  9513:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9514: }
                   9515: 
                   9516: # ---------------------------------------------------------- Revoke Custom Role
                   9517: 
                   9518: sub revokecustomrole {
1.957     raeburn  9519:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9520:     my $now=time;
1.357     www      9521:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9522:            $deleteflag,$selfenroll,$context);
1.17      www      9523: }
                   9524: 
1.533     banghart 9525: # ------------------------------------------------------------ Disk usage
1.535     albertel 9526: sub diskusage {
1.955     raeburn  9527:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9528:     $directorypath =~ s/\/$//;
                   9529:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9530:                        .&escape($getpropath).':'.&escape($uname).':'
                   9531:                        .&escape($udom),homeserver($uname,$udom));
                   9532:     if ($listing eq 'unknown_cmd') {
                   9533:         if ($getpropath) {
                   9534:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9535:         }
                   9536:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9537:     }
1.514     albertel 9538:     return $listing;
1.512     banghart 9539: }
                   9540: 
1.566     banghart 9541: sub is_locked {
1.1096    raeburn  9542:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9543:     my @check;
                   9544:     my $is_locked;
1.1093    raeburn  9545:     push (@check,$file_name);
1.613     albertel 9546:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9547: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9548:     my ($tmp)=keys(%locked);
                   9549:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9550:     
1.566     banghart 9551:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9552:         $is_locked = 'false';
                   9553:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9554:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9555:                $is_locked = 'true';
1.1096    raeburn  9556:                if (ref($which) eq 'ARRAY') {
                   9557:                    push(@{$which},$entry);
                   9558:                } else {
                   9559:                    last;
                   9560:                }
1.745     raeburn  9561:            }
                   9562:        }
1.566     banghart 9563:     } else {
                   9564:         $is_locked = 'false';
                   9565:     }
1.1093    raeburn  9566:     return $is_locked;
1.566     banghart 9567: }
                   9568: 
1.759     albertel 9569: sub declutter_portfile {
                   9570:     my ($file) = @_;
1.833     albertel 9571:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9572:     return $file;
                   9573: }
                   9574: 
1.559     banghart 9575: # ------------------------------------------------------------- Mark as Read Only
                   9576: 
                   9577: sub mark_as_readonly {
                   9578:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9579:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9580:     my ($tmp)=keys(%current_permissions);
                   9581:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9582:     foreach my $file (@{$files}) {
1.759     albertel 9583: 	$file = &declutter_portfile($file);
1.561     banghart 9584:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9585:     }
1.613     albertel 9586:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9587:     return;
                   9588: }
                   9589: 
1.572     banghart 9590: # ------------------------------------------------------------Save Selected Files
                   9591: 
                   9592: sub save_selected_files {
                   9593:     my ($user, $path, @files) = @_;
                   9594:     my $filename = $user."savedfiles";
1.573     banghart 9595:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9596:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9597:     foreach my $file (@files) {
1.620     albertel 9598:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9599:     }
                   9600:     foreach my $file (@other_files) {
1.574     banghart 9601:         print (OUT $file."\n");
1.572     banghart 9602:     }
1.574     banghart 9603:     close (OUT);
1.572     banghart 9604:     return 'ok';
                   9605: }
                   9606: 
1.574     banghart 9607: sub clear_selected_files {
                   9608:     my ($user) = @_;
                   9609:     my $filename = $user."savedfiles";
1.1117    foxr     9610:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9611:     print (OUT undef);
                   9612:     close (OUT);
                   9613:     return ("ok");    
                   9614: }
                   9615: 
1.572     banghart 9616: sub files_in_path {
                   9617:     my ($user, $path) = @_;
                   9618:     my $filename = $user."savedfiles";
                   9619:     my %return_files;
1.1117    foxr     9620:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9621:     while (my $line_in = <IN>) {
1.574     banghart 9622:         chomp ($line_in);
                   9623:         my @paths_and_file = split (m!/!, $line_in);
                   9624:         my $file_part = pop (@paths_and_file);
                   9625:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9626:         $path_part.='/';
                   9627:         my $path_and_file = $path_part.$file_part;
                   9628:         if ($path_part eq $path) {
                   9629:             $return_files{$file_part}= 'selected';
                   9630:         }
                   9631:     }
1.574     banghart 9632:     close (IN);
                   9633:     return (\%return_files);
1.572     banghart 9634: }
                   9635: 
                   9636: # called in portfolio select mode, to show files selected NOT in current directory
                   9637: sub files_not_in_path {
                   9638:     my ($user, $path) = @_;
                   9639:     my $filename = $user."savedfiles";
                   9640:     my @return_files;
                   9641:     my $path_part;
1.1117    foxr     9642:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9643:     while (my $line = <IN>) {
1.572     banghart 9644:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9645:         my @paths_and_file = split(m|/|, $line);
                   9646:         my $file_part = pop(@paths_and_file);
                   9647:         chomp($file_part);
                   9648:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9649:         $path_part .= '/';
                   9650:         my $path_and_file = $path_part.$file_part;
                   9651:         if ($path_part ne $path) {
1.800     albertel 9652:             push(@return_files, ($path_and_file));
1.572     banghart 9653:         }
                   9654:     }
1.800     albertel 9655:     close(OUT);
1.574     banghart 9656:     return (@return_files);
1.572     banghart 9657: }
                   9658: 
1.1273    raeburn  9659: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   9660:  
                   9661: sub portfiles_versioning {
                   9662:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   9663:     my $portfolio_root = '/userfiles/portfolio';
                   9664:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   9665:     foreach my $file (@{$portfiles}) {
                   9666:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   9667:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   9668:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   9669:         my $getpropath = 1;
                   9670:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   9671:                                              $stu_name,$getpropath);
                   9672:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   9673:         my $new_answer = 
                   9674:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   9675:         if ($new_answer ne 'problem getting file') {
                   9676:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   9677:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   9678:                               [$symb,$env{'request.course.id'},'graded']);
                   9679:         }
                   9680:     }
                   9681: }
                   9682: 
                   9683: sub get_next_version {
                   9684:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   9685:     my $version;
                   9686:     if (ref($dir_list) eq 'ARRAY') {
                   9687:         foreach my $row (@{$dir_list}) {
                   9688:             my ($file) = split(/\&/,$row,2);
                   9689:             my ($file_name,$file_version,$file_ext) =
                   9690:                 &file_name_version_ext($file);
                   9691:             if (($file_name eq $answer_name) &&
                   9692:                 ($file_ext eq $answer_ext)) {
                   9693:                      # gets here if filename and extension match,
                   9694:                      # regardless of version
                   9695:                 if ($file_version ne '') {
                   9696:                     # a versioned file is found  so save it for later
                   9697:                     if ($file_version > $version) {
                   9698:                         $version = $file_version;
                   9699:                     }
                   9700:                 }
                   9701:             }
                   9702:         }
                   9703:     }
                   9704:     $version ++;
                   9705:     return($version);
                   9706: }
                   9707: 
                   9708: sub version_selected_portfile {
                   9709:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   9710:     my ($answer_name,$answer_ver,$answer_ext) =
                   9711:         &file_name_version_ext($file_name);
                   9712:     my $new_answer;
                   9713:     $env{'form.copy'} =
                   9714:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   9715:     if($env{'form.copy'} eq '-1') {
                   9716:         $new_answer = 'problem getting file';
                   9717:     } else {
                   9718:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   9719:         my $copy_result = 
                   9720:             &finishuserfileupload($stu_name,$domain,'copy',
                   9721:                                   '/portfolio'.$directory.$new_answer);
                   9722:     }
                   9723:     undef($env{'form.copy'});
                   9724:     return ($new_answer);
                   9725: }
                   9726: 
                   9727: sub file_name_version_ext {
                   9728:     my ($file)=@_;
                   9729:     my @file_parts = split(/\./, $file);
                   9730:     my ($name,$version,$ext);
                   9731:     if (@file_parts > 1) {
                   9732:         $ext=pop(@file_parts);
                   9733:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   9734:             $version=pop(@file_parts);
                   9735:         }
                   9736:         $name=join('.',@file_parts);
                   9737:     } else {
                   9738:         $name=join('.',@file_parts);
                   9739:     }
                   9740:     return($name,$version,$ext);
                   9741: }
                   9742: 
1.745     raeburn  9743: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9744: 
1.745     raeburn  9745: sub get_portfile_permissions {
                   9746:     my ($domain,$user) = @_;
1.613     albertel 9747:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9748:     my ($tmp)=keys(%current_permissions);
                   9749:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9750:     return \%current_permissions;
                   9751: }
                   9752: 
                   9753: #---------------------------------------------Get portfolio file access controls
                   9754: 
1.749     raeburn  9755: sub get_access_controls {
1.745     raeburn  9756:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9757:     my %access;
                   9758:     my $real_file = $file;
                   9759:     $file =~ s/\.meta$//;
1.745     raeburn  9760:     if (defined($file)) {
1.749     raeburn  9761:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9762:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9763:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9764:             }
                   9765:         }
1.745     raeburn  9766:     } else {
1.749     raeburn  9767:         foreach my $key (keys(%{$current_permissions})) {
                   9768:             if ($key =~ /\0accesscontrol$/) {
                   9769:                 if (defined($group)) {
                   9770:                     if ($key !~ m-^\Q$group\E/-) {
                   9771:                         next;
                   9772:                     }
                   9773:                 }
                   9774:                 my ($fullpath) = split(/\0/,$key);
                   9775:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9776:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9777:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9778:                     }
                   9779:                 }
                   9780:             }
                   9781:         }
                   9782:     }
                   9783:     return %access;
                   9784: }
                   9785: 
                   9786: sub modify_access_controls {
                   9787:     my ($file_name,$changes,$domain,$user)=@_;
                   9788:     my ($outcome,$deloutcome);
                   9789:     my %store_permissions;
                   9790:     my %new_values;
                   9791:     my %new_control;
                   9792:     my %translation;
                   9793:     my @deletions = ();
                   9794:     my $now = time;
                   9795:     if (exists($$changes{'activate'})) {
                   9796:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9797:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9798:             my $numnew = scalar(@newitems);
                   9799:             for (my $i=0; $i<$numnew; $i++) {
                   9800:                 my $newkey = $newitems[$i];
                   9801:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9802:                 if ($newkey =~ /^\d+:/) { 
                   9803:                     $newkey =~ s/^(\d+)/$newid/;
                   9804:                     $translation{$1} = $newid;
                   9805:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9806:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9807:                     $translation{$1} = $newid;
                   9808:                 }
1.749     raeburn  9809:                 $new_values{$file_name."\0".$newkey} = 
                   9810:                                           $$changes{'activate'}{$newitems[$i]};
                   9811:                 $new_control{$newkey} = $now;
                   9812:             }
                   9813:         }
                   9814:     }
                   9815:     my %todelete;
                   9816:     my %changed_items;
                   9817:     foreach my $action ('delete','update') {
                   9818:         if (exists($$changes{$action})) {
                   9819:             if (ref($$changes{$action}) eq 'HASH') {
                   9820:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9821:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9822:                     if ($action eq 'delete') { 
                   9823:                         $todelete{$itemnum} = 1;
                   9824:                     } else {
                   9825:                         $changed_items{$itemnum} = $key;
                   9826:                     }
                   9827:                 }
1.745     raeburn  9828:             }
                   9829:         }
1.749     raeburn  9830:     }
                   9831:     # get lock on access controls for file.
                   9832:     my $lockhash = {
                   9833:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9834:                                                        ':'.$env{'user.domain'},
                   9835:                    }; 
                   9836:     my $tries = 0;
                   9837:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9838:    
1.1288    damieng  9839:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  9840:         $tries ++;
1.1289    damieng  9841:         sleep(0.1);
1.749     raeburn  9842:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9843:     }
                   9844:     if ($gotlock eq 'ok') {
                   9845:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9846:         my ($tmp)=keys(%curr_permissions);
                   9847:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9848:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9849:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9850:             if (ref($curr_controls) eq 'HASH') {
                   9851:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9852:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9853:                     if (defined($todelete{$itemnum})) {
                   9854:                         push(@deletions,$file_name."\0".$control_item);
                   9855:                     } else {
                   9856:                         if (defined($changed_items{$itemnum})) {
                   9857:                             $new_control{$changed_items{$itemnum}} = $now;
                   9858:                             push(@deletions,$file_name."\0".$control_item);
                   9859:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9860:                         } else {
                   9861:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9862:                         }
                   9863:                     }
1.745     raeburn  9864:                 }
                   9865:             }
                   9866:         }
1.970     raeburn  9867:         my ($group);
                   9868:         if (&is_course($domain,$user)) {
                   9869:             ($group,my $file) = split(/\//,$file_name,2);
                   9870:         }
1.749     raeburn  9871:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9872:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9873:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9874:         #  remove lock
                   9875:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9876:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9877:         my $sqlresult =
1.970     raeburn  9878:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9879:                                     $group);
1.749     raeburn  9880:     } else {
                   9881:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9882:     }
1.749     raeburn  9883:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9884: }
                   9885: 
1.827     raeburn  9886: sub make_public_indefinitely {
1.1271    raeburn  9887:     my (@requrl) = @_;
                   9888:     return &automated_portfile_access('public',\@requrl);
                   9889: }
                   9890: 
                   9891: sub automated_portfile_access {
                   9892:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  9893:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   9894:         return 'invalid';
                   9895:     }
1.1271    raeburn  9896:     my %urls;
                   9897:     if (ref($addsref) eq 'ARRAY') {
                   9898:         foreach my $requrl (@{$addsref}) {
                   9899:             if (&is_portfolio_url($requrl)) {
                   9900:                 unless (exists($urls{$requrl})) {
                   9901:                     $urls{$requrl} = 'add';
                   9902:                 }
                   9903:             }
                   9904:         }
                   9905:     }
                   9906:     if (ref($delsref) eq 'ARRAY') {
                   9907:         foreach my $requrl (@{$delsref}) { 
                   9908:             if (&is_portfolio_url($requrl)) {
                   9909:                 unless (exists($urls{$requrl})) {
                   9910:                     $urls{$requrl} = 'delete'; 
                   9911:                 }
                   9912:             }
                   9913:         }
                   9914:     }
                   9915:     unless (keys(%urls)) {
                   9916:         return 'invalid';
                   9917:     }
                   9918:     my $ip;
                   9919:     if ($accesstype eq 'ip') {
                   9920:         if (ref($info) eq 'HASH') {
                   9921:             if ($info->{'ip'} ne '') {
                   9922:                 $ip = $info->{'ip'};
                   9923:             }
                   9924:         }
                   9925:         if ($ip eq '') {
                   9926:             return 'invalid';
                   9927:         }
                   9928:     }
                   9929:     my $errors;
1.827     raeburn  9930:     my $now = time;
1.1271    raeburn  9931:     my %current_perms;
                   9932:     foreach my $requrl (sort(keys(%urls))) {
                   9933:         my $action;
                   9934:         if ($urls{$requrl} eq 'add') {
                   9935:             $action = 'activate';
                   9936:         } else {
                   9937:             $action = 'none';
                   9938:         }
                   9939:         my $aclnum = 0;
1.827     raeburn  9940:         my (undef,$udom,$unum,$file_name,$group) =
                   9941:             &parse_portfolio_url($requrl);
1.1271    raeburn  9942:         unless (exists($current_perms{$unum.':'.$udom})) {
                   9943:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   9944:         }
                   9945:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  9946:                                                    $group,$file_name);
                   9947:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9948:             my ($num,$scope,$end,$start) = 
                   9949:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  9950:             if ($scope eq $accesstype) {
                   9951:                 if (($start <= $now) && ($end == 0)) {
                   9952:                     if ($accesstype eq 'ip') {
                   9953:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   9954:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   9955:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   9956:                                     if ($urls{$requrl} eq 'add') {
                   9957:                                         $action = 'none';
                   9958:                                         last;
                   9959:                                     } else {
                   9960:                                         $action = 'delete';
                   9961:                                         $aclnum = $num;
                   9962:                                         last;
                   9963:                                     }
                   9964:                                 }
                   9965:                             }
                   9966:                         }
                   9967:                     } elsif ($accesstype eq 'public') {
                   9968:                         if ($urls{$requrl} eq 'add') {
                   9969:                             $action = 'none';
                   9970:                             last;
                   9971:                         } else {
                   9972:                             $action = 'delete';
                   9973:                             $aclnum = $num;
                   9974:                             last;
                   9975:                         }
                   9976:                     }
                   9977:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  9978:                     $action = 'update';
                   9979:                     $aclnum = $num;
1.1271    raeburn  9980:                     last;
1.827     raeburn  9981:                 }
                   9982:             }
                   9983:         }
                   9984:         if ($action eq 'none') {
1.1271    raeburn  9985:             next;
1.827     raeburn  9986:         } else {
                   9987:             my %changes;
                   9988:             my $newend = 0;
                   9989:             my $newstart = $now;
1.1271    raeburn  9990:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  9991:             $changes{$action}{$newkey} = {
1.1271    raeburn  9992:                 type => $accesstype,
1.827     raeburn  9993:                 time => {
                   9994:                     start => $newstart,
                   9995:                     end   => $newend,
                   9996:                 },
                   9997:             };
1.1271    raeburn  9998:             if ($accesstype eq 'ip') {
                   9999:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   10000:             }
1.827     raeburn  10001:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10002:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  10003:             unless ($outcome eq 'ok') {
                   10004:                 $errors .= $outcome.' ';
                   10005:             }
1.827     raeburn  10006:         }
1.1271    raeburn  10007:     }
                   10008:     if ($errors) {
                   10009:         $errors =~ s/\s$//;
                   10010:         return $errors;
1.827     raeburn  10011:     } else {
1.1271    raeburn  10012:         return 'ok';
1.827     raeburn  10013:     }
                   10014: }
                   10015: 
1.745     raeburn  10016: #------------------------------------------------------Get Marked as Read Only
                   10017: 
                   10018: sub get_marked_as_readonly {
                   10019:     my ($domain,$user,$what,$group) = @_;
                   10020:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10021:     my @readonly_files;
1.629     banghart 10022:     my $cmp1=$what;
                   10023:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10024:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10025:         if (defined($group)) {
                   10026:             if ($file_name !~ m-^\Q$group\E/-) {
                   10027:                 next;
                   10028:             }
                   10029:         }
1.561     banghart 10030:         if (ref($value) eq "ARRAY"){
                   10031:             foreach my $stored_what (@{$value}) {
1.629     banghart 10032:                 my $cmp2=$stored_what;
1.759     albertel 10033:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10034:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10035:                 }
1.629     banghart 10036:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10037:                     push(@readonly_files, $file_name);
1.745     raeburn  10038:                     last;
1.563     banghart 10039:                 } elsif (!defined($what)) {
                   10040:                     push(@readonly_files, $file_name);
1.745     raeburn  10041:                     last;
1.561     banghart 10042:                 }
                   10043:             }
1.745     raeburn  10044:         }
1.561     banghart 10045:     }
                   10046:     return @readonly_files;
                   10047: }
1.577     banghart 10048: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10049: 
1.577     banghart 10050: sub get_marked_as_readonly_hash {
1.745     raeburn  10051:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10052:     my %readonly_files;
1.745     raeburn  10053:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10054:         if (defined($group)) {
                   10055:             if ($file_name !~ m-^\Q$group\E/-) {
                   10056:                 next;
                   10057:             }
                   10058:         }
1.577     banghart 10059:         if (ref($value) eq "ARRAY"){
                   10060:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10061:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10062:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10063:                         if ($lock_descriptor eq 'graded') {
                   10064:                             $readonly_files{$file_name} = 'graded';
                   10065:                         } elsif ($lock_descriptor eq 'handback') {
                   10066:                             $readonly_files{$file_name} = 'handback';
                   10067:                         } else {
                   10068:                             if (!exists($readonly_files{$file_name})) {
                   10069:                                 $readonly_files{$file_name} = 'locked';
                   10070:                             }
                   10071:                         }
1.745     raeburn  10072:                     }
1.750     banghart 10073:                 } 
1.577     banghart 10074:             }
                   10075:         } 
                   10076:     }
                   10077:     return %readonly_files;
                   10078: }
1.559     banghart 10079: # ------------------------------------------------------------ Unmark as Read Only
                   10080: 
                   10081: sub unmark_as_readonly {
1.629     banghart 10082:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10083:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10084:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10085:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10086:     my $symb_crs = $what;
                   10087:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10088:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10089:     my ($tmp)=keys(%current_permissions);
                   10090:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10091:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10092:     foreach my $file (@readonly_files) {
1.759     albertel 10093: 	my $clean_file = &declutter_portfile($file);
                   10094: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10095: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10096:         my @new_locks;
                   10097:         my @del_keys;
                   10098:         if (ref($current_locks) eq "ARRAY"){
                   10099:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10100:                 my $compare=$locker;
1.749     raeburn  10101:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10102:                     $compare=join('',@{$locker});
1.746     raeburn  10103:                     if ($compare ne $symb_crs) {
                   10104:                         push(@new_locks, $locker);
                   10105:                     }
1.563     banghart 10106:                 }
                   10107:             }
1.650     albertel 10108:             if (scalar(@new_locks) > 0) {
1.563     banghart 10109:                 $current_permissions{$file} = \@new_locks;
                   10110:             } else {
                   10111:                 push(@del_keys, $file);
1.613     albertel 10112:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10113:                 delete($current_permissions{$file});
1.563     banghart 10114:             }
                   10115:         }
1.561     banghart 10116:     }
1.613     albertel 10117:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10118:     return;
                   10119: }
1.512     banghart 10120: 
1.17      www      10121: # ------------------------------------------------------------ Directory lister
                   10122: 
                   10123: sub dirlist {
1.955     raeburn  10124:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10125:     $uri=~s/^\///;
                   10126:     $uri=~s/\/$//;
1.253     stredwic 10127:     my ($udom, $uname);
1.955     raeburn  10128:     if ($getuserdir) {
1.253     stredwic 10129:         $udom = $userdomain;
                   10130:         $uname = $username;
1.955     raeburn  10131:     } else {
                   10132:         (undef,$udom,$uname)=split(/\//,$uri);
                   10133:         if(defined($userdomain)) {
                   10134:             $udom = $userdomain;
                   10135:         }
                   10136:         if(defined($username)) {
                   10137:             $uname = $username;
                   10138:         }
1.253     stredwic 10139:     }
1.955     raeburn  10140:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10141: 
1.955     raeburn  10142:     $dirRoot = $perlvar{'lonDocRoot'};
                   10143:     if (defined($getpropath)) {
                   10144:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10145:         $dirRoot =~ s/\/$//;
1.955     raeburn  10146:     } elsif (defined($getuserdir)) {
                   10147:         my $subdir=$uname.'__';
                   10148:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10149:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10150:                    ."/$udom/$subdir/$uname";
                   10151:     } elsif (defined($alternateRoot)) {
                   10152:         $dirRoot = $alternateRoot;
1.751     banghart 10153:     }
1.253     stredwic 10154: 
                   10155:     if($udom) {
                   10156:         if($uname) {
1.1135    raeburn  10157:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10158:             if ($uhome eq 'no_host') {
                   10159:                 return ([],'no_host');
                   10160:             }
1.955     raeburn  10161:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10162:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10163:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10164:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10165:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10166:             } else {
                   10167:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10168:             }
1.605     matthew  10169:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10170:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10171:                 @listing_results = split(/:/,$listing);
                   10172:             } else {
                   10173:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10174:             }
1.1135    raeburn  10175:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10176:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10177:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10178:                 return ([],$listing);
                   10179:             } else {
                   10180:                 return (\@listing_results);
1.1135    raeburn  10181:             }
1.955     raeburn  10182:         } elsif(!$alternateRoot) {
1.1136    raeburn  10183:             my (%allusers,%listerror);
1.841     albertel 10184: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10185:  	    foreach my $tryserver (keys(%servers)) {
                   10186:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10187:                                   &escape($udom),$tryserver);
                   10188:                 if ($listing eq 'unknown_cmd') {
                   10189: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10190: 				      $udom, $tryserver);
                   10191:                 } else {
                   10192:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10193:                 }
1.841     albertel 10194: 		if ($listing eq 'unknown_cmd') {
                   10195: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10196: 				      $udom, $tryserver);
                   10197: 		    @listing_results = split(/:/,$listing);
                   10198: 		} else {
                   10199: 		    @listing_results =
                   10200: 			map { &unescape($_); } split(/:/,$listing);
                   10201: 		}
1.1136    raeburn  10202:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10203:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10204:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10205:                     $listerror{$tryserver} = $listing;
                   10206:                 } else {
1.841     albertel 10207: 		    foreach my $line (@listing_results) {
                   10208: 			my ($entry) = split(/&/,$line,2);
                   10209: 			$allusers{$entry} = 1;
                   10210: 		    }
                   10211: 		}
1.253     stredwic 10212:             }
1.1136    raeburn  10213:             my @alluserslist=();
1.800     albertel 10214:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10215:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10216:             }
1.1318    droeschl 10217: 
                   10218:             if (!%listerror) {
                   10219:                 # no errors
                   10220:                 return (\@alluserslist);
                   10221:             } elsif (scalar(keys(%servers)) == 1) {
                   10222:                 # one library server, one error 
                   10223:                 my ($key) = keys(%listerror);
                   10224:                 return (\@alluserslist, $listerror{$key});
                   10225:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10226:                 # con_lost indicates that we might miss data from at least one
                   10227:                 # library server
                   10228:                 return (\@alluserslist, 'con_lost');
                   10229:             } else {
                   10230:                 # multiple library servers and no con_lost -> data should be
                   10231:                 # complete. 
                   10232:                 return (\@alluserslist);
                   10233:             }
                   10234: 
1.253     stredwic 10235:         } else {
1.1136    raeburn  10236:             return ([],'missing username');
1.253     stredwic 10237:         }
1.955     raeburn  10238:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10239:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10240:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10241:         return (\@all_domains);
1.955     raeburn  10242:     } else {
1.1136    raeburn  10243:         return ([],'missing domain');
1.275     stredwic 10244:     }
                   10245: }
                   10246: 
                   10247: # --------------------------------------------- GetFileTimestamp
                   10248: # This function utilizes dirlist and returns the date stamp for
                   10249: # when it was last modified.  It will also return an error of -1
                   10250: # if an error occurs
                   10251: 
                   10252: sub GetFileTimestamp {
1.955     raeburn  10253:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10254:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10255:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10256:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10257:                                     undef,$getuserdir);
                   10258:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10259:         return -1;
                   10260:     }
                   10261:     if (ref($fileref) eq 'ARRAY') {
                   10262:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10263:         # @stats contains first the filename, then the stat output
                   10264:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10265:     } else {
                   10266:         return -1;
1.253     stredwic 10267:     }
1.26      www      10268: }
                   10269: 
1.712     albertel 10270: sub stat_file {
                   10271:     my ($uri) = @_;
1.787     albertel 10272:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10273: 
1.955     raeburn  10274:     my ($udom,$uname,$file);
1.712     albertel 10275:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10276: 	($udom,$uname,$file) =
1.811     albertel 10277: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10278: 	$file = 'userfiles/'.$file;
                   10279:     }
                   10280:     if ($uri =~ m-^/res/-) {
                   10281: 	($udom,$uname) = 
1.807     albertel 10282: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10283: 	$file = $uri;
                   10284:     }
                   10285: 
                   10286:     if (!$udom || !$uname || !$file) {
                   10287: 	# unable to handle the uri
                   10288: 	return ();
                   10289:     }
1.956     raeburn  10290:     my $getpropath;
                   10291:     if ($file =~ /^userfiles\//) {
                   10292:         $getpropath = 1;
                   10293:     }
1.1136    raeburn  10294:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10295:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10296:         return ();
                   10297:     } else {
                   10298:         if (ref($listref) eq 'ARRAY') {
                   10299:             my @stats = split('&',$listref->[0]);
                   10300: 	    shift(@stats); #filename is first
                   10301: 	    return @stats;
                   10302:         }
1.712     albertel 10303:     }
                   10304:     return ();
                   10305: }
                   10306: 
1.1313    raeburn  10307: # --------------------------------------------------------- recursedirs
                   10308: # Recursive function to traverse either a specific user's Authoring Space
                   10309: # or corresponding Published Resource Space, and populate the hash ref:
                   10310: # $dirhashref with URLs of all directories, and if $filehashref hash
                   10311: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   10312: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   10313: # files in Authoring Space.
                   10314: #
                   10315: # Inputs:
                   10316: #
                   10317: # $is_home - true if current server is home server for user's space
                   10318: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   10319: # $docroot - Document root (i.e., /home/httpd/html
                   10320: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   10321: # $relpath - Current path (relative to top level).
                   10322: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   10323: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   10324: #
                   10325: # Returns: nothing
                   10326: #
                   10327: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   10328: #
                   10329: # Currently used by interface/londocs.pm to create linked select boxes for
                   10330: # directory and filename to import a Course "Author" resource into a course, and
                   10331: # also to create linked select boxes for Authoring Space and Directory to choose
                   10332: # save location for creation of a new "standard" problem from the Course Editor.
                   10333: #
                   10334: 
                   10335: sub recursedirs {
                   10336:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   10337:     return unless (ref($dirhashref) eq 'HASH');
                   10338:     my $currpath = $docroot.$toppath;
                   10339:     if ($relpath) {
                   10340:         $currpath .= "/$relpath";
                   10341:     }
                   10342:     my $savefile;
                   10343:     if (ref($filehashref)) {
                   10344:         $savefile = 1;
                   10345:     }
                   10346:     if ($is_home) {
                   10347:         if (opendir(my $dirh,$currpath)) {
                   10348:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   10349:                 next if ($item eq '');
                   10350:                 if (-d "$currpath/$item") {
                   10351:                     my $newpath;
                   10352:                     if ($relpath) {
                   10353:                         $newpath = "$relpath/$item";
                   10354:                     } else {
                   10355:                         $newpath = $item;
                   10356:                     }
                   10357:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10358:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10359:                 } elsif ($savefile) {
                   10360:                     if ($context eq 'priv') {
                   10361:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10362:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10363:                         }
                   10364:                     } else {
                   10365:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   10366:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10367:                         }
                   10368:                     }
                   10369:                 }
                   10370:             }
                   10371:             closedir($dirh);
                   10372:         }
                   10373:     } else {
                   10374:         my ($dirlistref,$listerror) =
                   10375:             &dirlist($toppath.$relpath);
                   10376:         my @dir_lines;
                   10377:         my $dirptr=16384;
                   10378:         if (ref($dirlistref) eq 'ARRAY') {
                   10379:             foreach my $dir_line (sort
                   10380:                               {
                   10381:                                   my ($afile)=split('&',$a,2);
                   10382:                                   my ($bfile)=split('&',$b,2);
                   10383:                                   return (lc($afile) cmp lc($bfile));
                   10384:                               } (@{$dirlistref})) {
                   10385:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   10386:                     split(/\&/,$dir_line,16);
                   10387:                 $item =~ s/\s+$//;
                   10388:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   10389:                 if ($dirptr&$testdir) {
                   10390:                     my $newpath;
                   10391:                     if ($relpath) {
                   10392:                         $newpath = "$relpath/$item";
                   10393:                     } else {
                   10394:                         $relpath = '/';
                   10395:                         $newpath = $item;
                   10396:                     }
                   10397:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10398:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10399:                 } elsif ($savefile) {
                   10400:                     if ($context eq 'priv') {
                   10401:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10402:                             $filehashref->{$relpath}{$item} = 1;
                   10403:                         }
                   10404:                     } else {
                   10405:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   10406:                             $filehashref->{$relpath}{$item} = 1;
                   10407:                         }
                   10408:                     }
                   10409:                 }
                   10410:             }
                   10411:         }
                   10412:     }
                   10413:     return;
                   10414: }
                   10415: 
1.26      www      10416: # -------------------------------------------------------- Value of a Condition
                   10417: 
1.713     albertel 10418: # gets the value of a specific preevaluated condition
                   10419: #    stored in the string  $env{user.state.<cid>}
                   10420: # or looks up a condition reference in the bighash and if if hasn't
                   10421: # already been evaluated recurses into docondval to get the value of
                   10422: # the condition, then memoizing it to 
                   10423: #   $env{user.state.<cid>.<condition>}
1.40      www      10424: sub directcondval {
                   10425:     my $number=shift;
1.620     albertel 10426:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10427: 	&Apache::lonuserstate::evalstate();
                   10428:     }
1.713     albertel 10429:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10430: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10431:     } elsif ($number =~ /^_/) {
                   10432: 	my $sub_condition;
                   10433: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10434: 		&GDBM_READER(),0640)) {
                   10435: 	    $sub_condition=$bighash{'conditions'.$number};
                   10436: 	    untie(%bighash);
                   10437: 	}
                   10438: 	my $value = &docondval($sub_condition);
1.949     raeburn  10439: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10440: 	return $value;
                   10441:     }
1.620     albertel 10442:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10443:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10444:     } else {
                   10445:        return 2;
                   10446:     }
                   10447: }
                   10448: 
1.713     albertel 10449: # get the collection of conditions for this resource
1.26      www      10450: sub condval {
                   10451:     my $condidx=shift;
1.54      www      10452:     my $allpathcond='';
1.713     albertel 10453:     foreach my $cond (split(/\|/,$condidx)) {
                   10454: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10455: 	    $allpathcond.=
                   10456: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10457: 	}
1.191     harris41 10458:     }
1.54      www      10459:     $allpathcond=~s/\|$//;
1.713     albertel 10460:     return &docondval($allpathcond);
                   10461: }
                   10462: 
                   10463: #evaluates an expression of conditions
                   10464: sub docondval {
                   10465:     my ($allpathcond) = @_;
                   10466:     my $result=0;
                   10467:     if ($env{'request.course.id'}
                   10468: 	&& defined($allpathcond)) {
                   10469: 	my $operand='|';
                   10470: 	my @stack;
                   10471: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10472: 	    if ($chunk eq '(') {
                   10473: 		push @stack,($operand,$result);
                   10474: 	    } elsif ($chunk eq ')') {
                   10475: 		my $before=pop @stack;
                   10476: 		if (pop @stack eq '&') {
                   10477: 		    $result=$result>$before?$before:$result;
                   10478: 		} else {
                   10479: 		    $result=$result>$before?$result:$before;
                   10480: 		}
                   10481: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10482: 		$operand=$chunk;
                   10483: 	    } else {
                   10484: 		my $new=directcondval($chunk);
                   10485: 		if ($operand eq '&') {
                   10486: 		    $result=$result>$new?$new:$result;
                   10487: 		} else {
                   10488: 		    $result=$result>$new?$result:$new;
                   10489: 		}
                   10490: 	    }
                   10491: 	}
1.26      www      10492:     }
                   10493:     return $result;
1.421     albertel 10494: }
                   10495: 
                   10496: # ---------------------------------------------------- Devalidate courseresdata
                   10497: 
                   10498: sub devalidatecourseresdata {
                   10499:     my ($coursenum,$coursedomain)=@_;
                   10500:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10501:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10502: }
                   10503: 
1.763     www      10504: 
1.200     www      10505: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10506: #
                   10507: #  Parameters:
                   10508: #      $coursenum    - Number of the course.
                   10509: #      $coursedomain - Domain at which the course was created.
                   10510: #  Returns:
                   10511: #     A hash of the course parameters along (I think) with timestamps
                   10512: #     and version info.
1.877     foxr     10513: 
1.624     albertel 10514: sub get_courseresdata {
                   10515:     my ($coursenum,$coursedomain)=@_;
1.200     www      10516:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10517:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10518:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10519:     my %dumpreply;
1.417     albertel 10520:     unless (defined($cached)) {
1.624     albertel 10521: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10522: 	$result=\%dumpreply;
1.251     albertel 10523: 	my ($tmp) = keys(%dumpreply);
                   10524: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10525: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10526: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10527: 	    return $tmp;
1.416     albertel 10528: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10529: 	    $result=undef;
1.599     albertel 10530: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10531: 	}
                   10532:     }
1.624     albertel 10533:     return $result;
                   10534: }
                   10535: 
1.633     albertel 10536: sub devalidateuserresdata {
                   10537:     my ($uname,$udom)=@_;
                   10538:     my $hashid="$udom:$uname";
                   10539:     &devalidate_cache_new('userres',$hashid);
                   10540: }
                   10541: 
1.624     albertel 10542: sub get_userresdata {
                   10543:     my ($uname,$udom)=@_;
                   10544:     #most student don\'t have any data set, check if there is some data
                   10545:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10546: 
                   10547:     my $hashid="$udom:$uname";
                   10548:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10549:     if (!defined($cached)) {
                   10550: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10551: 	$result=\%resourcedata;
                   10552: 	&do_cache_new('userres',$hashid,$result,600);
                   10553:     }
                   10554:     my ($tmp)=keys(%$result);
                   10555:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10556: 	return $result;
                   10557:     }
                   10558:     #error 2 occurs when the .db doesn't exist
                   10559:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  10560:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   10561: 	    &logthis("<font color=\"blue\">WARNING:".
                   10562: 		     " Trying to get resource data for ".
                   10563: 		     $uname." at ".$udom.": ".
                   10564: 		     $tmp."</font>");
                   10565:         }
1.624     albertel 10566:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10567: 	#&EXT_cache_set($udom,$uname);
                   10568: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10569: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10570:     }
                   10571:     return $tmp;
                   10572: }
1.879     foxr     10573: #----------------------------------------------- resdata - return resource data
                   10574: #  Purpose:
                   10575: #    Return resource data for either users or for a course.
                   10576: #  Parameters:
                   10577: #     $name      - Course/user name.
                   10578: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  10579: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  10580: #     $mapp      - decluttered URL of enclosing map  
                   10581: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   10582: #     $recurseup - Ref to array of map URLs, starting with map containing
                   10583: #                  $mapp up through hierarchy of nested maps to top level map.  
                   10584: #     $courseid  - CourseID (first part of param identifier).
                   10585: #     $modifier  - Middle part of param identifier.
                   10586: #     $what      - Last part of param identifier.
1.879     foxr     10587: #     @which     - Array of names of resources desired.
                   10588: #  Returns:
                   10589: #     The value of the first reasource in @which that is found in the
                   10590: #     resource hash.
                   10591: #  Exceptional Conditions:
                   10592: #     If the $type passed in is not valid (not the string 'course' or 
                   10593: #     'user', an undefined  reference is returned.
                   10594: #     If none of the resources are found, an undef is returned
1.624     albertel 10595: sub resdata {
1.1301    raeburn  10596:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   10597:         $modifier,$what,@which)=@_;
1.624     albertel 10598:     my $result;
                   10599:     if ($type eq 'course') {
                   10600: 	$result=&get_courseresdata($name,$domain);
                   10601:     } elsif ($type eq 'user') {
                   10602: 	$result=&get_userresdata($name,$domain);
                   10603:     }
                   10604:     if (!ref($result)) { return $result; }    
1.251     albertel 10605:     foreach my $item (@which) {
1.1301    raeburn  10606:         if ($item->[1] eq 'course') {
                   10607:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   10608:                 unless ($$recursed) {
1.1302    raeburn  10609:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  10610:                     $$recursed = 1;
                   10611:                 }
                   10612:                 foreach my $item (@${recurseup}) {
                   10613:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   10614:                     last if (defined($result->{$norecursechk}));
                   10615:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   10616:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   10617:                 }
                   10618:             }
                   10619:         }
                   10620:         if (defined($result->{$item->[0]})) {
1.927     albertel 10621: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 10622: 	}
1.250     albertel 10623:     }
1.291     albertel 10624:     return undef;
1.200     www      10625: }
                   10626: 
1.1298    raeburn  10627: sub get_domain_ltitools {
                   10628:     my ($cdom) = @_;
                   10629:     my %ltitools;
                   10630:     my ($result,$cached)=&is_cached_new('ltitools',$cdom);
                   10631:     if (defined($cached)) {
                   10632:         if (ref($result) eq 'HASH') {
                   10633:             %ltitools = %{$result};
                   10634:         }
                   10635:     } else {
                   10636:         my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
                   10637:         if (ref($domconfig{'ltitools'}) eq 'HASH') {
                   10638:             %ltitools = %{$domconfig{'ltitools'}};
                   10639:         }
                   10640:         my $cachetime = 24*60*60;
                   10641:         &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
                   10642:     }
                   10643:     return %ltitools;
                   10644: }
                   10645: 
1.1236    raeburn  10646: sub get_numsuppfiles {
                   10647:     my ($cnum,$cdom,$ignorecache)=@_;
                   10648:     my $hashid=$cnum.':'.$cdom;
                   10649:     my ($suppcount,$cached);
                   10650:     unless ($ignorecache) {
                   10651:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10652:     }
                   10653:     unless (defined($cached)) {
                   10654:         my $chome=&homeserver($cnum,$cdom);
                   10655:         unless ($chome eq 'no_host') {
                   10656:             ($suppcount,my $errors) = (0,0);
                   10657:             my $suppmap = 'supplemental.sequence';
                   10658:             ($suppcount,$errors) = 
                   10659:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10660:         }
                   10661:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10662:     }
                   10663:     return $suppcount;
                   10664: }
                   10665: 
1.379     matthew  10666: #
                   10667: # EXT resource caching routines
                   10668: #
                   10669: 
1.1302    raeburn  10670: {
                   10671: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   10672: #
                   10673: # The course for which we cache
                   10674: my $cachedmapkey='';
                   10675: # The cached recursive maps for this course
                   10676: my %cachedmaps=();
                   10677: # When this was last done
                   10678: my $cachedmaptime='';
                   10679: 
1.379     matthew  10680: sub clear_EXT_cache_status {
1.383     albertel 10681:     &delenv('cache.EXT.');
1.379     matthew  10682: }
                   10683: 
                   10684: sub EXT_cache_status {
                   10685:     my ($target_domain,$target_user) = @_;
1.383     albertel 10686:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10687:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10688:         # We know already the user has no data
                   10689:         return 1;
                   10690:     } else {
                   10691:         return 0;
                   10692:     }
                   10693: }
                   10694: 
                   10695: sub EXT_cache_set {
                   10696:     my ($target_domain,$target_user) = @_;
1.383     albertel 10697:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10698:     #&appenv({$cachename => time});
1.379     matthew  10699: }
                   10700: 
1.28      www      10701: # --------------------------------------------------------- Value of a Variable
1.58      www      10702: sub EXT {
1.715     albertel 10703: 
1.1228    raeburn  10704:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10705:     unless ($varname) { return ''; }
1.218     albertel 10706:     #get real user name/domain, courseid and symb
                   10707:     my $courseid;
1.359     albertel 10708:     my $publicuser;
1.427     www      10709:     if ($symbparm) {
                   10710: 	$symbparm=&get_symb_from_alias($symbparm);
                   10711:     }
1.218     albertel 10712:     if (!($uname && $udom)) {
1.790     albertel 10713:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10714:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10715:     } else {
1.620     albertel 10716: 	$courseid=$env{'request.course.id'};
1.218     albertel 10717:     }
1.48      www      10718:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10719:     my $rest;
1.320     albertel 10720:     if (defined($therest[0])) {
1.48      www      10721:        $rest=join('.',@therest);
                   10722:     } else {
                   10723:        $rest='';
                   10724:     }
1.320     albertel 10725: 
1.57      www      10726:     my $qualifierrest=$qualifier;
                   10727:     if ($rest) { $qualifierrest.='.'.$rest; }
                   10728:     my $spacequalifierrest=$space;
                   10729:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      10730:     if ($realm eq 'user') {
1.48      www      10731: # --------------------------------------------------------------- user.resource
                   10732: 	if ($space eq 'resource') {
1.651     albertel 10733: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   10734: 		  || defined($Apache::lonhomework::parsing_a_task))
                   10735: 		 &&
1.744     albertel 10736: 		 ($symbparm eq &symbread()) ) {	
                   10737: 		# if we are in the middle of processing the resource the
                   10738: 		# get the value we are planning on committing
                   10739:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   10740:                     return $Apache::lonhomework::results{$qualifierrest};
                   10741:                 } else {
                   10742:                     return $Apache::lonhomework::history{$qualifierrest};
                   10743:                 }
1.335     albertel 10744: 	    } else {
1.359     albertel 10745: 		my %restored;
1.620     albertel 10746: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 10747: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   10748: 		} else {
                   10749: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   10750: 		}
1.335     albertel 10751: 		return $restored{$qualifierrest};
                   10752: 	    }
1.48      www      10753: # ----------------------------------------------------------------- user.access
                   10754:         } elsif ($space eq 'access') {
1.218     albertel 10755: 	    # FIXME - not supporting calls for a specific user
1.48      www      10756:             return &allowed($qualifier,$rest);
                   10757: # ------------------------------------------ user.preferences, user.environment
                   10758:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 10759: 	    if (($uname eq $env{'user.name'}) &&
                   10760: 		($udom eq $env{'user.domain'})) {
                   10761: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10762: 	    } else {
1.359     albertel 10763: 		my %returnhash;
                   10764: 		if (!$publicuser) {
                   10765: 		    %returnhash=&userenvironment($udom,$uname,
                   10766: 						 $qualifierrest);
                   10767: 		}
1.218     albertel 10768: 		return $returnhash{$qualifierrest};
                   10769: 	    }
1.48      www      10770: # ----------------------------------------------------------------- user.course
                   10771:         } elsif ($space eq 'course') {
1.218     albertel 10772: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10773:             return $env{join('.',('request.course',$qualifier))};
1.48      www      10774: # ------------------------------------------------------------------- user.role
                   10775:         } elsif ($space eq 'role') {
1.218     albertel 10776: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10777:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      10778:             if ($qualifier eq 'value') {
                   10779: 		return $role;
                   10780:             } elsif ($qualifier eq 'extent') {
                   10781:                 return $where;
                   10782:             }
                   10783: # ----------------------------------------------------------------- user.domain
                   10784:         } elsif ($space eq 'domain') {
1.218     albertel 10785:             return $udom;
1.48      www      10786: # ------------------------------------------------------------------- user.name
                   10787:         } elsif ($space eq 'name') {
1.218     albertel 10788:             return $uname;
1.48      www      10789: # ---------------------------------------------------- Any other user namespace
1.29      www      10790:         } else {
1.359     albertel 10791: 	    my %reply;
                   10792: 	    if (!$publicuser) {
                   10793: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10794: 	    }
                   10795: 	    return $reply{$qualifierrest};
1.48      www      10796:         }
1.236     www      10797:     } elsif ($realm eq 'query') {
                   10798: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10799:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10800: 						[$spacequalifierrest]);
1.620     albertel 10801: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10802:    } elsif ($realm eq 'request') {
1.48      www      10803: # ------------------------------------------------------------- request.browser
                   10804:         if ($space eq 'browser') {
1.1145    bisitz   10805:             return $env{'browser.'.$qualifier};
1.57      www      10806: # ------------------------------------------------------------ request.filename
                   10807:         } else {
1.620     albertel 10808:             return $env{'request.'.$spacequalifierrest};
1.29      www      10809:         }
1.28      www      10810:     } elsif ($realm eq 'course') {
1.48      www      10811: # ---------------------------------------------------------- course.description
1.620     albertel 10812:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10813:     } elsif ($realm eq 'resource') {
1.165     www      10814: 
1.620     albertel 10815: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10816: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10817: 	}
1.693     albertel 10818: 
1.1232    raeburn  10819:         if ($qualifier eq '') {
                   10820: 	    if ($space eq 'title') {
                   10821: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10822: 	        return &gettitle($symbparm);
                   10823: 	    }
1.693     albertel 10824: 	
1.1232    raeburn  10825: 	    if ($space eq 'map') {
                   10826: 	        my ($map) = &decode_symb($symbparm);
                   10827: 	        return &symbread($map);
                   10828: 	    }
                   10829:             if ($space eq 'maptitle') {
                   10830:                 my ($map) = &decode_symb($symbparm);
                   10831:                 return &gettitle($map);
                   10832:             }
                   10833: 	    if ($space eq 'filename') {
                   10834: 	        if ($symbparm) {
                   10835: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10836: 	        }
                   10837: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10838: 	    }
1.1232    raeburn  10839: 
1.1233    raeburn  10840:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10841:                 if ($space eq 'visibleparts') {
                   10842:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10843:                     my $item;
                   10844:                     if (ref($navmap)) {
                   10845:                         my $res = $navmap->getBySymb($symbparm);
                   10846:                         my $parts = $res->parts();
                   10847:                         if (ref($parts) eq 'ARRAY') {
                   10848:                             $item = join(',',@{$parts});
                   10849:                         }
                   10850:                         undef($navmap);
1.1232    raeburn  10851:                     }
1.1233    raeburn  10852:                     return $item;
1.1232    raeburn  10853:                 }
                   10854:             }
                   10855:         }
1.693     albertel 10856: 
1.1301    raeburn  10857: 	my ($section, $group, @groups, @recurseup, $recursed);
                   10858: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  10859:         if (($courseid eq '') && ($cid)) {
                   10860:             $courseid = $cid;
                   10861:         }
                   10862: 	if (($symbparm && $courseid) && 
                   10863: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      10864: 
1.218     albertel 10865: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10866: 
1.60      www      10867: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10868: 	    my $symbp=$symbparm;
1.1301    raeburn  10869: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10870: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  10871:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 10872: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 10873: 	    if (($env{'user.name'} eq $uname) &&
                   10874: 		($env{'user.domain'} eq $udom)) {
                   10875: 		$section=$env{'request.course.sec'};
1.733     raeburn  10876:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10877:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10878: 	    } else {
1.539     albertel 10879: 		if (! defined($usection)) {
1.551     albertel 10880: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10881: 		} else {
                   10882: 		    $section = $usection;
                   10883: 		}
1.733     raeburn  10884:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10885: 	    }
                   10886: 
                   10887: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10888: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  10889:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 10890: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10891: 
1.593     albertel 10892: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10893: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  10894:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 10895: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10896: 
1.60      www      10897: # ----------------------------------------------------------- first, check user
1.624     albertel 10898: 
1.1301    raeburn  10899: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   10900:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 10901: 				       ([$courselevelr,'resource'],
                   10902: 					[$courselevelm,'map'     ],
1.1301    raeburn  10903:                                         [$courseleveli,'map'     ],
1.927     albertel 10904: 					[$courselevel, 'course'  ]));
1.931     albertel 10905: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10906: 
1.594     albertel 10907: # ------------------------------------------------ second, check some of course
1.684     raeburn  10908:             my $coursereply;
1.691     raeburn  10909:             if (@groups > 0) {
                   10910:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  10911:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   10912:                                        $mapp,\$recursed,\@recurseup);
                   10913:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  10914:             }
1.96      www      10915: 
1.684     raeburn  10916: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10917: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  10918: 				  'course',$mapp,\$recursed,\@recurseup,
                   10919:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 10920: 				  ([$seclevelr,   'resource'],
                   10921: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  10922:                                    [$secleveli,   'map'     ],
1.927     albertel 10923: 				   [$seclevel,    'course'  ],
                   10924: 				   [$courselevelr,'resource']));
                   10925: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10926: 
1.60      www      10927: # ------------------------------------------------------ third, check map parms
1.218     albertel 10928: 	    my %parmhash=();
                   10929: 	    my $thisparm='';
                   10930: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10931: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10932: 		    &GDBM_READER(),0640)) {
1.218     albertel 10933: 		$thisparm=$parmhash{$symbparm};
                   10934: 		untie(%parmhash);
                   10935: 	    }
1.927     albertel 10936: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10937: 	}
1.594     albertel 10938: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  10939:  
                   10940:         my $what = $spacequalifierrest;
                   10941: 	$what=~s/\./\_/;
1.282     albertel 10942: 	my $filename;
                   10943: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10944: 	if ($symbparm) {
1.409     www      10945: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10946: 	} else {
1.620     albertel 10947: 	    $filename=$env{'request.filename'};
1.282     albertel 10948: 	}
1.1301    raeburn  10949: 	my $metadata=&metadata($filename,$what);
1.927     albertel 10950: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1301    raeburn  10951: 	$metadata=&metadata($filename,'parameter_'.$what);
1.927     albertel 10952: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10953: 
1.1301    raeburn  10954: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 10955: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10956: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10957: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10958: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  10959: 				     'course',$mapp,\$recursed,\@recurseup,
                   10960:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 10961: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  10962:                                       [$courseleveli,'map'   ],
1.927     albertel 10963: 				      [$courselevel, 'course']));
                   10964: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10965: 	}
1.145     www      10966: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10967: 	unless ($space eq '0') {
1.336     albertel 10968: 	    my @parts=split(/_/,$space);
                   10969: 	    my $id=pop(@parts);
                   10970: 	    my $part=join('_',@parts);
                   10971: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10972: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10973: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10974: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10975: 	}
1.395     albertel 10976: 	if ($recurse) { return undef; }
                   10977: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10978: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10979: # ---------------------------------------------------- Any other user namespace
                   10980:     } elsif ($realm eq 'environment') {
                   10981: # ----------------------------------------------------------------- environment
1.620     albertel 10982: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10983: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10984: 	} else {
1.770     albertel 10985: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10986: 		return '';
                   10987: 	    }
1.219     albertel 10988: 	    my %returnhash=&userenvironment($udom,$uname,
                   10989: 					    $spacequalifierrest);
                   10990: 	    return $returnhash{$spacequalifierrest};
                   10991: 	}
1.28      www      10992:     } elsif ($realm eq 'system') {
1.48      www      10993: # ----------------------------------------------------------------- system.time
                   10994: 	if ($space eq 'time') {
                   10995: 	    return time;
                   10996:         }
1.696     albertel 10997:     } elsif ($realm eq 'server') {
                   10998: # ----------------------------------------------------------------- system.time
                   10999: 	if ($space eq 'name') {
                   11000: 	    return $ENV{'SERVER_NAME'};
                   11001:         }
1.28      www      11002:     }
1.48      www      11003:     return '';
1.61      www      11004: }
                   11005: 
1.927     albertel 11006: sub get_reply {
                   11007:     my ($reply_value) = @_;
1.940     raeburn  11008:     if (ref($reply_value) eq 'ARRAY') {
                   11009:         if (wantarray) {
                   11010: 	    return @$reply_value;
                   11011:         }
                   11012:         return $reply_value->[0];
                   11013:     } else {
                   11014:         return $reply_value;
1.927     albertel 11015:     }
                   11016: }
                   11017: 
1.691     raeburn  11018: sub check_group_parms {
1.1301    raeburn  11019:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   11020:         $recursed,$recurseupref) = @_;
                   11021:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   11022:                   [$what,'course']);
                   11023:     my $coursereply;
1.691     raeburn  11024:     foreach my $group (@{$groups}) {
1.1301    raeburn  11025:         my @groupitems = ();
1.691     raeburn  11026:         foreach my $level (@levels) {
1.927     albertel 11027:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11028:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11029:         }
1.1301    raeburn  11030:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11031:                                    $env{'course.'.$courseid.'.domain'},
                   11032:                                    'course',$mapp,$recursed,$recurseupref,
                   11033:                                    $courseid,'.['.$group.'].',$what,
                   11034:                                    @groupitems);
                   11035:         last if (defined($coursereply));
1.691     raeburn  11036:     }
                   11037:     return $coursereply;
                   11038: }
                   11039: 
1.1301    raeburn  11040: sub get_map_hierarchy {
1.1302    raeburn  11041:     my ($mapname,$courseid) = @_;
                   11042:     my @recurseup = ();
1.1301    raeburn  11043:     if ($mapname) {
1.1302    raeburn  11044:         if (($cachedmapkey eq $courseid) &&
                   11045:             (abs($cachedmaptime-time)<5)) {
                   11046:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   11047:                 return @{$cachedmaps{$mapname}};
                   11048:             }
                   11049:         }
1.1301    raeburn  11050:         my $navmap = Apache::lonnavmaps::navmap->new();
                   11051:         if (ref($navmap)) {
                   11052:             @recurseup = $navmap->recurseup_maps($mapname);
                   11053:             undef($navmap);
1.1302    raeburn  11054:             $cachedmaps{$mapname} = \@recurseup;
                   11055:             $cachedmaptime=time;
                   11056:             $cachedmapkey=$courseid;
1.1301    raeburn  11057:         }
                   11058:     }
                   11059:     return @recurseup;
                   11060: }
                   11061: 
1.1302    raeburn  11062: }
                   11063: 
1.691     raeburn  11064: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11065:     my ($courseid,@groups) = @_;
                   11066:     @groups = sort(@groups);
1.691     raeburn  11067:     return @groups;
                   11068: }
                   11069: 
1.395     albertel 11070: sub packages_tab_default {
                   11071:     my ($uri,$varname)=@_;
                   11072:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11073: 
                   11074:     my (@extension,@specifics,$do_default);
                   11075:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11076: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11077: 	if ($pack_type eq 'default') {
                   11078: 	    $do_default=1;
                   11079: 	} elsif ($pack_type eq 'extension') {
                   11080: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11081: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11082: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11083: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11084: 	}
                   11085:     }
                   11086:     # first look for a package that matches the requested part id
                   11087:     foreach my $package (@specifics) {
                   11088: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11089: 	next if ($pack_part ne $part);
                   11090: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11091: 	    return $packagetab{"$pack_type&$name&default"};
                   11092: 	}
                   11093:     }
                   11094:     # look for any possible matching non extension_ package
                   11095:     foreach my $package (@specifics) {
                   11096: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11097: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11098: 	    return $packagetab{"$pack_type&$name&default"};
                   11099: 	}
1.585     albertel 11100: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11101: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11102: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11103: 	}
                   11104:     }
1.738     albertel 11105:     # look for any posible extension_ match
                   11106:     foreach my $package (@extension) {
                   11107: 	my ($package,$pack_type)=@{$package};
                   11108: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11109: 	    return $packagetab{"$pack_type&$name&default"};
                   11110: 	}
                   11111: 	if (defined($packagetab{$package."&$name&default"})) {
                   11112: 	    return $packagetab{$package."&$name&default"};
                   11113: 	}
                   11114:     }
                   11115:     # look for a global default setting
                   11116:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11117: 	return $packagetab{"default&$name&default"};
                   11118:     }
1.395     albertel 11119:     return undef;
                   11120: }
                   11121: 
1.334     albertel 11122: sub add_prefix_and_part {
                   11123:     my ($prefix,$part)=@_;
                   11124:     my $keyroot;
                   11125:     if (defined($prefix) && $prefix !~ /^__/) {
                   11126: 	# prefix that has a part already
                   11127: 	$keyroot=$prefix;
                   11128:     } elsif (defined($prefix)) {
                   11129: 	# prefix that is missing a part
                   11130: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11131:     } else {
                   11132: 	# no prefix at all
                   11133: 	if (defined($part)) { $keyroot='_'.$part; }
                   11134:     }
                   11135:     return $keyroot;
                   11136: }
                   11137: 
1.71      www      11138: # ---------------------------------------------------------------- Get metadata
                   11139: 
1.599     albertel 11140: my %metaentry;
1.1070    www      11141: my %importedpartids;
1.71      www      11142: sub metadata {
1.176     www      11143:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11144:     $uri=&declutter($uri);
1.288     albertel 11145:     # if it is a non metadata possible uri return quickly
1.529     albertel 11146:     if (($uri eq '') || 
                   11147: 	(($uri =~ m|^/*adm/|) && 
1.1298    raeburn  11148: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|exttools?)$})) ||
1.1108    raeburn  11149:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11150: 	return undef;
                   11151:     }
1.1261    raeburn  11152:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11153: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11154: 	return undef;
1.288     albertel 11155:     }
1.73      www      11156:     my $filename=$uri;
                   11157:     $uri=~s/\.meta$//;
1.172     www      11158: #
                   11159: # Is the metadata already cached?
1.177     www      11160: # Look at timestamp of caching
1.172     www      11161: # Everything is cached by the main uri, libraries are never directly cached
                   11162: #
1.428     albertel 11163:     if (!defined($liburi)) {
1.599     albertel 11164: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11165: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11166:     }
                   11167:     {
1.1069    www      11168: # Imported parts would go here
1.1070    www      11169:         my %importedids=();
                   11170:         my @origfileimportpartids=();
1.1069    www      11171:         my $importedparts=0;
1.172     www      11172: #
                   11173: # Is this a recursive call for a library?
                   11174: #
1.599     albertel 11175: #	if (! exists($metacache{$uri})) {
                   11176: #	    $metacache{$uri}={};
                   11177: #	}
1.924     albertel 11178: 	my $cachetime = 60*60;
1.171     www      11179:         if ($liburi) {
                   11180: 	    $liburi=&declutter($liburi);
                   11181:             $filename=$liburi;
1.401     bowersj2 11182:         } else {
1.599     albertel 11183: 	    &devalidate_cache_new('meta',$uri);
                   11184: 	    undef(%metaentry);
1.401     bowersj2 11185: 	}
1.140     www      11186:         my %metathesekeys=();
1.73      www      11187:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11188: 	my $metastring;
1.1140    www      11189: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11190: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11191: 	    $metastring = 
1.929     albertel 11192: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11193: 					  ('grade_target' => 'meta'));
                   11194: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11195: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11196:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11197: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11198: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11199: 	    $metastring=&getfile($file);
1.489     albertel 11200: 	}
1.208     albertel 11201:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11202:         my $token;
1.140     www      11203:         undef %metathesekeys;
1.71      www      11204:         while ($token=$parser->get_token) {
1.339     albertel 11205: 	    if ($token->[0] eq 'S') {
                   11206: 		if (defined($token->[2]->{'package'})) {
1.172     www      11207: #
                   11208: # This is a package - get package info
                   11209: #
1.339     albertel 11210: 		    my $package=$token->[2]->{'package'};
                   11211: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11212: 		    if (defined($token->[2]->{'id'})) { 
                   11213: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11214: 		    }
1.599     albertel 11215: 		    if ($metaentry{':packages'}) {
                   11216: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11217: 		    } else {
1.599     albertel 11218: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11219: 		    }
1.736     albertel 11220: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11221: 			my $part=$keyroot;
                   11222: 			$part=~s/^\_//;
1.736     albertel 11223: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11224: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11225: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11226: 			    # ignore package.tab specified default values
                   11227:                             # here &package_tab_default() will fetch those
                   11228: 			    if ($subp eq 'default') { next; }
1.736     albertel 11229: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11230: 			    my $unikey;
                   11231: 			    if ($pack =~ /_0$/) {
                   11232: 				$unikey='parameter_0_'.$name;
                   11233: 				$part=0;
                   11234: 			    } else {
                   11235: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11236: 			    }
1.339     albertel 11237: 			    if ($subp eq 'display') {
                   11238: 				$value.=' [Part: '.$part.']';
                   11239: 			    }
1.599     albertel 11240: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11241: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11242: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11243: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11244: 			    }
1.599     albertel 11245: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11246: 				$metaentry{':'.$unikey}=
                   11247: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11248: 			    }
1.339     albertel 11249: 			}
                   11250: 		    }
                   11251: 		} else {
1.172     www      11252: #
                   11253: # This is not a package - some other kind of start tag
1.339     albertel 11254: #
                   11255: 		    my $entry=$token->[1];
1.1068    www      11256: 		    my $unikey='';
1.175     www      11257: 
1.339     albertel 11258: 		    if ($entry eq 'import') {
1.175     www      11259: #
                   11260: # Importing a library here
1.339     albertel 11261: #
1.1067    www      11262:                         my $location=$parser->get_text('/import');
                   11263:                         my $dir=$filename;
                   11264:                         $dir=~s|[^/]*$||;
                   11265:                         $location=&filelocation($dir,$location);
1.1069    www      11266:                        
1.1068    www      11267:                         my $importmode=$token->[2]->{'importmode'};
                   11268:                         if ($importmode eq 'problem') {
1.1069    www      11269: # Import as problem/response
1.1068    www      11270:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11271:                         } elsif ($importmode eq 'part') {
                   11272: # Import as part(s)
1.1069    www      11273:                            $importedparts=1;
                   11274: # We need to get the original file and the imported file to get the part order correct
                   11275: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   11276: # Load and inspect original file
1.1070    www      11277:                            if ($#origfileimportpartids<0) {
                   11278:                               undef(%importedpartids);
                   11279:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11280:                               my $origfile=&getfile($origfilelocation);
                   11281:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11282:                            }
                   11283: 
1.1069    www      11284: # Load and inspect imported file
                   11285:                            my $impfile=&getfile($location);
                   11286:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11287:                            if ($#impfilepartids>=0) {
                   11288: # This problem had parts
1.1070    www      11289:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11290:                            } else {
                   11291: # Importing by turning a single problem into a problem part
                   11292: # It gets the import-tags ID as part-ID
                   11293:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11294:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11295:                            }
1.1068    www      11296:                         } else {
                   11297: # Normal import
                   11298:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11299:                            if (defined($token->[2]->{'id'})) {
                   11300:                               $unikey.='_'.$token->[2]->{'id'};
                   11301:                            }
1.1067    www      11302:                         }
                   11303: 
1.339     albertel 11304: 			if ($depthcount<20) {
1.736     albertel 11305: 			    my $metadata = 
                   11306: 				&metadata($uri,'keys', $location,$unikey,
                   11307: 					  $depthcount+1);
                   11308: 			    foreach my $meta (split(',',$metadata)) {
                   11309: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11310: 				$metathesekeys{$meta}=1;
1.339     albertel 11311: 			    }
1.1068    www      11312: 			
                   11313:                         }
1.1067    www      11314: 		    } else {
                   11315: #
                   11316: # Not importing, some other kind of non-package, non-library start tag
                   11317: # 
                   11318:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11319:                         if (defined($token->[2]->{'id'})) {
                   11320:                             $unikey.='_'.$token->[2]->{'id'};
                   11321:                         }
1.339     albertel 11322: 			if (defined($token->[2]->{'name'})) { 
                   11323: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11324: 			}
                   11325: 			$metathesekeys{$unikey}=1;
1.736     albertel 11326: 			foreach my $param (@{$token->[3]}) {
                   11327: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11328: 				$token->[2]->{$param};
1.339     albertel 11329: 			}
                   11330: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11331: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11332: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11333: 		 # only ws inside the tag, and not in default, so use default
                   11334: 		 # as value
1.599     albertel 11335: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11336: 			} elsif ( $internaltext =~ /\S/ ) {
                   11337: 		  # something interesting inside the tag
                   11338: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11339: 			} else {
1.908     albertel 11340: 		  # no interesting values, don't set a default
1.339     albertel 11341: 			}
1.172     www      11342: # end of not-a-package not-a-library import
1.339     albertel 11343: 		    }
1.172     www      11344: # end of not-a-package start tag
1.339     albertel 11345: 		}
1.172     www      11346: # the next is the end of "start tag"
1.339     albertel 11347: 	    }
                   11348: 	}
1.483     albertel 11349: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11350: 	$extension = lc($extension);
                   11351: 	if ($extension eq 'htm') { $extension='html'; }
                   11352: 
1.737     albertel 11353: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11354: 	    #no specific packages #how's our extension
                   11355: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11356: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11357: 					 \%metathesekeys);
                   11358: 	}
1.883     albertel 11359: 
                   11360: 	if (!exists($metaentry{':packages'})
                   11361: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11362: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11363: 		#no specific packages well let's get default then
                   11364: 		if ($key!~/^default&/) { next; }
1.488     albertel 11365: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11366: 					     \%metathesekeys);
                   11367: 	    }
                   11368: 	}
1.338     www      11369: # are there custom rights to evaluate
1.599     albertel 11370: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11371: 
1.338     www      11372:     #
                   11373:     # Importing a rights file here
1.339     albertel 11374:     #
                   11375: 	    unless ($depthcount) {
1.599     albertel 11376: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11377: 		my $dir=$filename;
                   11378: 		$dir=~s|[^/]*$||;
                   11379: 		$location=&filelocation($dir,$location);
1.736     albertel 11380: 		my $rights_metadata =
                   11381: 		    &metadata($uri,'keys',$location,'_rights',
                   11382: 			      $depthcount+1);
                   11383: 		foreach my $rights (split(',',$rights_metadata)) {
                   11384: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11385: 		    $metathesekeys{$rights}=1;
1.339     albertel 11386: 		}
                   11387: 	    }
                   11388: 	}
1.737     albertel 11389: 	# uniqifiy package listing
                   11390: 	my %seen;
                   11391: 	my @uniq_packages =
                   11392: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11393: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11394: 
1.1070    www      11395:         if ($importedparts) {
                   11396: # We had imported parts and need to rebuild partorder
                   11397:            $metaentry{':partorder'}='';
                   11398:            $metathesekeys{'partorder'}=1;
                   11399:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   11400:                if ($origfileimportpartids[$index] eq 'part') {
                   11401: # original part, part of the problem
                   11402:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   11403:                } else {
                   11404: # we have imported parts at this position
                   11405:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   11406:                }
                   11407:            }
                   11408:            $metaentry{':partorder'}=~s/^\,//;
                   11409:         }
                   11410: 
1.737     albertel 11411: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11412: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  11413: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 11414: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      11415: # this is the end of "was not already recently cached
1.71      www      11416:     }
1.599     albertel 11417:     return $metaentry{':'.$what};
1.261     albertel 11418: }
                   11419: 
1.488     albertel 11420: sub metadata_create_package_def {
1.483     albertel 11421:     my ($uri,$key,$package,$metathesekeys)=@_;
                   11422:     my ($pack,$name,$subp)=split(/\&/,$key);
                   11423:     if ($subp eq 'default') { next; }
                   11424:     
1.599     albertel 11425:     if (defined($metaentry{':packages'})) {
                   11426: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 11427:     } else {
1.599     albertel 11428: 	$metaentry{':packages'}=$package;
1.483     albertel 11429:     }
                   11430:     my $value=$packagetab{$key};
                   11431:     my $unikey;
                   11432:     $unikey='parameter_0_'.$name;
1.599     albertel 11433:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 11434:     $$metathesekeys{$unikey}=1;
1.599     albertel 11435:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11436: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 11437:     }
1.599     albertel 11438:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   11439: 	$metaentry{':'.$unikey}=
                   11440: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 11441:     }
                   11442: }
                   11443: 
1.261     albertel 11444: sub metadata_generate_part0 {
                   11445:     my ($metadata,$metacache,$uri) = @_;
                   11446:     my %allnames;
1.737     albertel 11447:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 11448: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 11449: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   11450: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 11451: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 11452: 	    $allnames{$name}=$part;
                   11453: 	  }
                   11454: 	}
                   11455:     }
                   11456:     foreach my $name (keys(%allnames)) {
                   11457:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 11458:       my $key=":parameter_0_$name";
1.261     albertel 11459:       $$metacache{"$key.part"}='0';
                   11460:       $$metacache{"$key.name"}=$name;
1.428     albertel 11461:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 11462: 					   $allnames{$name}.'_'.$name.
                   11463: 					   '.type'};
1.428     albertel 11464:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 11465: 			     '.display'};
1.644     www      11466:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11467:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11468:       $$metacache{"$key.display"}=$olddis;
                   11469:     }
1.71      www      11470: }
                   11471: 
1.764     albertel 11472: # ------------------------------------------------------ Devalidate title cache
                   11473: 
                   11474: sub devalidate_title_cache {
                   11475:     my ($url)=@_;
                   11476:     if (!$env{'request.course.id'}) { return; }
                   11477:     my $symb=&symbread($url);
                   11478:     if (!$symb) { return; }
                   11479:     my $key=$env{'request.course.id'}."\0".$symb;
                   11480:     &devalidate_cache_new('title',$key);
                   11481: }
                   11482: 
1.1014    droeschl 11483: # ------------------------------------------------- Get the title of a course
                   11484: 
                   11485: sub current_course_title {
                   11486:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11487: }
1.301     www      11488: # ------------------------------------------------- Get the title of a resource
                   11489: 
                   11490: sub gettitle {
                   11491:     my $urlsymb=shift;
                   11492:     my $symb=&symbread($urlsymb);
1.534     albertel 11493:     if ($symb) {
1.620     albertel 11494: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11495: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11496: 	if (defined($cached)) { 
                   11497: 	    return $result;
                   11498: 	}
1.534     albertel 11499: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11500: 	my $title='';
1.907     albertel 11501: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11502: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11503: 	} else {
                   11504: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11505: 		    &GDBM_READER(),0640)) {
                   11506: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11507: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11508: 		untie(%bighash);
                   11509: 	    }
1.534     albertel 11510: 	}
                   11511: 	$title=~s/\&colon\;/\:/gs;
                   11512: 	if ($title) {
1.1159    www      11513: # Remember both $symb and $title for dynamic metadata
                   11514:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11515:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11516: # Cache this title and then return it
1.599     albertel 11517: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11518: 	}
                   11519: 	$urlsymb=$url;
                   11520:     }
                   11521:     my $title=&metadata($urlsymb,'title');
                   11522:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11523:     return $title;
1.301     www      11524: }
1.613     albertel 11525: 
1.614     albertel 11526: sub get_slot {
                   11527:     my ($which,$cnum,$cdom)=@_;
                   11528:     if (!$cnum || !$cdom) {
1.790     albertel 11529: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11530: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11531: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11532:     }
1.703     albertel 11533:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11534:     my %slotinfo;
                   11535:     if (exists($remembered{$key})) {
                   11536: 	$slotinfo{$which} = $remembered{$key};
                   11537:     } else {
                   11538: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11539: 	&Apache::lonhomework::showhash(%slotinfo);
                   11540: 	my ($tmp)=keys(%slotinfo);
                   11541: 	if ($tmp=~/^error:/) { return (); }
                   11542: 	$remembered{$key} = $slotinfo{$which};
                   11543:     }
1.616     albertel 11544:     if (ref($slotinfo{$which}) eq 'HASH') {
                   11545: 	return %{$slotinfo{$which}};
                   11546:     }
                   11547:     return $slotinfo{$which};
1.614     albertel 11548: }
1.1150    raeburn  11549: 
                   11550: sub get_reservable_slots {
                   11551:     my ($cnum,$cdom,$uname,$udom) = @_;
                   11552:     my $now = time;
                   11553:     my $reservable_info;
                   11554:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   11555:     if (exists($remembered{$key})) {
                   11556:         $reservable_info = $remembered{$key};
                   11557:     } else {
                   11558:         my %resv;
                   11559:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   11560:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   11561:         $reservable_info = \%resv;
                   11562:         $remembered{$key} = $reservable_info;
                   11563:     }
                   11564:     return $reservable_info;
                   11565: }
                   11566: 
                   11567: sub get_course_slots {
                   11568:     my ($cnum,$cdom) = @_;
                   11569:     my $hashid=$cnum.':'.$cdom;
                   11570:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   11571:     if (defined($cached)) {
                   11572:         if (ref($result) eq 'HASH') {
                   11573:             return %{$result};
                   11574:         }
                   11575:     } else {
                   11576:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   11577:         my ($tmp) = keys(%slots);
                   11578:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  11579:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  11580:             return %slots;
                   11581:         }
                   11582:     }
                   11583:     return;
                   11584: }
                   11585: 
                   11586: sub devalidate_slots_cache {
                   11587:     my ($cnum,$cdom)=@_;
                   11588:     my $hashid=$cnum.':'.$cdom;
                   11589:     &devalidate_cache_new('allslots',$hashid);
                   11590: }
                   11591: 
1.1181    raeburn  11592: sub get_coursechange {
                   11593:     my ($cdom,$cnum) = @_;
                   11594:     if ($cdom eq '' || $cnum eq '') {
                   11595:         return unless ($env{'request.course.id'});
                   11596:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11597:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11598:     }
                   11599:     my $hashid=$cdom.'_'.$cnum;
                   11600:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   11601:     if ((defined($cached)) && ($change ne '')) {
                   11602:         return $change;
                   11603:     } else {
                   11604:         my %crshash;
                   11605:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   11606:         if ($crshash{'internal.contentchange'} eq '') {
                   11607:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   11608:             if ($change eq '') {
                   11609:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   11610:                 $change = $crshash{'internal.created'};
                   11611:             }
                   11612:         } else {
                   11613:             $change = $crshash{'internal.contentchange'};
                   11614:         }
                   11615:         my $cachetime = 600;
                   11616:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   11617:     }
                   11618:     return $change;
                   11619: }
                   11620: 
                   11621: sub devalidate_coursechange_cache {
                   11622:     my ($cnum,$cdom)=@_;
                   11623:     my $hashid=$cnum.':'.$cdom;
                   11624:     &devalidate_cache_new('crschange',$hashid);
                   11625: }
                   11626: 
1.31      www      11627: # ------------------------------------------------- Update symbolic store links
                   11628: 
                   11629: sub symblist {
                   11630:     my ($mapname,%newhash)=@_;
1.438     www      11631:     $mapname=&deversion(&declutter($mapname));
1.31      www      11632:     my %hash;
1.620     albertel 11633:     if (($env{'request.course.fn'}) && (%newhash)) {
                   11634:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11635:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  11636: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 11637: 		next if ($url eq 'last_known'
                   11638: 			 && $env{'form.no_update_last_known'});
                   11639: 		$hash{declutter($url)}=&encode_symb($mapname,
                   11640: 						    $newhash{$url}->[1],
                   11641: 						    $newhash{$url}->[0]);
1.191     harris41 11642:             }
1.31      www      11643:             if (untie(%hash)) {
                   11644: 		return 'ok';
                   11645:             }
                   11646:         }
                   11647:     }
                   11648:     return 'error';
1.212     www      11649: }
                   11650: 
                   11651: # --------------------------------------------------------------- Verify a symb
                   11652: 
                   11653: sub symbverify {
1.1190    raeburn  11654:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      11655:     my $thisfn=$thisurl;
1.439     www      11656:     $thisfn=&declutter($thisfn);
1.215     www      11657: # direct jump to resource in page or to a sequence - will construct own symbs
                   11658:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   11659: # check URL part
1.409     www      11660:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      11661: 
1.431     www      11662:     unless ($url eq $thisfn) { return 0; }
1.213     www      11663: 
1.216     www      11664:     $symb=&symbclean($symb);
1.510     www      11665:     $thisurl=&deversion($thisurl);
1.439     www      11666:     $thisfn=&deversion($thisfn);
1.213     www      11667: 
                   11668:     my %bighash;
                   11669:     my $okay=0;
1.431     www      11670: 
1.620     albertel 11671:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11672:                             &GDBM_READER(),0640)) {
1.1204    raeburn  11673:         my $noclutter;
1.1032    raeburn  11674:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   11675:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  11676:             if ($map =~ m{^uploaded/.+\.page$}) {
                   11677:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   11678:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   11679:                 $noclutter = 1;
                   11680:             }
                   11681:         }
                   11682:         my $ids;
                   11683:         if ($noclutter) {
                   11684:             $ids=$bighash{'ids_'.$thisurl};
                   11685:         } else {
                   11686:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  11687:         }
1.1102    raeburn  11688:         unless ($ids) {
                   11689:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   11690:             $ids=$bighash{$idkey};
1.216     www      11691:         }
                   11692:         if ($ids) {
                   11693: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  11694:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  11695:                 $symb =~ s/\?.+$//;
1.1202    raeburn  11696:             }
1.800     albertel 11697: 	    foreach my $id (split(/\,/,$ids)) {
                   11698: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      11699:                if (
                   11700:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  11701:    eq $symb) {
                   11702:                    if (ref($encstate)) {
                   11703:                        $$encstate = $bighash{'encrypted_'.$id};
                   11704:                    }
1.620     albertel 11705: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  11706: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   11707:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  11708: 		       $okay=1;
1.1202    raeburn  11709:                        last;
1.582     albertel 11710: 		   }
                   11711: 	       }
1.216     www      11712: 	   }
                   11713:         }
1.213     www      11714: 	untie(%bighash);
                   11715:     }
                   11716:     return $okay;
1.31      www      11717: }
                   11718: 
1.210     www      11719: # --------------------------------------------------------------- Clean-up symb
                   11720: 
                   11721: sub symbclean {
                   11722:     my $symb=shift;
1.568     albertel 11723:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11724: # remove version from map
                   11725:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11726: 
1.210     www      11727: # remove version from URL
                   11728:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      11729: 
1.507     www      11730: # remove wrapper
                   11731: 
1.510     www      11732:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 11733:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      11734:     return $symb;
1.409     www      11735: }
                   11736: 
                   11737: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 11738: 
                   11739: sub encode_symb {
                   11740:     my ($map,$resid,$url)=@_;
                   11741:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   11742: }
1.409     www      11743: 
                   11744: sub decode_symb {
1.568     albertel 11745:     my $symb=shift;
                   11746:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   11747:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      11748:     return (&fixversion($map),$resid,&fixversion($url));
                   11749: }
                   11750: 
                   11751: sub fixversion {
                   11752:     my $fn=shift;
1.609     banghart 11753:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      11754:     my %bighash;
                   11755:     my $uri=&clutter($fn);
1.620     albertel 11756:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      11757: # is this cached?
1.599     albertel 11758:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      11759:     if (defined($cached)) { return $result; }
                   11760: # unfortunately not cached, or expired
1.620     albertel 11761:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      11762: 	    &GDBM_READER(),0640)) {
                   11763:  	if ($bighash{'version_'.$uri}) {
                   11764:  	    my $version=$bighash{'version_'.$uri};
1.444     www      11765:  	    unless (($version eq 'mostrecent') || 
                   11766: 		    ($version==&getversion($uri))) {
1.440     www      11767:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   11768:  	    }
                   11769:  	}
                   11770:  	untie %bighash;
1.413     www      11771:     }
1.599     albertel 11772:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      11773: }
                   11774: 
                   11775: sub deversion {
                   11776:     my $url=shift;
                   11777:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   11778:     return $url;
1.210     www      11779: }
                   11780: 
1.31      www      11781: # ------------------------------------------------------ Return symb list entry
                   11782: 
                   11783: sub symbread {
1.1282    raeburn  11784:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  11785:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  11786:     if (defined($env{$cache_str})) {
                   11787:         if ($ignorecachednull) {
                   11788:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   11789:         } else {
                   11790:             return $env{$cache_str};
                   11791:         }
                   11792:     }
1.242     www      11793: # no filename provided? try from environment
1.1265    raeburn  11794:     unless ($thisfn) {
1.620     albertel 11795:         if ($env{'request.symb'}) {
                   11796: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 11797: 	}
1.620     albertel 11798: 	$thisfn=$env{'request.filename'};
1.44      www      11799:     }
1.569     albertel 11800:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      11801: # is that filename actually a symb? Verify, clean, and return
                   11802:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 11803: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 11804: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 11805: 	}
1.242     www      11806:     }
1.44      www      11807:     $thisfn=declutter($thisfn);
1.31      www      11808:     my %hash;
1.37      www      11809:     my %bighash;
                   11810:     my $syval='';
1.620     albertel 11811:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  11812:         my $targetfn = $thisfn;
1.609     banghart 11813:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  11814:             $targetfn = 'adm/wrapper/'.$thisfn;
                   11815:         }
1.687     albertel 11816: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   11817: 	    $targetfn=$1;
                   11818: 	}
1.620     albertel 11819:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11820:                       &GDBM_READER(),0640)) {
1.481     raeburn  11821: 	    $syval=$hash{$targetfn};
1.37      www      11822:             untie(%hash);
                   11823:         }
                   11824: # ---------------------------------------------------------- There was an entry
                   11825:         if ($syval) {
1.601     albertel 11826: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 11827: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  11828: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11829: 		    #return $env{$cache_str}='';
1.601     albertel 11830: 		#}    
                   11831: 		#$syval.=$1;
                   11832: 	    #}
1.37      www      11833:         } else {
                   11834: # ------------------------------------------------------- Was not in symb table
1.620     albertel 11835:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11836:                             &GDBM_READER(),0640)) {
1.37      www      11837: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      11838:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      11839:               unless ($ids) { 
                   11840:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      11841:               }
                   11842:               unless ($ids) {
                   11843: # alias?
                   11844: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      11845:               }
1.37      www      11846:               if ($ids) {
                   11847: # ------------------------------------------------------------------- Has ID(s)
                   11848:                  my @possibilities=split(/\,/,$ids);
1.39      www      11849:                  if ($#possibilities==0) {
                   11850: # ----------------------------------------------- There is only one possibility
1.37      www      11851: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 11852: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11853: 						    $resid,$thisfn);
1.1282    raeburn  11854:                      if (ref($possibles) eq 'HASH') {
                   11855:                          $possibles->{$syval} = 1;    
                   11856:                      }
                   11857:                      if ($checkforblock) {
                   11858:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   11859:                          if (@blockers) {
                   11860:                              $syval = '';
                   11861:                              return;
                   11862:                          }
                   11863:                      }
                   11864:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      11865: # ------------------------------------------ There is more than one possibility
                   11866:                      my $realpossible=0;
1.800     albertel 11867:                      foreach my $id (@possibilities) {
                   11868: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  11869:                          my $canaccess;
                   11870:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   11871:                              $canaccess = 1;
                   11872:                          } else { 
                   11873:                              $canaccess = &allowed('bre',$file);
                   11874:                          }
                   11875:                          if ($canaccess) {
                   11876:          		     my ($mapid,$resid)=split(/\./,$id);
                   11877:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11878:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11879: 						             $resid,$thisfn);
                   11880:                                  if (ref($possibles) eq 'HASH') {
                   11881:                                      $possibles->{$syval} = 1;
                   11882:                                  }
                   11883:                                  if ($checkforblock) {
                   11884:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   11885:                                      unless (@blockers > 0) {
                   11886:                                          $syval = $poss_syval;
                   11887:                                          $realpossible++;
                   11888:                                      }
                   11889:                                  } else {
                   11890:                                      $syval = $poss_syval;
                   11891:                                      $realpossible++;
                   11892:                                  }
                   11893:                              }
1.39      www      11894: 			 }
1.191     harris41 11895:                      }
1.39      www      11896: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11897:                  } else {
                   11898:                      $syval='';
1.37      www      11899:                  }
                   11900: 	      }
1.1282    raeburn  11901:               untie(%bighash);
1.481     raeburn  11902:            }
1.31      www      11903:         }
1.62      www      11904:         if ($syval) {
1.620     albertel 11905: 	    return $env{$cache_str}=$syval;
1.62      www      11906:         }
1.31      www      11907:     }
1.949     raeburn  11908:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11909:     return $env{$cache_str}='';
1.31      www      11910: }
                   11911: 
                   11912: # ---------------------------------------------------------- Return random seed
                   11913: 
1.32      www      11914: sub numval {
                   11915:     my $txt=shift;
                   11916:     $txt=~tr/A-J/0-9/;
                   11917:     $txt=~tr/a-j/0-9/;
                   11918:     $txt=~tr/K-T/0-9/;
                   11919:     $txt=~tr/k-t/0-9/;
                   11920:     $txt=~tr/U-Z/0-5/;
                   11921:     $txt=~tr/u-z/0-5/;
                   11922:     $txt=~s/\D//g;
1.564     albertel 11923:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      11924:     return int($txt);
1.368     albertel 11925: }
                   11926: 
1.484     albertel 11927: sub numval2 {
                   11928:     my $txt=shift;
                   11929:     $txt=~tr/A-J/0-9/;
                   11930:     $txt=~tr/a-j/0-9/;
                   11931:     $txt=~tr/K-T/0-9/;
                   11932:     $txt=~tr/k-t/0-9/;
                   11933:     $txt=~tr/U-Z/0-5/;
                   11934:     $txt=~tr/u-z/0-5/;
                   11935:     $txt=~s/\D//g;
                   11936:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11937:     my $total;
                   11938:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 11939:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 11940:     return int($total);
                   11941: }
                   11942: 
1.575     albertel 11943: sub numval3 {
                   11944:     use integer;
                   11945:     my $txt=shift;
                   11946:     $txt=~tr/A-J/0-9/;
                   11947:     $txt=~tr/a-j/0-9/;
                   11948:     $txt=~tr/K-T/0-9/;
                   11949:     $txt=~tr/k-t/0-9/;
                   11950:     $txt=~tr/U-Z/0-5/;
                   11951:     $txt=~tr/u-z/0-5/;
                   11952:     $txt=~s/\D//g;
                   11953:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11954:     my $total;
                   11955:     foreach my $val (@txts) { $total+=$val; }
                   11956:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11957:     return $total;
                   11958: }
                   11959: 
1.675     albertel 11960: sub digest {
                   11961:     my ($data)=@_;
                   11962:     my $digest=&Digest::MD5::md5($data);
                   11963:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11964:     my ($e,$f);
                   11965:     {
                   11966:         use integer;
                   11967:         $e=($a+$b);
                   11968:         $f=($c+$d);
                   11969:         if ($_64bit) {
                   11970:             $e=(($e<<32)>>32);
                   11971:             $f=(($f<<32)>>32);
                   11972:         }
                   11973:     }
                   11974:     if (wantarray) {
                   11975: 	return ($e,$f);
                   11976:     } else {
                   11977: 	my $g;
                   11978: 	{
                   11979: 	    use integer;
                   11980: 	    $g=($e+$f);
                   11981: 	    if ($_64bit) {
                   11982: 		$g=(($g<<32)>>32);
                   11983: 	    }
                   11984: 	}
                   11985: 	return $g;
                   11986:     }
                   11987: }
                   11988: 
1.368     albertel 11989: sub latest_rnd_algorithm_id {
1.675     albertel 11990:     return '64bit5';
1.366     albertel 11991: }
1.32      www      11992: 
1.503     albertel 11993: sub get_rand_alg {
                   11994:     my ($courseid)=@_;
1.790     albertel 11995:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 11996:     if ($courseid) {
1.620     albertel 11997: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 11998:     }
                   11999:     return &latest_rnd_algorithm_id();
                   12000: }
                   12001: 
1.562     albertel 12002: sub validCODE {
                   12003:     my ($CODE)=@_;
                   12004:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12005:     return 0;
                   12006: }
                   12007: 
1.491     albertel 12008: sub getCODE {
1.620     albertel 12009:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12010:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12011: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12012: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12013: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12014:     }
                   12015:     return undef;
                   12016: }
1.1133    foxr     12017: #
                   12018: #  Determines the random seed for a specific context:
                   12019: #
                   12020: # parameters:
                   12021: #   symb      - in course context the symb for the seed.
                   12022: #   course_id - The course id of the form domain_coursenum.
                   12023: #   domain    - Domain for the user.
                   12024: #   course    - Course for the user.
                   12025: #   cenv      - environment of the course.
                   12026: #
                   12027: # NOTE:
                   12028: #   All parameters are picked out of the environment if missing
                   12029: #   or not defined.
                   12030: #   If a symb cannot be determined the current time is used instead.
                   12031: #
                   12032: #  For a given well defined symb, courside, domain, username,
                   12033: #  and course environment, the seed is reproducible.
                   12034: #
1.31      www      12035: sub rndseed {
1.1133    foxr     12036:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12037:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12038:     if (!defined($symb)) {
1.366     albertel 12039: 	unless ($symb=$wsymb) { return time; }
                   12040:     }
1.1146    foxr     12041:     if (!defined $courseid) { 
                   12042: 	$courseid=$wcourseid; 
                   12043:     }
                   12044:     if (!defined $domain) { $domain=$wdomain; }
                   12045:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12046: 
                   12047:     my $which;
                   12048:     if (defined($cenv->{'rndseed'})) {
                   12049: 	$which = $cenv->{'rndseed'};
                   12050:     } else {
                   12051: 	$which =&get_rand_alg($courseid);
                   12052:     }
1.491     albertel 12053:     if (defined(&getCODE())) {
1.1133    foxr     12054: 
1.675     albertel 12055: 	if ($which eq '64bit5') {
                   12056: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12057: 	} elsif ($which eq '64bit4') {
1.575     albertel 12058: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12059: 	} else {
                   12060: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12061: 	}
1.675     albertel 12062:     } elsif ($which eq '64bit5') {
                   12063: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12064:     } elsif ($which eq '64bit4') {
                   12065: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12066:     } elsif ($which eq '64bit3') {
                   12067: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12068:     } elsif ($which eq '64bit2') {
                   12069: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12070:     } elsif ($which eq '64bit') {
                   12071: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12072:     }
                   12073:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12074: }
                   12075: 
                   12076: sub rndseed_32bit {
                   12077:     my ($symb,$courseid,$domain,$username)=@_;
                   12078:     {
                   12079: 	use integer;
                   12080: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12081: 	my $symbseed=numval($symb) << 22;
                   12082: 	my $namechck=unpack("%32C*",$username) << 17;
                   12083: 	my $nameseed=numval($username) << 12;
                   12084: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12085: 	my $courseseed=unpack("%32C*",$courseid);
                   12086: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12087: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12088: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12089: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12090: 	return $num;
                   12091:     }
                   12092: }
                   12093: 
                   12094: sub rndseed_64bit {
                   12095:     my ($symb,$courseid,$domain,$username)=@_;
                   12096:     {
                   12097: 	use integer;
                   12098: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12099: 	my $symbseed=numval($symb) << 10;
                   12100: 	my $namechck=unpack("%32S*",$username);
                   12101: 	
                   12102: 	my $nameseed=numval($username) << 21;
                   12103: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12104: 	my $courseseed=unpack("%32S*",$courseid);
                   12105: 	
                   12106: 	my $num1=$symbchck+$symbseed+$namechck;
                   12107: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12108: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12109: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12110: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12111: 	return "$num1,$num2";
1.155     albertel 12112:     }
1.366     albertel 12113: }
                   12114: 
1.443     albertel 12115: sub rndseed_64bit2 {
                   12116:     my ($symb,$courseid,$domain,$username)=@_;
                   12117:     {
                   12118: 	use integer;
                   12119: 	# strings need to be an even # of cahracters long, it it is odd the
                   12120:         # last characters gets thrown away
                   12121: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12122: 	my $symbseed=numval($symb) << 10;
                   12123: 	my $namechck=unpack("%32S*",$username.' ');
                   12124: 	
                   12125: 	my $nameseed=numval($username) << 21;
1.501     albertel 12126: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12127: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12128: 	
                   12129: 	my $num1=$symbchck+$symbseed+$namechck;
                   12130: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12131: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12132: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12133: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12134: 	return "$num1,$num2";
                   12135:     }
                   12136: }
                   12137: 
                   12138: sub rndseed_64bit3 {
                   12139:     my ($symb,$courseid,$domain,$username)=@_;
                   12140:     {
                   12141: 	use integer;
                   12142: 	# strings need to be an even # of cahracters long, it it is odd the
                   12143:         # last characters gets thrown away
                   12144: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12145: 	my $symbseed=numval2($symb) << 10;
                   12146: 	my $namechck=unpack("%32S*",$username.' ');
                   12147: 	
                   12148: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12149: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12150: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12151: 	
                   12152: 	my $num1=$symbchck+$symbseed+$namechck;
                   12153: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12154: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12155: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12156: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12157: 	
1.503     albertel 12158: 	return "$num1:$num2";
1.443     albertel 12159:     }
                   12160: }
                   12161: 
1.575     albertel 12162: sub rndseed_64bit4 {
                   12163:     my ($symb,$courseid,$domain,$username)=@_;
                   12164:     {
                   12165: 	use integer;
                   12166: 	# strings need to be an even # of cahracters long, it it is odd the
                   12167:         # last characters gets thrown away
                   12168: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12169: 	my $symbseed=numval3($symb) << 10;
                   12170: 	my $namechck=unpack("%32S*",$username.' ');
                   12171: 	
                   12172: 	my $nameseed=numval3($username) << 21;
                   12173: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12174: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12175: 	
                   12176: 	my $num1=$symbchck+$symbseed+$namechck;
                   12177: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12178: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12179: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12180: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12181: 	
1.575     albertel 12182: 	return "$num1:$num2";
                   12183:     }
                   12184: }
                   12185: 
1.675     albertel 12186: sub rndseed_64bit5 {
                   12187:     my ($symb,$courseid,$domain,$username)=@_;
                   12188:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12189:     return "$num1:$num2";
                   12190: }
                   12191: 
1.366     albertel 12192: sub rndseed_CODE_64bit {
                   12193:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12194:     {
1.366     albertel 12195: 	use integer;
1.443     albertel 12196: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12197: 	my $symbseed=numval2($symb);
1.491     albertel 12198: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12199: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12200: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12201: 	my $num1=$symbseed+$CODEchck;
                   12202: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12203: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12204: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12205: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12206: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12207: 	return "$num1:$num2";
1.366     albertel 12208:     }
                   12209: }
                   12210: 
1.575     albertel 12211: sub rndseed_CODE_64bit4 {
                   12212:     my ($symb,$courseid,$domain,$username)=@_;
                   12213:     {
                   12214: 	use integer;
                   12215: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12216: 	my $symbseed=numval3($symb);
                   12217: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12218: 	my $CODEseed=numval3(&getCODE());
                   12219: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12220: 	my $num1=$symbseed+$CODEchck;
                   12221: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12222: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12223: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12224: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12225: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12226: 	return "$num1:$num2";
                   12227:     }
                   12228: }
                   12229: 
1.675     albertel 12230: sub rndseed_CODE_64bit5 {
                   12231:     my ($symb,$courseid,$domain,$username)=@_;
                   12232:     my $code = &getCODE();
                   12233:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12234:     return "$num1:$num2";
                   12235: }
                   12236: 
1.366     albertel 12237: sub setup_random_from_rndseed {
                   12238:     my ($rndseed)=@_;
1.503     albertel 12239:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  12240:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12241:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12242:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12243:         } else {
                   12244:             &Math::Random::random_set_seed($num1,$num2);
                   12245:         }
1.366     albertel 12246:     } else {
                   12247: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12248:     }
1.36      albertel 12249: }
                   12250: 
1.474     albertel 12251: sub latest_receipt_algorithm_id {
1.835     albertel 12252:     return 'receipt3';
1.474     albertel 12253: }
                   12254: 
1.480     www      12255: sub recunique {
                   12256:     my $fucourseid=shift;
                   12257:     my $unique;
1.835     albertel 12258:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12259: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12260: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12261:     } else {
                   12262: 	$unique=$perlvar{'lonReceipt'};
                   12263:     }
                   12264:     return unpack("%32C*",$unique);
                   12265: }
                   12266: 
                   12267: sub recprefix {
                   12268:     my $fucourseid=shift;
                   12269:     my $prefix;
1.835     albertel 12270:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12271: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12272: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12273:     } else {
                   12274: 	$prefix=$perlvar{'lonHostID'};
                   12275:     }
                   12276:     return unpack("%32C*",$prefix);
                   12277: }
                   12278: 
1.76      www      12279: sub ireceipt {
1.474     albertel 12280:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12281: 
                   12282:     my $return =&recprefix($fucourseid).'-';
                   12283: 
                   12284:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12285: 	$env{'request.state'} eq 'construct') {
                   12286: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12287: 	return $return;
                   12288:     }
                   12289: 
1.76      www      12290:     my $cuname=unpack("%32C*",$funame);
                   12291:     my $cudom=unpack("%32C*",$fudom);
                   12292:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12293:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12294:     my $cunique=&recunique($fucourseid);
1.474     albertel 12295:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12296:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12297: 
1.790     albertel 12298: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12299: 			       
                   12300: 	$return.= ($cunique%$cuname+
                   12301: 		   $cunique%$cudom+
                   12302: 		   $cusymb%$cuname+
                   12303: 		   $cusymb%$cudom+
                   12304: 		   $cucourseid%$cuname+
                   12305: 		   $cucourseid%$cudom+
                   12306: 		   $cpart%$cuname+
                   12307: 		   $cpart%$cudom);
                   12308:     } else {
                   12309: 	$return.= ($cunique%$cuname+
                   12310: 		   $cunique%$cudom+
                   12311: 		   $cusymb%$cuname+
                   12312: 		   $cusymb%$cudom+
                   12313: 		   $cucourseid%$cuname+
                   12314: 		   $cucourseid%$cudom);
                   12315:     }
                   12316:     return $return;
1.76      www      12317: }
                   12318: 
                   12319: sub receipt {
1.474     albertel 12320:     my ($part)=@_;
1.790     albertel 12321:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12322:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12323: }
1.260     ng       12324: 
1.790     albertel 12325: sub whichuser {
                   12326:     my ($passedsymb)=@_;
                   12327:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12328:     if (defined($env{'form.grade_symb'})) {
                   12329: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12330: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12331: 	if (!$allowed &&
                   12332: 	    exists($env{'request.course.sec'}) &&
                   12333: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12334: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12335: 			      '/'.$env{'request.course.sec'});
                   12336: 	}
                   12337: 	if ($allowed) {
                   12338: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12339: 	    $courseid=$tmp_courseid;
                   12340: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12341: 	    ($name)=&get_env_multiple('form.grade_username');
                   12342: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12343: 	}
                   12344:     }
                   12345:     if (!$passedsymb) {
                   12346: 	$symb=&symbread();
                   12347:     } else {
                   12348: 	$symb=$passedsymb;
                   12349:     }
                   12350:     $courseid=$env{'request.course.id'};
                   12351:     $domain=$env{'user.domain'};
                   12352:     $name=$env{'user.name'};
                   12353:     if ($name eq 'public' && $domain eq 'public') {
                   12354: 	if (!defined($env{'form.username'})) {
                   12355: 	    $env{'form.username'}.=time.rand(10000000);
                   12356: 	}
                   12357: 	$name.=$env{'form.username'};
                   12358:     }
                   12359:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12360: 
                   12361: }
                   12362: 
1.36      albertel 12363: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12364: # returns either the contents of the file or 
                   12365: # -1 if the file doesn't exist
1.481     raeburn  12366: #
                   12367: # if the target is a file that was uploaded via DOCS, 
                   12368: # a check will be made to see if a current copy exists on the local server,
                   12369: # if it does this will be served, otherwise a copy will be retrieved from
                   12370: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12371: # the local server.   
1.472     albertel 12372: 
1.36      albertel 12373: sub getfile {
1.538     albertel 12374:     my ($file) = @_;
1.609     banghart 12375:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12376:     &repcopy($file);
                   12377:     return &readfile($file);
                   12378: }
                   12379: 
                   12380: sub repcopy_userfile {
                   12381:     my ($file)=@_;
1.1142    raeburn  12382:     my $londocroot = $perlvar{'lonDocRoot'};
                   12383:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12384:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12385:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12386: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12387:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12388:     if (-e "$file") {
1.828     www      12389: # we already have a local copy, check it out
1.538     albertel 12390: 	my @fileinfo = stat($file);
1.828     www      12391: 	my $rtncode;
                   12392: 	my $info;
1.538     albertel 12393: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12394: 	if ($lwpresp ne 'ok') {
1.828     www      12395: # there is no such file anymore, even though we had a local copy
1.482     albertel 12396: 	    if ($rtncode eq '404') {
1.538     albertel 12397: 		unlink($file);
1.482     albertel 12398: 	    }
                   12399: 	    return -1;
                   12400: 	}
                   12401: 	if ($info < $fileinfo[9]) {
1.828     www      12402: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12403: 	    return 'ok';
1.828     www      12404: 	} else {
                   12405: # the file is outdated, get rid of it
                   12406: 	    unlink($file);
1.482     albertel 12407: 	}
1.828     www      12408:     }
                   12409: # one way or the other, at this point, we don't have the file
                   12410: # construct the correct path for the file
                   12411:     my @parts = ($cdom,$cnum); 
                   12412:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12413: 	push @parts, split(/\//,$1);
                   12414:     }
                   12415:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   12416:     foreach my $part (@parts) {
                   12417: 	$path .= '/'.$part;
                   12418: 	if (!-e $path) {
                   12419: 	    mkdir($path,0770);
1.482     albertel 12420: 	}
                   12421:     }
1.828     www      12422: # now the path exists for sure
                   12423: # get a user agent
                   12424:     my $ua=new LWP::UserAgent;
                   12425:     my $transferfile=$file.'.in.transfer';
                   12426: # FIXME: this should flock
                   12427:     if (-e $transferfile) { return 'ok'; }
                   12428:     my $request;
                   12429:     $uri=~s/^\///;
1.980     raeburn  12430:     my $homeserver = &homeserver($cnum,$cdom);
                   12431:     my $protocol = $protocol{$homeserver};
                   12432:     $protocol = 'http' if ($protocol ne 'https');
                   12433:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      12434:     my $response=$ua->request($request,$transferfile);
                   12435: # did it work?
                   12436:     if ($response->is_error()) {
                   12437: 	unlink($transferfile);
                   12438: 	&logthis("Userfile repcopy failed for $uri");
                   12439: 	return -1;
                   12440:     }
                   12441: # worked, rename the transfer file
                   12442:     rename($transferfile,$file);
1.607     raeburn  12443:     return 'ok';
1.481     raeburn  12444: }
                   12445: 
1.517     albertel 12446: sub tokenwrapper {
                   12447:     my $uri=shift;
1.980     raeburn  12448:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 12449:     $uri=~s|^/||;
1.620     albertel 12450:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 12451:     my $token=$1;
1.552     albertel 12452:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   12453:     if ($udom && $uname && $file) {
                   12454: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  12455:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  12456:         my $homeserver = &homeserver($uname,$udom);
                   12457:         my $protocol = $protocol{$homeserver};
                   12458:         $protocol = 'http' if ($protocol ne 'https');
                   12459:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 12460:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   12461:                                '&tokenissued='.$perlvar{'lonHostID'};
                   12462:     } else {
                   12463:         return '/adm/notfound.html';
                   12464:     }
                   12465: }
                   12466: 
1.828     www      12467: # call with reqtype HEAD: get last modification time
                   12468: # call with reqtype GET: get the file contents
                   12469: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12470: #
1.481     raeburn  12471: sub getuploaded {
                   12472:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12473:     $uri=~s/^\///;
1.980     raeburn  12474:     my $homeserver = &homeserver($cnum,$cdom);
                   12475:     my $protocol = $protocol{$homeserver};
                   12476:     $protocol = 'http' if ($protocol ne 'https');
                   12477:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12478:     my $ua=new LWP::UserAgent;
                   12479:     my $request=new HTTP::Request($reqtype,$uri);
                   12480:     my $response=$ua->request($request);
                   12481:     $$rtncode = $response->code;
1.482     albertel 12482:     if (! $response->is_success()) {
                   12483: 	return 'failed';
                   12484:     }      
                   12485:     if ($reqtype eq 'HEAD') {
1.486     www      12486: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12487:     } elsif ($reqtype eq 'GET') {
                   12488: 	$$info = $response->content;
1.472     albertel 12489:     }
1.482     albertel 12490:     return 'ok';
1.36      albertel 12491: }
                   12492: 
1.481     raeburn  12493: sub readfile {
                   12494:     my $file = shift;
                   12495:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12496:     my $fh;
                   12497:     open($fh,"<$file");
                   12498:     my $a='';
1.800     albertel 12499:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12500:     return $a;
                   12501: }
                   12502: 
1.36      albertel 12503: sub filelocation {
1.590     banghart 12504:     my ($dir,$file) = @_;
                   12505:     my $location;
                   12506:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12507: 
                   12508:     if ($file =~ m-^/adm/-) {
                   12509: 	$file=~s-^/adm/wrapper/-/-;
                   12510: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12511:     }
1.882     albertel 12512: 
1.1139    www      12513:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12514:         $location = $file;
1.609     banghart 12515:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12516:         my ($udom,$uname,$filename)=
1.811     albertel 12517:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12518:         my $home=&homeserver($uname,$udom);
                   12519:         my $is_me=0;
                   12520:         my @ids=&current_machine_ids();
                   12521:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12522:         if ($is_me) {
1.1117    foxr     12523:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12524:         } else {
                   12525:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12526:   	      $udom.'/'.$uname.'/'.$filename;
                   12527:         }
1.882     albertel 12528:     } elsif ($file =~ m-^/adm/-) {
                   12529: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12530:     } else {
                   12531:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12532:         $file=~s:^/(res|priv)/:/:;
                   12533:         my $space=$1;
1.590     banghart 12534:         if ( !( $file =~ m:^/:) ) {
                   12535:             $location = $dir. '/'.$file;
                   12536:         } else {
1.1142    raeburn  12537:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12538:         }
1.59      albertel 12539:     }
1.590     banghart 12540:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12541:     while ($location=~m{/\.\./}) {
                   12542: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12543: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   12544: 	} else {
                   12545: 	    $location=~ s{/\.\./}{/}g;
                   12546: 	}
                   12547:     } #remove dir/..
1.590     banghart 12548:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   12549:     return $location;
1.46      www      12550: }
1.36      albertel 12551: 
1.46      www      12552: sub hreflocation {
                   12553:     my ($dir,$file)=@_;
1.980     raeburn  12554:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 12555: 	$file=filelocation($dir,$file);
1.700     albertel 12556:     } elsif ($file=~m-^/adm/-) {
                   12557: 	$file=~s-^/adm/wrapper/-/-;
                   12558: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 12559:     }
                   12560:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   12561: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   12562:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  12563: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   12564: 	        {/uploaded/$1/$2/}x;
1.46      www      12565:     }
1.913     albertel 12566:     if ($file=~ m{^/userfiles/}) {
                   12567: 	$file =~ s{^/userfiles/}{/uploaded/};
                   12568:     }
1.462     albertel 12569:     return $file;
1.465     albertel 12570: }
                   12571: 
1.1139    www      12572: 
                   12573: 
                   12574: 
                   12575: 
1.465     albertel 12576: sub current_machine_domains {
1.853     albertel 12577:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   12578: }
                   12579: 
                   12580: sub machine_domains {
                   12581:     my ($hostname) = @_;
1.465     albertel 12582:     my @domains;
1.838     albertel 12583:     my %hostname = &all_hostnames();
1.465     albertel 12584:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  12585: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 12586: 	if ($hostname eq $name) {
1.844     albertel 12587: 	    push(@domains,&host_domain($id));
1.465     albertel 12588: 	}
                   12589:     }
                   12590:     return @domains;
                   12591: }
                   12592: 
                   12593: sub current_machine_ids {
1.853     albertel 12594:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   12595: }
                   12596: 
                   12597: sub machine_ids {
                   12598:     my ($hostname) = @_;
                   12599:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 12600:     my @ids;
1.888     albertel 12601:     my %name_to_host = &all_names();
1.889     albertel 12602:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   12603: 	return @{ $name_to_host{$hostname} };
                   12604:     }
                   12605:     return;
1.31      www      12606: }
                   12607: 
1.824     raeburn  12608: sub additional_machine_domains {
                   12609:     my @domains;
                   12610:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   12611:     while( my $line = <$fh>) {
                   12612:         $line =~ s/\s//g;
                   12613:         push(@domains,$line);
                   12614:     }
                   12615:     return @domains;
                   12616: }
                   12617: 
                   12618: sub default_login_domain {
                   12619:     my $domain = $perlvar{'lonDefDomain'};
                   12620:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   12621:     foreach my $posdom (&current_machine_domains(),
                   12622:                         &additional_machine_domains()) {
                   12623:         if (lc($posdom) eq lc($testdomain)) {
                   12624:             $domain=$posdom;
                   12625:             last;
                   12626:         }
                   12627:     }
                   12628:     return $domain;
                   12629: }
                   12630: 
1.31      www      12631: # ------------------------------------------------------------- Declutters URLs
                   12632: 
                   12633: sub declutter {
                   12634:     my $thisfn=shift;
1.569     albertel 12635:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  12636:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   12637:         $thisfn=~s{^/home/httpd/html}{};
                   12638:     }
1.31      www      12639:     $thisfn=~s/^\///;
1.697     albertel 12640:     $thisfn=~s|^adm/wrapper/||;
                   12641:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12642:     $thisfn=~s/^res\///;
1.1172    bisitz   12643:     $thisfn=~s/^priv\///;
1.1032    raeburn  12644:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12645:         $thisfn=~s/\?.+$//;
                   12646:     }
1.268     www      12647:     return $thisfn;
                   12648: }
                   12649: 
                   12650: # ------------------------------------------------------------- Clutter up URLs
                   12651: 
                   12652: sub clutter {
                   12653:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12654:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 12655: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      12656:        $thisfn='/res'.$thisfn; 
                   12657:     }
1.1031    raeburn  12658:     if ($thisfn !~m|^/adm|) {
                   12659: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 12660: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 12661: 	} else {
                   12662: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   12663: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 12664: 	    if ($embstyle eq 'ssi'
                   12665: 		|| ($embstyle eq 'hdn')
                   12666: 		|| ($embstyle eq 'rat')
                   12667: 		|| ($embstyle eq 'prv')
                   12668: 		|| ($embstyle eq 'ign')) {
                   12669: 		#do nothing with these
                   12670: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 12671: 		|| ($embstyle eq 'emb')
                   12672: 		|| ($embstyle eq 'wrp')) {
                   12673: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 12674: 	    } elsif ($embstyle eq 'unk'
                   12675: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 12676: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 12677: 	    } else {
1.718     www      12678: #		&logthis("Got a blank emb style");
1.695     albertel 12679: 	    }
1.694     albertel 12680: 	}
1.1298    raeburn  12681:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/exttools?$}) {
                   12682:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 12683:     }
1.31      www      12684:     return $thisfn;
1.12      www      12685: }
                   12686: 
1.787     albertel 12687: sub clutter_with_no_wrapper {
                   12688:     my $uri = &clutter(shift);
                   12689:     if ($uri =~ m-^/adm/-) {
                   12690: 	$uri =~ s-^/adm/wrapper/-/-;
                   12691: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   12692:     }
                   12693:     return $uri;
                   12694: }
                   12695: 
1.557     albertel 12696: sub freeze_escape {
                   12697:     my ($value)=@_;
                   12698:     if (ref($value)) {
                   12699: 	$value=&nfreeze($value);
                   12700: 	return '__FROZEN__'.&escape($value);
                   12701:     }
                   12702:     return &escape($value);
                   12703: }
                   12704: 
1.11      www      12705: 
1.557     albertel 12706: sub thaw_unescape {
                   12707:     my ($value)=@_;
                   12708:     if ($value =~ /^__FROZEN__/) {
                   12709: 	substr($value,0,10,undef);
                   12710: 	$value=&unescape($value);
                   12711: 	return &thaw($value);
                   12712:     }
                   12713:     return &unescape($value);
                   12714: }
                   12715: 
1.436     albertel 12716: sub correct_line_ends {
                   12717:     my ($result)=@_;
                   12718:     $$result =~s/\r\n/\n/mg;
                   12719:     $$result =~s/\r/\n/mg;
1.415     albertel 12720: }
1.1       albertel 12721: # ================================================================ Main Program
                   12722: 
1.184     www      12723: sub goodbye {
1.204     albertel 12724:    &logthis("Starting Shut down");
1.443     albertel 12725: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 12726:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 12727: #converted
1.599     albertel 12728: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 12729:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   12730: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   12731: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 12732: #1.1 only
1.870     albertel 12733: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   12734: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   12735: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   12736: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   12737:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 12738:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   12739:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      12740:    &flushcourselogs();
                   12741:    &logthis("Shutting down");
                   12742: }
                   12743: 
1.852     albertel 12744: sub get_dns {
1.1210    raeburn  12745:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 12746:     if (!$ignore_cache) {
                   12747: 	my ($content,$cached)=
                   12748: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   12749: 	if ($cached) {
1.1210    raeburn  12750: 	    &$func($content,$hashref);
1.869     albertel 12751: 	    return;
                   12752: 	}
                   12753:     }
                   12754: 
                   12755:     my %alldns;
1.852     albertel 12756:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12757:     foreach my $dns (<$config>) {
                   12758: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  12759:         my $line = $1;
                   12760:         my ($host,$protocol) = split(/:/,$line);
                   12761:         if ($protocol ne 'https') {
                   12762:             $protocol = 'http';
                   12763:         }
                   12764: 	$alldns{$host} = $protocol;
1.869     albertel 12765:     }
                   12766:     while (%alldns) {
1.1263    raeburn  12767: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 12768: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  12769:         $ua->timeout(30);
1.979     raeburn  12770: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 12771: 	my $response=$ua->request($request);
1.979     raeburn  12772:         delete($alldns{$dns});
1.852     albertel 12773: 	next if ($response->is_error());
                   12774: 	my @content = split("\n",$response->content);
1.1210    raeburn  12775: 	unless ($nocache) {
1.1219    raeburn  12776: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210    raeburn  12777: 	}
                   12778: 	&$func(\@content,$hashref);
1.869     albertel 12779: 	return;
1.852     albertel 12780:     }
                   12781:     close($config);
1.871     albertel 12782:     my $which = (split('/',$url))[3];
                   12783:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   12784:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 12785:     my @content = <$config>;
1.1210    raeburn  12786:     &$func(\@content,$hashref);
                   12787:     return;
                   12788: }
                   12789: 
                   12790: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  12791: sub parse_dns_checksums_tab {
1.1210    raeburn  12792:     my ($lines,$hashref) = @_;
1.1264    raeburn  12793:     my $lonhost = $perlvar{'lonHostID'};
                   12794:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  12795:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  12796:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   12797:     my $webconfdir = '/etc/httpd/conf';
                   12798:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   12799:         $webconfdir = '/etc/apache2';
                   12800:     } elsif ($distro =~ /^sles(\d+)$/) {
                   12801:         if ($1 >= 10) {
                   12802:             $webconfdir = '/etc/apache2';
                   12803:         }
                   12804:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   12805:         if ($1 >= 10.0) {
                   12806:             $webconfdir = '/etc/apache2';
                   12807:         }
                   12808:     }
1.1210    raeburn  12809:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12810:     my (%chksum,%revnum);
                   12811:     if (ref($lines) eq 'ARRAY') {
                   12812:         chomp(@{$lines});
1.1238    raeburn  12813:         my $version = shift(@{$lines});
                   12814:         if ($version eq $release) {  
1.1210    raeburn  12815:             foreach my $line (@{$lines}) {
1.1238    raeburn  12816:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  12817:                 if ($file =~ m{^/etc/httpd/conf}) {
                   12818:                     if ($webconfdir eq '/etc/apache2') {
                   12819:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   12820:                     }
                   12821:                 }
1.1238    raeburn  12822:                 $chksum{$file} = $shasum;
                   12823:                 $revnum{$file} = $version;
1.1210    raeburn  12824:             }
                   12825:             if (ref($hashref) eq 'HASH') {
                   12826:                 %{$hashref} = (
                   12827:                                 sums     => \%chksum,
                   12828:                                 versions => \%revnum,
                   12829:                               );
                   12830:             }
                   12831:         }
                   12832:     }
1.869     albertel 12833:     return;
1.852     albertel 12834: }
1.1210    raeburn  12835: 
                   12836: sub fetch_dns_checksums {
1.1238    raeburn  12837:     my %checksums;
                   12838:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  12839:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  12840:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12841:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  12842:              \%checksums);
1.1210    raeburn  12843:     return \%checksums;
                   12844: }
                   12845: 
1.327     albertel 12846: # ------------------------------------------------------------ Read domain file
                   12847: {
1.852     albertel 12848:     my $loaded;
1.846     albertel 12849:     my %domain;
                   12850: 
1.852     albertel 12851:     sub parse_domain_tab {
                   12852: 	my ($lines) = @_;
                   12853: 	foreach my $line (@$lines) {
                   12854: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      12855: 
1.846     albertel 12856: 	    chomp($line);
1.852     albertel 12857: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 12858: 	    my %this_domain;
                   12859: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   12860: 			       'lang_def', 'city', 'longi', 'lati',
                   12861: 			       'primary') {
                   12862: 		$this_domain{$field} = shift(@elements);
                   12863: 	    }
                   12864: 	    $domain{$name} = \%this_domain;
1.852     albertel 12865: 	}
                   12866:     }
1.864     albertel 12867: 
                   12868:     sub reset_domain_info {
                   12869: 	undef($loaded);
                   12870: 	undef(%domain);
                   12871:     }
                   12872: 
1.852     albertel 12873:     sub load_domain_tab {
1.1293    raeburn  12874: 	my ($ignore_cache,$nocache) = @_;
                   12875: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 12876: 	my $fh;
                   12877: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   12878: 	    my @lines = <$fh>;
                   12879: 	    &parse_domain_tab(\@lines);
1.448     albertel 12880: 	}
1.852     albertel 12881: 	close($fh);
                   12882: 	$loaded = 1;
1.327     albertel 12883:     }
1.846     albertel 12884: 
                   12885:     sub domain {
1.852     albertel 12886: 	&load_domain_tab() if (!$loaded);
                   12887: 
1.846     albertel 12888: 	my ($name,$what) = @_;
                   12889: 	return if ( !exists($domain{$name}) );
                   12890: 
                   12891: 	if (!$what) {
                   12892: 	    return $domain{$name}{'description'};
                   12893: 	}
                   12894: 	return $domain{$name}{$what};
                   12895:     }
1.974     raeburn  12896: 
                   12897:     sub domain_info {
                   12898:         &load_domain_tab() if (!$loaded);
                   12899:         return %domain;
                   12900:     }
                   12901: 
1.327     albertel 12902: }
                   12903: 
                   12904: 
1.1       albertel 12905: # ------------------------------------------------------------- Read hosts file
                   12906: {
1.838     albertel 12907:     my %hostname;
1.844     albertel 12908:     my %hostdom;
1.845     albertel 12909:     my %libserv;
1.852     albertel 12910:     my $loaded;
1.888     albertel 12911:     my %name_to_host;
1.1074    raeburn  12912:     my %internetdom;
1.1107    raeburn  12913:     my %LC_dns_serv;
1.852     albertel 12914: 
                   12915:     sub parse_hosts_tab {
                   12916: 	my ($file) = @_;
                   12917: 	foreach my $configline (@$file) {
                   12918: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  12919:             chomp($configline);
                   12920: 	    if ($configline =~ /^\^/) {
                   12921:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   12922:                     $LC_dns_serv{$1} = 1;
                   12923:                 }
                   12924:                 next;
                   12925:             }
1.1074    raeburn  12926: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 12927: 	    $name=~s/\s//g;
                   12928: 	    if ($id && $domain && $role && $name) {
                   12929: 		$hostname{$id}=$name;
1.888     albertel 12930: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 12931: 		$hostdom{$id}=$domain;
                   12932: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  12933:                 if (defined($protocol)) {
                   12934:                     if ($protocol eq 'https') {
                   12935:                         $protocol{$id} = $protocol;
                   12936:                     } else {
                   12937:                         $protocol{$id} = 'http'; 
                   12938:                     }
1.968     raeburn  12939:                 } else {
1.969     raeburn  12940:                     $protocol{$id} = 'http';
1.968     raeburn  12941:                 }
1.1074    raeburn  12942:                 if (defined($intdom)) {
                   12943:                     $internetdom{$id} = $intdom;
                   12944:                 }
1.852     albertel 12945: 	    }
                   12946: 	}
                   12947:     }
1.864     albertel 12948:     
                   12949:     sub reset_hosts_info {
1.897     albertel 12950: 	&purge_remembered();
1.864     albertel 12951: 	&reset_domain_info();
                   12952: 	&reset_hosts_ip_info();
1.892     albertel 12953: 	undef(%name_to_host);
1.864     albertel 12954: 	undef(%hostname);
                   12955: 	undef(%hostdom);
                   12956: 	undef(%libserv);
                   12957: 	undef($loaded);
                   12958:     }
1.1       albertel 12959: 
1.852     albertel 12960:     sub load_hosts_tab {
1.1293    raeburn  12961: 	my ($ignore_cache,$nocache) = @_;
                   12962: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852     albertel 12963: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12964: 	my @config = <$config>;
                   12965: 	&parse_hosts_tab(\@config);
                   12966: 	close($config);
                   12967: 	$loaded=1;
1.1       albertel 12968:     }
1.852     albertel 12969: 
1.838     albertel 12970:     sub hostname {
1.852     albertel 12971: 	&load_hosts_tab() if (!$loaded);
                   12972: 
1.838     albertel 12973: 	my ($lonid) = @_;
                   12974: 	return $hostname{$lonid};
                   12975:     }
1.845     albertel 12976: 
1.838     albertel 12977:     sub all_hostnames {
1.852     albertel 12978: 	&load_hosts_tab() if (!$loaded);
                   12979: 
1.838     albertel 12980: 	return %hostname;
                   12981:     }
1.845     albertel 12982: 
1.888     albertel 12983:     sub all_names {
1.1293    raeburn  12984:         my ($ignore_cache,$nocache) = @_;
                   12985: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 12986: 
                   12987: 	return %name_to_host;
                   12988:     }
                   12989: 
1.974     raeburn  12990:     sub all_host_domain {
                   12991:         &load_hosts_tab() if (!$loaded);
                   12992:         return %hostdom;
                   12993:     }
                   12994: 
1.845     albertel 12995:     sub is_library {
1.852     albertel 12996: 	&load_hosts_tab() if (!$loaded);
                   12997: 
1.845     albertel 12998: 	return exists($libserv{$_[0]});
                   12999:     }
                   13000: 
                   13001:     sub all_library {
1.852     albertel 13002: 	&load_hosts_tab() if (!$loaded);
                   13003: 
1.845     albertel 13004: 	return %libserv;
                   13005:     }
                   13006: 
1.1062    droeschl 13007:     sub unique_library {
                   13008: 	#2x reverse removes all hostnames that appear more than once
                   13009:         my %unique = reverse &all_library();
                   13010:         return reverse %unique;
                   13011:     }
                   13012: 
1.841     albertel 13013:     sub get_servers {
1.852     albertel 13014: 	&load_hosts_tab() if (!$loaded);
                   13015: 
1.841     albertel 13016: 	my ($domain,$type) = @_;
                   13017: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13018: 	                                          : %hostname;
                   13019: 	my %result;
1.842     albertel 13020: 	if (ref($domain) eq 'ARRAY') {
                   13021: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13022: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13023: 		    $result{$host} = $hostname;
                   13024: 		}
                   13025: 	    }
                   13026: 	} else {
                   13027: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13028: 		if ($hostdom{$host} eq $domain) {
                   13029: 		    $result{$host} = $hostname;
                   13030: 		}
1.841     albertel 13031: 	    }
                   13032: 	}
                   13033: 	return %result;
                   13034:     }
1.845     albertel 13035: 
1.1062    droeschl 13036:     sub get_unique_servers {
                   13037:         my %unique = reverse &get_servers(@_);
                   13038: 	return reverse %unique;
                   13039:     }
                   13040: 
1.844     albertel 13041:     sub host_domain {
1.852     albertel 13042: 	&load_hosts_tab() if (!$loaded);
                   13043: 
1.844     albertel 13044: 	my ($lonid) = @_;
                   13045: 	return $hostdom{$lonid};
                   13046:     }
                   13047: 
1.841     albertel 13048:     sub all_domains {
1.852     albertel 13049: 	&load_hosts_tab() if (!$loaded);
                   13050: 
1.841     albertel 13051: 	my %seen;
                   13052: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13053: 	return @uniq;
                   13054:     }
1.1074    raeburn  13055: 
                   13056:     sub internet_dom {
                   13057:         &load_hosts_tab() if (!$loaded);
                   13058: 
                   13059:         my ($lonid) = @_;
                   13060:         return $internetdom{$lonid};
                   13061:     }
1.1107    raeburn  13062: 
                   13063:     sub is_LC_dns {
                   13064:         &load_hosts_tab() if (!$loaded);
                   13065: 
                   13066:         my ($hostname) = @_;
                   13067:         return exists($LC_dns_serv{$hostname});
                   13068:     }
                   13069: 
1.1       albertel 13070: }
                   13071: 
1.847     albertel 13072: { 
                   13073:     my %iphost;
1.856     albertel 13074:     my %name_to_ip;
                   13075:     my %lonid_to_ip;
1.869     albertel 13076: 
1.847     albertel 13077:     sub get_hosts_from_ip {
                   13078: 	my ($ip) = @_;
                   13079: 	my %iphosts = &get_iphost();
                   13080: 	if (ref($iphosts{$ip})) {
                   13081: 	    return @{$iphosts{$ip}};
                   13082: 	}
                   13083: 	return;
1.839     albertel 13084:     }
1.864     albertel 13085:     
                   13086:     sub reset_hosts_ip_info {
                   13087: 	undef(%iphost);
                   13088: 	undef(%name_to_ip);
                   13089: 	undef(%lonid_to_ip);
                   13090:     }
1.856     albertel 13091: 
                   13092:     sub get_host_ip {
                   13093: 	my ($lonid) = @_;
                   13094: 	if (exists($lonid_to_ip{$lonid})) {
                   13095: 	    return $lonid_to_ip{$lonid};
                   13096: 	}
                   13097: 	my $name=&hostname($lonid);
                   13098:    	my $ip = gethostbyname($name);
                   13099: 	return if (!$ip || length($ip) ne 4);
                   13100: 	$ip=inet_ntoa($ip);
                   13101: 	$name_to_ip{$name}   = $ip;
                   13102: 	$lonid_to_ip{$lonid} = $ip;
                   13103: 	return $ip;
                   13104:     }
1.847     albertel 13105:     
                   13106:     sub get_iphost {
1.1293    raeburn  13107: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13108: 
1.869     albertel 13109: 	if (!$ignore_cache) {
                   13110: 	    if (%iphost) {
                   13111: 		return %iphost;
                   13112: 	    }
                   13113: 	    my ($ip_info,$cached)=
                   13114: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13115: 	    if ($cached) {
                   13116: 		%iphost      = %{$ip_info->[0]};
                   13117: 		%name_to_ip  = %{$ip_info->[1]};
                   13118: 		%lonid_to_ip = %{$ip_info->[2]};
                   13119: 		return %iphost;
                   13120: 	    }
                   13121: 	}
1.894     albertel 13122: 
                   13123: 	# get yesterday's info for fallback
                   13124: 	my %old_name_to_ip;
                   13125: 	my ($ip_info,$cached)=
                   13126: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13127: 	if ($cached) {
                   13128: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13129: 	}
                   13130: 
1.1293    raeburn  13131: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13132: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13133: 	    my $ip;
                   13134: 	    if (!exists($name_to_ip{$name})) {
                   13135: 		$ip = gethostbyname($name);
                   13136: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13137: 		    if (defined($old_name_to_ip{$name})) {
                   13138: 			$ip = $old_name_to_ip{$name};
                   13139: 			&logthis("Can't find $name defaulting to old $ip");
                   13140: 		    } else {
                   13141: 			&logthis("Name $name no IP found");
                   13142: 			next;
                   13143: 		    }
                   13144: 		} else {
                   13145: 		    $ip=inet_ntoa($ip);
1.847     albertel 13146: 		}
                   13147: 		$name_to_ip{$name} = $ip;
                   13148: 	    } else {
                   13149: 		$ip = $name_to_ip{$name};
1.653     albertel 13150: 	    }
1.888     albertel 13151: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13152: 		$lonid_to_ip{$id} = $ip;
                   13153: 	    }
                   13154: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13155: 	}
1.1293    raeburn  13156:         unless ($nocache) {
                   13157: 	    &do_cache_new('iphost','iphost',
                   13158: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13159: 		          48*60*60);
                   13160:         }
1.869     albertel 13161: 
1.847     albertel 13162: 	return %iphost;
1.598     albertel 13163:     }
                   13164: 
1.992     raeburn  13165:     #
                   13166:     #  Given a DNS returns the loncapa host name for that DNS 
                   13167:     # 
                   13168:     sub host_from_dns {
                   13169:         my ($dns) = @_;
                   13170:         my @hosts;
                   13171:         my $ip;
                   13172: 
1.993     raeburn  13173:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13174:             $ip = $name_to_ip{$dns};
                   13175:         }
                   13176:         if (!$ip) {
                   13177:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13178:             if (length($ip) == 4) { 
                   13179: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13180:             }
                   13181:         }
                   13182:         if ($ip) {
                   13183: 	    @hosts = get_hosts_from_ip($ip);
                   13184: 	    return $hosts[0];
                   13185:         }
                   13186:         return undef;
1.986     foxr     13187:     }
1.992     raeburn  13188: 
1.1074    raeburn  13189:     sub get_internet_names {
                   13190:         my ($lonid) = @_;
                   13191:         return if ($lonid eq '');
                   13192:         my ($idnref,$cached)=
                   13193:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13194:         if ($cached) {
                   13195:             return $idnref;
                   13196:         }
                   13197:         my $ip = &get_host_ip($lonid);
                   13198:         my @hosts = &get_hosts_from_ip($ip);
                   13199:         my %iphost = &get_iphost();
                   13200:         my (@idns,%seen);
                   13201:         foreach my $id (@hosts) {
                   13202:             my $dom = &host_domain($id);
                   13203:             my $prim_id = &domain($dom,'primary');
                   13204:             my $prim_ip = &get_host_ip($prim_id);
                   13205:             next if ($seen{$prim_ip});
                   13206:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13207:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13208:                     my $intdom = &internet_dom($id);
                   13209:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13210:                         push(@idns,$intdom);
                   13211:                     }
                   13212:                 }
                   13213:             }
                   13214:             $seen{$prim_ip} = 1;
                   13215:         }
1.1219    raeburn  13216:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13217:     }
                   13218: 
1.986     foxr     13219: }
                   13220: 
1.1079    raeburn  13221: sub all_loncaparevs {
1.1249    raeburn  13222:     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  13223: }
                   13224: 
1.1227    raeburn  13225: # ---------------------------------------------------------- Read loncaparev table
                   13226: {
                   13227:     sub load_loncaparevs { 
                   13228:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   13229:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   13230:                 while (my $configline=<$config>) {
                   13231:                     chomp($configline);
                   13232:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13233:                     $loncaparevs{$hostid}=$loncaparev;
                   13234:                 }
                   13235:                 close($config);
                   13236:             }
                   13237:         }
                   13238:     }
                   13239: }
                   13240: 
                   13241: # ---------------------------------------------------------- Read serverhostID table
                   13242: {
                   13243:     sub load_serverhomeIDs {
                   13244:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   13245:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   13246:                 while (my $configline=<$config>) {
                   13247:                     chomp($configline);
                   13248:                     my ($name,$id)=split(/:/,$configline);
                   13249:                     $serverhomeIDs{$name}=$id;
                   13250:                 }
                   13251:                 close($config);
                   13252:             }
                   13253:         }
                   13254:     }
                   13255: }
                   13256: 
                   13257: 
1.862     albertel 13258: BEGIN {
                   13259: 
                   13260: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13261:     unless ($readit) {
                   13262: {
                   13263:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13264:     %perlvar = (%perlvar,%{$configvars});
                   13265: }
                   13266: 
                   13267: 
1.1       albertel 13268: # ------------------------------------------------------ Read spare server file
                   13269: {
1.448     albertel 13270:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13271: 
                   13272:     while (my $configline=<$config>) {
                   13273:        chomp($configline);
1.284     matthew  13274:        if ($configline) {
1.784     albertel 13275: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13276: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13277: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13278:        }
                   13279:     }
1.448     albertel 13280:     close($config);
1.1       albertel 13281: }
1.11      www      13282: # ------------------------------------------------------------ Read permissions
                   13283: {
1.448     albertel 13284:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13285: 
                   13286:     while (my $configline=<$config>) {
1.448     albertel 13287: 	chomp($configline);
                   13288: 	if ($configline) {
                   13289: 	    my ($role,$perm)=split(/ /,$configline);
                   13290: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13291: 	}
1.11      www      13292:     }
1.448     albertel 13293:     close($config);
1.11      www      13294: }
                   13295: 
                   13296: # -------------------------------------------- Read plain texts for permissions
                   13297: {
1.448     albertel 13298:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13299: 
                   13300:     while (my $configline=<$config>) {
1.448     albertel 13301: 	chomp($configline);
                   13302: 	if ($configline) {
1.742     raeburn  13303: 	    my ($short,@plain)=split(/:/,$configline);
                   13304:             %{$prp{$short}} = ();
                   13305: 	    if (@plain > 0) {
                   13306:                 $prp{$short}{'std'} = $plain[0];
                   13307:                 for (my $i=1; $i<@plain; $i++) {
                   13308:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13309:                 }
                   13310:             }
1.448     albertel 13311: 	}
1.135     www      13312:     }
1.448     albertel 13313:     close($config);
1.135     www      13314: }
                   13315: 
                   13316: # ---------------------------------------------------------- Read package table
                   13317: {
1.448     albertel 13318:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13319: 
                   13320:     while (my $configline=<$config>) {
1.483     albertel 13321: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13322: 	chomp($configline);
                   13323: 	my ($short,$plain)=split(/:/,$configline);
                   13324: 	my ($pack,$name)=split(/\&/,$short);
                   13325: 	if ($plain ne '') {
                   13326: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13327: 	    $packagetab{$short}=$plain; 
                   13328: 	}
1.11      www      13329:     }
1.448     albertel 13330:     close($config);
1.329     matthew  13331: }
                   13332: 
1.1073    raeburn  13333: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  13334: 
                   13335: &load_loncaparevs();
1.1073    raeburn  13336: 
1.1074    raeburn  13337: # ---------------------------------------------------------- Read serverhostID table
                   13338: 
1.1227    raeburn  13339: &load_serverhomeIDs();
                   13340: 
                   13341: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13342: {
                   13343:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13344:     if (-e $file) {
                   13345:         my $parser = HTML::LCParser->new($file);
                   13346:         while (my $token = $parser->get_token()) {
                   13347:             if ($token->[0] eq 'S') {
                   13348:                 my $item = $token->[1];
                   13349:                 my $name = $token->[2]{'name'};
                   13350:                 my $value = $token->[2]{'value'};
1.1285    raeburn  13351:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  13352:                 my $namematch = $token->[2]{'namematch'};
                   13353:                 if ($item eq 'parameter') {
                   13354:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   13355:                         my $release = $parser->get_text();
                   13356:                         $release =~ s/(^\s*|\s*$ )//gx;
                   13357:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   13358:                     }
                   13359:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  13360:                     my $release = $parser->get_text();
                   13361:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  13362:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  13363:                 }
                   13364:             }
                   13365:         }
                   13366:     }
1.1073    raeburn  13367: }
                   13368: 
1.1138    raeburn  13369: # ---------------------------------------------------------- Read managers table
                   13370: {
                   13371:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   13372:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   13373:             while (my $configline=<$config>) {
                   13374:                 chomp($configline);
                   13375:                 next if ($configline =~ /^\#/);
                   13376:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13377:                     $managerstab{$configline} = 1;
                   13378:                 }
                   13379:             }
                   13380:             close($config);
                   13381:         }
                   13382:     }
                   13383: }
                   13384: 
1.329     matthew  13385: # ------------- set up temporary directory
                   13386: {
1.1117    foxr     13387:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  13388: 
1.11      www      13389: }
                   13390: 
1.794     albertel 13391: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   13392: 				'compress_threshold'=> 20_000,
                   13393:  			        });
1.185     www      13394: 
1.281     www      13395: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      13396: $dumpcount=0;
1.958     www      13397: $locknum=0;
1.22      www      13398: 
1.163     harris41 13399: &logtouch();
1.672     albertel 13400: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      13401: $readit=1;
1.564     albertel 13402:     {
                   13403: 	use integer;
                   13404: 	my $test=(2**32)+1;
1.568     albertel 13405: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 13406: 	&logthis(" Detected 64bit platform ($_64bit)");
                   13407:     }
1.195     www      13408: }
1.1       albertel 13409: }
1.179     www      13410: 
1.1       albertel 13411: 1;
1.191     harris41 13412: __END__
                   13413: 
1.243     albertel 13414: =pod
                   13415: 
1.191     harris41 13416: =head1 NAME
                   13417: 
1.243     albertel 13418: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 13419: 
                   13420: =head1 SYNOPSIS
                   13421: 
1.243     albertel 13422: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 13423: 
                   13424:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   13425: 
1.243     albertel 13426: Common parameters:
                   13427: 
                   13428: =over 4
                   13429: 
                   13430: =item *
                   13431: 
                   13432: $uname : an internal username (if $cname expecting a course Id specifically)
                   13433: 
                   13434: =item *
                   13435: 
                   13436: $udom : a domain (if $cdom expecting a course's domain specifically)
                   13437: 
                   13438: =item *
                   13439: 
                   13440: $symb : a resource instance identifier
                   13441: 
                   13442: =item *
                   13443: 
                   13444: $namespace : the name of a .db file that contains the data needed or
                   13445: being set.
                   13446: 
                   13447: =back
                   13448: 
1.394     bowersj2 13449: =head1 OVERVIEW
1.191     harris41 13450: 
1.394     bowersj2 13451: lonnet provides subroutines which interact with the
                   13452: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   13453: about classes, users, and resources.
1.243     albertel 13454: 
                   13455: For many of these objects you can also use this to store data about
                   13456: them or modify them in various ways.
1.191     harris41 13457: 
1.394     bowersj2 13458: =head2 Symbs
1.191     harris41 13459: 
1.394     bowersj2 13460: To identify a specific instance of a resource, LON-CAPA uses symbols
                   13461: or "symbs"X<symb>. These identifiers are built from the URL of the
                   13462: map, the resource number of the resource in the map, and the URL of
                   13463: the resource itself. The latter is somewhat redundant, but might help
                   13464: if maps change.
                   13465: 
                   13466: An example is
                   13467: 
                   13468:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   13469: 
                   13470: The respective map entry is
                   13471: 
                   13472:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   13473:   title="Problem 2">
                   13474:  </resource>
                   13475: 
                   13476: Symbs are used by the random number generator, as well as to store and
                   13477: restore data specific to a certain instance of for example a problem.
                   13478: 
                   13479: =head2 Storing And Retrieving Data
                   13480: 
                   13481: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   13482: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   13483: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   13484: is is the non-critical message twin of cstore. These functions are for
                   13485: handlers to store a perl hash to a user's permanent data space in an
                   13486: easy manner, and to retrieve it again on another call. It is expected
                   13487: that a handler would use this once at the beginning to retrieve data,
                   13488: and then again once at the end to send only the new data back.
                   13489: 
                   13490: The data is stored in the user's data directory on the user's
                   13491: homeserver under the ID of the course.
                   13492: 
                   13493: The hash that is returned by restore will have all of the previous
                   13494: value for all of the elements of the hash.
                   13495: 
                   13496: Example:
                   13497: 
                   13498:  #creating a hash
                   13499:  my %hash;
                   13500:  $hash{'foo'}='bar';
                   13501: 
                   13502:  #storing it
                   13503:  &Apache::lonnet::cstore(\%hash);
                   13504: 
                   13505:  #changing a value
                   13506:  $hash{'foo'}='notbar';
                   13507: 
                   13508:  #adding a new value
                   13509:  $hash{'bar'}='foo';
                   13510:  &Apache::lonnet::cstore(\%hash);
                   13511: 
                   13512:  #retrieving the hash
                   13513:  my %history=&Apache::lonnet::restore();
                   13514: 
                   13515:  #print the hash
                   13516:  foreach my $key (sort(keys(%history))) {
                   13517:    print("\%history{$key} = $history{$key}");
                   13518:  }
                   13519: 
                   13520: Will print out:
1.191     harris41 13521: 
1.394     bowersj2 13522:  %history{1:foo} = bar
                   13523:  %history{1:keys} = foo:timestamp
                   13524:  %history{1:timestamp} = 990455579
                   13525:  %history{2:bar} = foo
                   13526:  %history{2:foo} = notbar
                   13527:  %history{2:keys} = foo:bar:timestamp
                   13528:  %history{2:timestamp} = 990455580
                   13529:  %history{bar} = foo
                   13530:  %history{foo} = notbar
                   13531:  %history{timestamp} = 990455580
                   13532:  %history{version} = 2
                   13533: 
                   13534: Note that the special hash entries C<keys>, C<version> and
                   13535: C<timestamp> were added to the hash. C<version> will be equal to the
                   13536: total number of versions of the data that have been stored. The
                   13537: C<timestamp> attribute will be the UNIX time the hash was
                   13538: stored. C<keys> is available in every historical section to list which
                   13539: keys were added or changed at a specific historical revision of a
                   13540: hash.
                   13541: 
                   13542: B<Warning>: do not store the hash that restore returns directly. This
                   13543: will cause a mess since it will restore the historical keys as if the
                   13544: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 13545: 
1.394     bowersj2 13546: Calling convention:
1.191     harris41 13547: 
1.1225    raeburn  13548:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  13549:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 13550: 
1.394     bowersj2 13551: For more detailed information, see lonnet specific documentation.
1.191     harris41 13552: 
1.394     bowersj2 13553: =head1 RETURN MESSAGES
1.191     harris41 13554: 
1.394     bowersj2 13555: =over 4
1.191     harris41 13556: 
1.394     bowersj2 13557: =item * B<con_lost>: unable to contact remote host
1.191     harris41 13558: 
1.394     bowersj2 13559: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   13560: when the connection is brought back up
1.191     harris41 13561: 
1.394     bowersj2 13562: =item * B<con_failed>: unable to contact remote host and unable to save message
                   13563: for later delivery
1.191     harris41 13564: 
1.967     bisitz   13565: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 13566: 
1.394     bowersj2 13567: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 13568: that was requested
1.191     harris41 13569: 
1.243     albertel 13570: =back
1.191     harris41 13571: 
1.243     albertel 13572: =head1 PUBLIC SUBROUTINES
1.191     harris41 13573: 
1.243     albertel 13574: =head2 Session Environment Functions
1.191     harris41 13575: 
1.243     albertel 13576: =over 4
1.191     harris41 13577: 
1.394     bowersj2 13578: =item * 
                   13579: X<appenv()>
1.949     raeburn  13580: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 13581: the user envirnoment file, and will be restored for each access this
1.620     albertel 13582: user makes during this session, also modifies the %env for the current
1.949     raeburn  13583: process. Optional rolesarrayref - if defined contains a reference to an array
                   13584: of roles which are exempt from the restriction on modifying user.role entries 
                   13585: in the user's environment.db and in %env.    
1.191     harris41 13586: 
                   13587: =item *
1.394     bowersj2 13588: X<delenv()>
1.987     raeburn  13589: B<delenv($delthis,$regexp)>: removes all items from the session
                   13590: environment file that begin with $delthis. If the 
                   13591: optional second arg - $regexp - is true, $delthis is treated as a 
                   13592: regular expression, otherwise \Q$delthis\E is used. 
                   13593: The values are also deleted from the current processes %env.
1.191     harris41 13594: 
1.795     albertel 13595: =item * get_env_multiple($name) 
                   13596: 
                   13597: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   13598: values may be defined and end up as an array ref.
                   13599: 
                   13600: returns an array of values
                   13601: 
1.243     albertel 13602: =back
                   13603: 
                   13604: =head2 User Information
1.191     harris41 13605: 
1.243     albertel 13606: =over 4
1.191     harris41 13607: 
                   13608: =item *
1.394     bowersj2 13609: X<queryauthenticate()>
                   13610: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 13611: authentication scheme
                   13612: 
                   13613: =item *
1.394     bowersj2 13614: X<authenticate()>
1.1073    raeburn  13615: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 13616: authenticate user from domain's lib servers (first use the current
                   13617: one). C<$upass> should be the users password.
1.1073    raeburn  13618: $checkdefauth is optional (value is 1 if a check should be made to
                   13619:    authenticate user using default authentication method, and allow
                   13620:    account creation if username does not have account in the domain).
                   13621: $clientcancheckhost is optional (value is 1 if checking whether the
                   13622:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 13623: 
                   13624: =item *
1.394     bowersj2 13625: X<homeserver()>
                   13626: B<homeserver($uname,$udom)>: find the server which has
                   13627: the user's directory and files (there must be only one), this caches
                   13628: the answer, and also caches if there is a borken connection.
1.191     harris41 13629: 
                   13630: =item *
1.394     bowersj2 13631: X<idget()>
1.1300    raeburn  13632: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   13633: a list of student/employee IDs or clicker IDs
                   13634: (student/employee IDs are a unique resource in a domain, there must be 
                   13635: only 1 ID per username, and only 1 username per ID in a specific domain).
                   13636: clickerIDs are not necessarily unique, as students might share clickers.
                   13637: (returns hash: id=>name,id=>name)
1.191     harris41 13638: 
                   13639: =item *
1.394     bowersj2 13640: X<idrget()>
                   13641: B<idrget($udom,@unames)>: find the IDs behind a list of
                   13642: usernames (returns hash: name=>id,name=>id)
1.191     harris41 13643: 
                   13644: =item *
1.394     bowersj2 13645: X<idput()>
1.1300    raeburn  13646: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   13647: names and associated student/employee IDs or clicker IDs.
                   13648: 
                   13649: =item *
                   13650: X<iddel()>
                   13651: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   13652: student/employee ID or clicker ID username look-ups from domain.
                   13653: The homeserver ($uhome) and namespace ($namespace) are optional.
                   13654: If no $uhome is provided, it will be determined usig &homeserver()
                   13655: for each user.  If no $namespace is provided, the default is ids.
                   13656: 
                   13657: =item *
                   13658: X<updateclickers()>
                   13659: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   13660: clicker ID-to-username look-ups in clickers.db on library server.
                   13661: Permitted actions are add or del (i.e., add or delete). The 
                   13662: clickers.db contains clickerID as keys (escaped), and each corresponding
                   13663: value is an escaped comma-separated list of usernames (for whom the
                   13664: library server is the homeserver), who registered that particular ID.
                   13665: If $critical is true, the update will be sent via &critical, otherwise
                   13666: &reply() will be used.
1.191     harris41 13667: 
                   13668: =item *
1.394     bowersj2 13669: X<rolesinit()>
1.1169    droeschl 13670: B<rolesinit($udom,$username)>: get user privileges.
                   13671: returns user role, first access and timer interval hashes
1.243     albertel 13672: 
                   13673: =item *
1.1171    droeschl 13674: X<privileged()>
                   13675: B<privileged($username,$domain)>: returns a true if user has a
                   13676: privileged and active role (i.e. su or dc), false otherwise.
                   13677: 
                   13678: =item *
1.551     albertel 13679: X<getsection()>
                   13680: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 13681: course $cname, return section name/number or '' for "not in course"
                   13682: and '-1' for "no section"
                   13683: 
                   13684: =item *
1.394     bowersj2 13685: X<userenvironment()>
                   13686: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 13687: passed in @what from the requested user's environment, returns a hash
                   13688: 
1.858     raeburn  13689: =item * 
                   13690: X<userlog_query()>
1.859     albertel 13691: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   13692: activity.log file. %filters defines filters applied when parsing the
                   13693: log file. These can be start or end timestamps, or the type of action
                   13694: - log to look for Login or Logout events, check for Checkin or
                   13695: Checkout, role for role selection. The response is in the form
                   13696: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   13697: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  13698: 
1.243     albertel 13699: =back
                   13700: 
                   13701: =head2 User Roles
                   13702: 
                   13703: =over 4
                   13704: 
                   13705: =item *
                   13706: 
1.1284    raeburn  13707: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   13708: returns codes for allowed actions.
                   13709: 
                   13710: The first argument is required, all others are optional.
                   13711: 
                   13712: $priv is the privilege being checked.
                   13713: $uri contains additional information about what is being checked for access (e.g.,
                   13714: URL, course ID etc.). 
                   13715: $symb is the unique resource instance identifier in a course; if needed,
                   13716: but not provided, it will be retrieved via a call to &symbread(). 
                   13717: $role is the role for which a priv is being checked (only used if priv is evb). 
                   13718: $clientip is the user's IP address (only used when checking for access to portfolio 
                   13719: files).
                   13720: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   13721: prevents recursive calls to &allowed.
                   13722: 
1.243     albertel 13723:  F: full access
                   13724:  U,I,K: authentication modes (cxx only)
                   13725:  '': forbidden
                   13726:  1: user needs to choose course
                   13727:  2: browse allowed
1.766     albertel 13728:  A: passphrase authentication needed
1.1284    raeburn  13729:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 13730: 
                   13731: =item *
                   13732: 
1.1192    raeburn  13733: constructaccess($url,$setpriv) : check for access to construction space URL
                   13734: 
                   13735: See if the owner domain and name in the URL match those in the
                   13736: expected environment.  If so, return three element list
                   13737: ($ownername,$ownerdomain,$ownerhome).
                   13738: 
                   13739: Otherwise return the null string.
                   13740: 
                   13741: If second argument 'setpriv' is true, it assigns the privileges,
                   13742: and returns the same three element list, unless the owner has
                   13743: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   13744: in which case the null string is returned.
                   13745: 
                   13746: =item *
                   13747: 
1.243     albertel 13748: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   13749: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   13750: and course level
                   13751: 
                   13752: =item *
                   13753: 
1.988     raeburn  13754: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   13755: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  13756: $type is Course (default) or Community.
1.988     raeburn  13757: If $forcedefault evaluates to true, text returned will be default 
                   13758: text for $type. Otherwise, if this is a course, the text returned 
                   13759: will be a custom name for the role (if defined in the course's 
                   13760: environment).  If no custom name is defined the default is returned.
                   13761:    
1.832     raeburn  13762: =item *
                   13763: 
1.1219    raeburn  13764: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  13765: All arguments are optional. Returns a hash of a roles, either for
                   13766: co-author/assistant author roles for a user's Construction Space
1.906     albertel 13767: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  13768: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   13769: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   13770: For each key, value is set to colon-separated start and end times for
                   13771: the role.  If no username and domain are specified, will default to
1.934     raeburn  13772: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  13773: of role statuses (active, future or previous), roles 
                   13774: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   13775: to restrict the list of roles reported. If no array ref is 
                   13776: provided for types, will default to return only active roles.
1.834     albertel 13777: 
1.1195    raeburn  13778: =item *
                   13779: 
                   13780: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  13781: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   13782: 
                   13783: Additional optional arguments are: $type (if role checking is to be restricted 
                   13784: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  13785: available roles) or future (roles available in the future), and
                   13786: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  13787: have active Domain Coordinator role in course's domain or in additional
                   13788: domains (specified in 'Domains to check for privileged users' in course
                   13789: environment -- set via:  Course Settings -> Classlists and staff listing).
                   13790: 
                   13791: =item *
                   13792: 
                   13793: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   13794: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   13795: $possdomains and $possroles are optional array refs -- to domains to check and
                   13796: roles to check.  If $possdomains is not specified, a dump will be done of the
                   13797: users' roles.db to check for a dc or su role in any domain. This can be
                   13798: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   13799: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   13800: this then allows &privileged_by_domain() to be used, which caches the identity
                   13801: of privileged users, eliminating the need for repeated calls to &dump().
                   13802: 
                   13803: =item *
                   13804: 
                   13805: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   13806: where the outer hash keys are domains specified in the $possdomains array ref,
                   13807: next inner hash keys are privileged roles specified in the $roles array ref,
                   13808: and the innermost hash contains key = value pairs for username:domain = end:start
                   13809: for active or future "privileged" users with that role in that domain. To avoid
                   13810: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   13811: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  13812: 
1.243     albertel 13813: =back
                   13814: 
                   13815: =head2 User Modification
                   13816: 
                   13817: =over 4
                   13818: 
                   13819: =item *
                   13820: 
1.957     raeburn  13821: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 13822: user for the level given by URL.  Optional start and end dates (leave empty
                   13823: string or zero for "no date")
1.191     harris41 13824: 
                   13825: =item *
                   13826: 
1.243     albertel 13827: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   13828: change a users, password, possible return values are: ok,
                   13829: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   13830: refused
1.191     harris41 13831: 
                   13832: =item *
                   13833: 
1.243     albertel 13834: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 13835: 
                   13836: =item *
                   13837: 
1.1058    raeburn  13838: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   13839:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   13840: 
                   13841: will update user information (firstname,middlename,lastname,generation,
                   13842: permanentemail), and if forceid is true, student/employee ID also.
                   13843: A user's institutional affiliation(s) can also be updated.
                   13844: User information fields will not be overwritten with empty entries 
                   13845: unless the field is included in the $candelete array reference.
                   13846: This array is included when a single user is modified via "Manage Users",
                   13847: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 13848: 
                   13849: =item *
                   13850: 
1.286     matthew  13851: modifystudent
                   13852: 
1.957     raeburn  13853: modify a student's enrollment and identification information.
1.1235    raeburn  13854: The course id is resolved based on the current user's environment.  
                   13855: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  13856: associated with a course.
                   13857: 
1.297     matthew  13858: This call is essentially a wrapper for lonnet::modifyuser and
                   13859: lonnet::modify_student_enrollment
1.286     matthew  13860: 
                   13861: Inputs: 
                   13862: 
                   13863: =over 4
                   13864: 
1.957     raeburn  13865: =item B<$udom> Student's loncapa domain
1.286     matthew  13866: 
1.957     raeburn  13867: =item B<$uname> Student's loncapa login name
1.286     matthew  13868: 
1.964     bisitz   13869: =item B<$uid> Student/Employee ID
1.286     matthew  13870: 
1.957     raeburn  13871: =item B<$umode> Student's authentication mode
1.286     matthew  13872: 
1.957     raeburn  13873: =item B<$upass> Student's password
1.286     matthew  13874: 
1.957     raeburn  13875: =item B<$first> Student's first name
1.286     matthew  13876: 
1.957     raeburn  13877: =item B<$middle> Student's middle name
1.286     matthew  13878: 
1.957     raeburn  13879: =item B<$last> Student's last name
1.286     matthew  13880: 
1.957     raeburn  13881: =item B<$gene> Student's generation
1.286     matthew  13882: 
1.957     raeburn  13883: =item B<$usec> Student's section in course
1.286     matthew  13884: 
                   13885: =item B<$end> Unix time of the roles expiration
                   13886: 
                   13887: =item B<$start> Unix time of the roles start date
                   13888: 
                   13889: =item B<$forceid> If defined, allow $uid to be changed
                   13890: 
                   13891: =item B<$desiredhome> server to use as home server for student
                   13892: 
1.957     raeburn  13893: =item B<$email> Student's permanent e-mail address
                   13894: 
                   13895: =item B<$type> Type of enrollment (auto or manual)
                   13896: 
1.963     raeburn  13897: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   13898: 
                   13899: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  13900: 
1.963     raeburn  13901: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  13902: 
1.963     raeburn  13903: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  13904: 
1.1216    raeburn  13905: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   13906: 
                   13907: =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  13908: 
1.286     matthew  13909: =back
1.297     matthew  13910: 
                   13911: =item *
                   13912: 
                   13913: modify_student_enrollment
                   13914: 
1.1235    raeburn  13915: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  13916: 'role.request.course' must be defined for this function to proceed.
                   13917: 
                   13918: Inputs:
                   13919: 
                   13920: =over 4
                   13921: 
1.1235    raeburn  13922: =item $udom, student's domain
1.297     matthew  13923: 
1.1235    raeburn  13924: =item $uname, student's name
1.297     matthew  13925: 
1.1235    raeburn  13926: =item $uid, student's user id
1.297     matthew  13927: 
1.1235    raeburn  13928: =item $first, student's first name
1.297     matthew  13929: 
                   13930: =item $middle
                   13931: 
                   13932: =item $last
                   13933: 
                   13934: =item $gene
                   13935: 
                   13936: =item $usec
                   13937: 
                   13938: =item $end
                   13939: 
                   13940: =item $start
                   13941: 
1.957     raeburn  13942: =item $type
                   13943: 
                   13944: =item $locktype
                   13945: 
                   13946: =item $cid
                   13947: 
                   13948: =item $selfenroll
                   13949: 
                   13950: =item $context
                   13951: 
1.1216    raeburn  13952: =item $credits, number of credits student will earn from this class
                   13953: 
1.1314    raeburn  13954: =item $instsec, institutional course section code for student
                   13955: 
1.297     matthew  13956: =back
                   13957: 
1.191     harris41 13958: 
                   13959: =item *
                   13960: 
1.243     albertel 13961: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   13962: custom role; give a custom role to a user for the level given by URL.  Specify
                   13963: name and domain of role author, and role name
1.191     harris41 13964: 
                   13965: =item *
                   13966: 
1.243     albertel 13967: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 13968: 
                   13969: =item *
                   13970: 
1.243     albertel 13971: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   13972: 
                   13973: =back
                   13974: 
                   13975: =head2 Course Infomation
                   13976: 
                   13977: =over 4
1.191     harris41 13978: 
                   13979: =item *
                   13980: 
1.1118    foxr     13981: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 13982: specified course id, including all environment settings for the
                   13983: course, the description of the course will be in the hash under the
                   13984: key 'description'
1.191     harris41 13985: 
1.1118    foxr     13986: $options is an optional parameter that if supplied is a hash reference that controls
                   13987: what how this function works.  It has the following key/values:
                   13988: 
                   13989: =over 4
                   13990: 
                   13991: =item freshen_cache
                   13992: 
                   13993: If defined, and the environment cache for the course is valid, it is 
                   13994: returned in the returned hash.
                   13995: 
                   13996: =item one_time
                   13997: 
                   13998: If defined, the last cache time is set to _now_
                   13999: 
                   14000: =item user
                   14001: 
                   14002: If defined, the supplied username is used instead of the current user.
                   14003: 
                   14004: 
                   14005: =back
                   14006: 
1.191     harris41 14007: =item *
                   14008: 
1.624     albertel 14009: resdata($name,$domain,$type,@which) : request for current parameter
                   14010: setting for a specific $type, where $type is either 'course' or 'user',
                   14011: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  14012: answers for 10 minutes.
1.243     albertel 14013: 
1.877     foxr     14014: =item *
                   14015: 
                   14016: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14017: data base, returning a hash that is keyed by the resource name and has
                   14018: values that are the resource value.  I believe that the timestamps and
                   14019: versions are also returned.
                   14020: 
1.1236    raeburn  14021: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14022: supplemental content area. This routine caches the number of files for 
                   14023: 10 minutes.
                   14024: 
1.243     albertel 14025: =back
                   14026: 
                   14027: =head2 Course Modification
                   14028: 
                   14029: =over 4
1.191     harris41 14030: 
                   14031: =item *
                   14032: 
1.243     albertel 14033: writecoursepref($courseid,%prefs) : write preferences (environment
                   14034: database) for a course
1.191     harris41 14035: 
                   14036: =item *
                   14037: 
1.1011    raeburn  14038: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14039: 
                   14040: =item *
                   14041: 
1.1038    raeburn  14042: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14043: 
1.1167    droeschl 14044: =item *
                   14045: 
                   14046: is_course($courseid), is_course($cdom, $cnum)
                   14047: 
                   14048: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14049: two component version $cdom, $cnum. It checks if the specified course exists.
                   14050: 
                   14051: Returns:
                   14052:     undef if the course doesn't exist, otherwise
                   14053:     in scalar context the combined courseid.
                   14054:     in list context the two components of the course identifier, domain and 
                   14055:     courseid.    
                   14056: 
1.243     albertel 14057: =back
                   14058: 
                   14059: =head2 Resource Subroutines
                   14060: 
                   14061: =over 4
1.191     harris41 14062: 
                   14063: =item *
                   14064: 
1.243     albertel 14065: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14066: 
                   14067: =item *
                   14068: 
1.243     albertel 14069: repcopy($filename) : subscribes to the requested file, and attempts to
                   14070: replicate from the owning library server, Might return
1.607     raeburn  14071: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14072: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14073: resource. Expects the local filesystem pathname
                   14074: (/home/httpd/html/res/....)
                   14075: 
                   14076: =back
                   14077: 
                   14078: =head2 Resource Information
                   14079: 
                   14080: =over 4
1.191     harris41 14081: 
                   14082: =item *
                   14083: 
1.1228    raeburn  14084: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14085: and returns the value of a variety of different possible values,
                   14086: $varname should be a request string, and the other parameters can be
                   14087: used to specify who and what one is asking about. Ordinarily, $cid 
                   14088: does not need to be specified, as it is retrived from 
                   14089: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14090: within lonuserstate::loadmap() when initializing a course, before
                   14091: $env{'request.course.id'} has been set, so it needs to be provided
                   14092: in that one case.
1.243     albertel 14093: 
                   14094: Possible values for $varname are environment.lastname (or other item
                   14095: from the envirnment hash), user.name (or someother aspect about the
                   14096: user), resource.0.maxtries (or some other part and parameter of a
                   14097: resource)
1.204     albertel 14098: 
                   14099: =item *
                   14100: 
1.243     albertel 14101: directcondval($number) : get current value of a condition; reads from a state
                   14102: string
1.204     albertel 14103: 
                   14104: =item *
                   14105: 
1.243     albertel 14106: condval($condidx) : value of condition index based on state
1.204     albertel 14107: 
                   14108: =item *
                   14109: 
1.243     albertel 14110: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14111: resource's metadata, $what should be either a specific key, or either
                   14112: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14113: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14114: 
                   14115: this function automatically caches all requests
1.191     harris41 14116: 
                   14117: =item *
                   14118: 
1.243     albertel 14119: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14120: network of library servers; returns file handle of where SQL and regex results
                   14121: will be stored for query
1.191     harris41 14122: 
                   14123: =item *
                   14124: 
1.1282    raeburn  14125: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   14126: return symbolic list entry (all arguments optional). 
                   14127: 
                   14128: Args: filename is the filename (including path) for the file for which a symb 
                   14129: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   14130: to check access status if more than one resource was found in the bighash 
                   14131: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   14132: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   14133: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14134: cause possible symbs to be checked to determine if they are subject to content
                   14135: blocking, if so they will not be included as possible symbs; possibles is a
                   14136: ref to a hash, which, as a side effect, will be populated with all possible 
                   14137: symbs (content blocking not tested).
                   14138:  
1.243     albertel 14139: returns the data handle
1.191     harris41 14140: 
                   14141: =item *
                   14142: 
1.1190    raeburn  14143: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   14144: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14145: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  14146: on failure, user must be in a course, as it assumes the existence of
                   14147: the course initial hash, and uses $env('request.course.id'}.  The third
                   14148: arg is an optional reference to a scalar.  If this arg is passed in the 
                   14149: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14150: encrypted; otherwise it will be null.  
1.191     harris41 14151: 
                   14152: =item *
                   14153: 
1.243     albertel 14154: symbclean($symb) : removes versions numbers from a symb, returns the
                   14155: cleaned symb
1.191     harris41 14156: 
                   14157: =item *
                   14158: 
1.243     albertel 14159: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14160: course map, user must be in a course for it to work.
1.191     harris41 14161: 
                   14162: =item *
                   14163: 
1.243     albertel 14164: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14165: 
                   14166: =item *
                   14167: 
1.243     albertel 14168: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14169: a random seed, all arguments are optional, if they aren't sent it uses the
                   14170: environment to derive them. Note: if symb isn't sent and it can't get one
                   14171: from &symbread it will use the current time as its return value
1.191     harris41 14172: 
                   14173: =item *
                   14174: 
1.243     albertel 14175: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14176: unfakeable, receipt
1.191     harris41 14177: 
                   14178: =item *
                   14179: 
1.620     albertel 14180: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14181: 
                   14182: =item *
                   14183: 
1.243     albertel 14184: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14185: 
                   14186: =item *
                   14187: 
1.243     albertel 14188: 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 14189: 
                   14190: =item *
                   14191: 
1.243     albertel 14192: 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 14193: 
                   14194: =item *
                   14195: 
1.243     albertel 14196: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14197: 
                   14198: =item *
                   14199: 
1.243     albertel 14200: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14201: forcing spreadsheet to reevaluate the resource scores next time.
                   14202: 
1.1195    raeburn  14203: =item * 
                   14204: 
1.1196    raeburn  14205: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14206: when viewing in course context.
1.1195    raeburn  14207: 
1.1196    raeburn  14208:  input: six args -- filename (decluttered), course number, course domain,
                   14209:                     url, symb (if registered) and group (if this is a 
                   14210:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  14211: 
1.1196    raeburn  14212:  output: array of five scalars --
1.1195    raeburn  14213:          $cfile -- url for file editing if editable on current server
                   14214:          $home -- homeserver of resource (i.e., for author if published,
                   14215:                                           or course if uploaded.).
                   14216:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  14217:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   14218:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  14219: 
                   14220: =item *
                   14221: 
                   14222: is_course_upload($file,$cnum,$cdom)
                   14223: 
                   14224: Used in course context to determine if current file was uploaded to 
                   14225: the course (i.e., would be found in /userfiles/docs on the course's 
                   14226: homeserver.
                   14227: 
                   14228:   input: 3 args -- filename (decluttered), course number and course domain.
                   14229:   output: boolean -- 1 if file was uploaded.
                   14230: 
1.243     albertel 14231: =back
                   14232: 
                   14233: =head2 Storing/Retreiving Data
                   14234: 
                   14235: =over 4
1.191     harris41 14236: 
                   14237: =item *
                   14238: 
1.1269    raeburn  14239: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   14240: permanently for this url; hashref needs to be given and should be a \%hashname;
                   14241: the remaining args aren't required and if they aren't passed or are '' they will
                   14242: be derived from the env (with the exception of $laststore, which is an 
                   14243: optional arg used when a user's submission is stored in grading).
                   14244: $laststore is $version=$timestamp, where $version is the most recent version
                   14245: number retrieved for the corresponding $symb in the $namespace db file, and
                   14246: $timestamp is the timestamp for that transaction (UNIX time).
                   14247: $laststore is currently only passed when cstore() is called by 
                   14248: structuretags::finalize_storage().
1.191     harris41 14249: 
                   14250: =item *
                   14251: 
1.1269    raeburn  14252: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   14253: but uses critical subroutine
1.191     harris41 14254: 
                   14255: =item *
                   14256: 
1.243     albertel 14257: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14258: all args are optional
1.191     harris41 14259: 
                   14260: =item *
                   14261: 
1.717     albertel 14262: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14263: dumps the complete (or key matching regexp) namespace into a hash
                   14264: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14265: normally &store()ed into
                   14266: 
                   14267: $range should be either an integer '100' (give me the first 100
                   14268:                                            matching records)
                   14269:               or be  two integers sperated by a - with no spaces
                   14270:                  '30-50' (give me the 30th through the 50th matching
                   14271:                           records)
                   14272: 
                   14273: 
                   14274: =item *
                   14275: 
1.1269    raeburn  14276: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14277: replaces a &store() version of data with a replacement set of data
                   14278: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  14279: reference. If $tolog is true, the transaction is logged in the courselog
                   14280: with an action=PUTSTORE.
1.717     albertel 14281: 
                   14282: =item *
                   14283: 
1.243     albertel 14284: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14285: works very similar to store/cstore, but all data is stored in a
                   14286: temporary location and can be reset using tmpreset, $storehash should
                   14287: be a hash reference, returns nothing on success
1.191     harris41 14288: 
                   14289: =item *
                   14290: 
1.243     albertel 14291: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14292: similar to restore, but all data is stored in a temporary location and
                   14293: can be reset using tmpreset. Returns a hash of values on success,
                   14294: error string otherwise.
1.191     harris41 14295: 
                   14296: =item *
                   14297: 
1.243     albertel 14298: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14299: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14300: 
                   14301: =item *
                   14302: 
1.243     albertel 14303: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14304: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14305: 
                   14306: =item *
                   14307: 
1.243     albertel 14308: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14309: namesp ($udom and $uname are optional)
1.191     harris41 14310: 
                   14311: =item *
                   14312: 
1.702     albertel 14313: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14314: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14315: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  14316: 
1.702     albertel 14317: $range should be either an integer '100' (give me the first 100
                   14318:                                            matching records)
                   14319:               or be  two integers sperated by a - with no spaces
                   14320:                  '30-50' (give me the 30th through the 50th matching
                   14321:                           records)
1.449     matthew  14322: =item *
                   14323: 
                   14324: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   14325: $store can be a scalar, an array reference, or if the amount to be 
                   14326: incremented is > 1, a hash reference.
                   14327: 
                   14328: ($udom and $uname are optional)
1.191     harris41 14329: 
                   14330: =item *
                   14331: 
1.243     albertel 14332: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   14333: ($udom and $uname are optional)
1.191     harris41 14334: 
                   14335: =item *
                   14336: 
1.243     albertel 14337: cput($namespace,$storehash,$udom,$uname) : critical put
                   14338: ($udom and $uname are optional)
1.191     harris41 14339: 
                   14340: =item *
                   14341: 
1.748     albertel 14342: newput($namespace,$storehash,$udom,$uname) :
                   14343: 
                   14344: Attempts to store the items in the $storehash, but only if they don't
                   14345: currently exist, if this succeeds you can be certain that you have 
                   14346: successfully created a new key value pair in the $namespace db.
                   14347: 
                   14348: 
                   14349: Args:
                   14350:  $namespace: name of database to store values to
                   14351:  $storehash: hashref to store to the db
                   14352:  $udom: (optional) domain of user containing the db
                   14353:  $uname: (optional) name of user caontaining the db
                   14354: 
                   14355: Returns:
                   14356:  'ok' -> succeeded in storing all keys of $storehash
                   14357:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   14358:                         least <key> already existed in the db (other
                   14359:                         requested keys may also already exist)
1.967     bisitz   14360:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 14361:  'con_lost' -> unable to contact request server
                   14362:  'refused' -> action was not allowed by remote machine
                   14363: 
                   14364: 
                   14365: =item *
                   14366: 
1.243     albertel 14367: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14368: reference filled in from namesp (encrypts the return communication)
                   14369: ($udom and $uname are optional)
1.191     harris41 14370: 
                   14371: =item *
                   14372: 
1.243     albertel 14373: log($udom,$name,$home,$message) : write to permanent log for user; use
                   14374: critical subroutine
                   14375: 
1.806     raeburn  14376: =item *
                   14377: 
1.860     raeburn  14378: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   14379: array reference filled in from namespace found in domain level on either
                   14380: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  14381: 
                   14382: =item *
                   14383: 
1.860     raeburn  14384: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   14385: domain level either on specified domain server ($uhome) or primary domain 
                   14386: server ($udom and $uhome are optional)
1.806     raeburn  14387: 
1.943     raeburn  14388: =item * 
                   14389: 
1.1240    raeburn  14390: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   14391: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   14392: the target domain.
                   14393: 
                   14394: May also include additional key => value pairs for the following groups:
                   14395: 
                   14396: =over
                   14397: 
                   14398: =item
                   14399: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   14400: 
                   14401: =over
                   14402: 
                   14403: =item defaultquota, authorquota
                   14404: 
                   14405: =back
                   14406: 
                   14407: =item
                   14408: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   14409: portfolio for users).
                   14410: 
                   14411: =over
                   14412: 
                   14413: =item
                   14414: aboutme, blog, webdav, portfolio
                   14415: 
                   14416: =back
                   14417: 
                   14418: =item
                   14419: requestcourses: ability to request courses, and how requests are processed.
                   14420: 
                   14421: =over
                   14422: 
                   14423: =item
1.1305    raeburn  14424: official, unofficial, community, textbook, placement
1.1240    raeburn  14425: 
                   14426: =back
                   14427: 
                   14428: =item
                   14429: inststatus: types of institutional affiliation, and order in which they are displayed.
                   14430: 
                   14431: =over
                   14432: 
                   14433: =item
1.1256    raeburn  14434: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  14435: 
                   14436: =back
                   14437: 
                   14438: =item
                   14439: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   14440: for course's uploaded content.
                   14441: 
                   14442: =over
                   14443: 
                   14444: =item
1.1246    raeburn  14445: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  14446: communityquota, textbookquota, placementquota
1.1240    raeburn  14447: 
                   14448: =back
                   14449: 
                   14450: =item
                   14451: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   14452: on your servers.
                   14453: 
                   14454: =over
                   14455: 
                   14456: =item 
                   14457: remotesessions, hostedsessions
                   14458: 
                   14459: =back
                   14460: 
                   14461: =back
                   14462: 
                   14463: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   14464: utility to create a configuration.db file on a domain's primary library server 
                   14465: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   14466: -- corresponding values are authentication type (internal, krb4, krb5,
                   14467: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   14468: will be available. Values are retrieved from cache (if current), unless the
                   14469: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   14470: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   14471: 
                   14472: Typical usage:
1.943     raeburn  14473: 
1.1240    raeburn  14474: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  14475: 
1.243     albertel 14476: =back
                   14477: 
                   14478: =head2 Network Status Functions
                   14479: 
                   14480: =over 4
1.191     harris41 14481: 
                   14482: =item *
                   14483: 
1.1137    raeburn  14484: dirlist() : return directory list based on URI (first arg).
                   14485: 
                   14486: Inputs: 1 required, 5 optional.
                   14487: 
                   14488: =over
                   14489: 
                   14490: =item 
                   14491: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   14492: 
                   14493: =item
                   14494: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   14495: 
                   14496: =item
                   14497: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   14498: 
                   14499: =item
                   14500: $getpropath - boolean: 1 if prepend path using &propath(). 
                   14501: 
                   14502: =item
                   14503: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   14504: 
                   14505: =item 
                   14506: $alternateRoot - path to prepend in place of path from $uri.
                   14507: 
                   14508: =back
                   14509: 
                   14510: Returns: Array of up to two items.
                   14511: 
                   14512: =over
                   14513: 
                   14514: a reference to an array of files/subdirectories
                   14515: 
                   14516: =over
                   14517: 
                   14518: Each element in the array of files/subdirectories is a & separated list of
                   14519: item name and the result of running stat on the item.  If dirlist was requested
                   14520: for a file instead of a directory, the item name will be ''. For a directory 
                   14521: listing, if the item is a metadata file, the element will end &N&M 
                   14522: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   14523: default copyright set (1).  
                   14524: 
                   14525: =back
                   14526: 
                   14527: a scalar containing error condition (if encountered).
                   14528: 
                   14529: =over
                   14530: 
                   14531: =item 
                   14532: no_host (no homeserver identified for $username:$domain).
                   14533: 
                   14534: =item 
                   14535: no_such_host (server contacted for listing not identified as valid host).
                   14536: 
                   14537: =item 
                   14538: con_lost (connection to remote server failed).
                   14539: 
                   14540: =item 
                   14541: refused (invalid $username:$domain received on lond side).
                   14542: 
                   14543: =item 
                   14544: no_such_dir (directory at specified path on lond side does not exist). 
                   14545: 
                   14546: =item 
                   14547: empty (directory at specified path on lond side is empty).
                   14548: 
                   14549: =over
                   14550: 
                   14551: This is currently not encountered because the &ls3, &ls2, 
                   14552: &ls (_handler) routines on the lond side do not filter out
                   14553: . and .. from a directory listing. 
                   14554: 
                   14555: =back
                   14556: 
                   14557: =back
                   14558: 
                   14559: =back
1.191     harris41 14560: 
                   14561: =item *
                   14562: 
1.243     albertel 14563: spareserver() : find server with least workload from spare.tab
                   14564: 
1.986     foxr     14565: 
                   14566: =item *
                   14567: 
                   14568: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   14569: if there is no corresponding loncapa host.
                   14570: 
1.243     albertel 14571: =back
                   14572: 
1.986     foxr     14573: 
1.243     albertel 14574: =head2 Apache Request
                   14575: 
                   14576: =over 4
1.191     harris41 14577: 
                   14578: =item *
                   14579: 
1.243     albertel 14580: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   14581: localhost, posts hash
                   14582: 
                   14583: =back
                   14584: 
                   14585: =head2 Data to String to Data
                   14586: 
                   14587: =over 4
1.191     harris41 14588: 
                   14589: =item *
                   14590: 
1.243     albertel 14591: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   14592: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 14593: 
                   14594: =item *
                   14595: 
1.243     albertel 14596: hashref2str($hashref) : convert a hashref into a string complete with
                   14597: escaping and '=' and '&' separators, supports elements that are
                   14598: arrayrefs and hashrefs
1.191     harris41 14599: 
                   14600: =item *
                   14601: 
1.243     albertel 14602: arrayref2str($arrayref) : convert an arrayref into a string complete
                   14603: with escaping and '&' separators, supports elements that are arrayrefs
                   14604: and hashrefs
1.191     harris41 14605: 
                   14606: =item *
                   14607: 
1.243     albertel 14608: str2hash($string) : convert string to hash using unescaping and
                   14609: splitting on '=' and '&', supports elements that are arrayrefs and
                   14610: hashrefs
1.191     harris41 14611: 
                   14612: =item *
                   14613: 
1.243     albertel 14614: str2array($string) : convert string to hash using unescaping and
                   14615: splitting on '&', supports elements that are arrayrefs and hashrefs
                   14616: 
                   14617: =back
                   14618: 
                   14619: =head2 Logging Routines
                   14620: 
                   14621: 
                   14622: These routines allow one to make log messages in the lonnet.log and
                   14623: lonnet.perm logfiles.
1.191     harris41 14624: 
1.1119    foxr     14625: =over 4
                   14626: 
1.191     harris41 14627: =item *
                   14628: 
1.243     albertel 14629: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 14630: 
                   14631: =item *
                   14632: 
1.243     albertel 14633: logthis() : append message to the normal lonnet.log file, it gets
                   14634: preiodically rolled over and deleted.
1.191     harris41 14635: 
                   14636: =item *
                   14637: 
1.243     albertel 14638: logperm() : append a permanent message to lonnet.perm.log, this log
                   14639: file never gets deleted by any automated portion of the system, only
                   14640: messages of critical importance should go in here.
                   14641: 
1.1119    foxr     14642: 
1.243     albertel 14643: =back
                   14644: 
                   14645: =head2 General File Helper Routines
                   14646: 
                   14647: =over 4
1.191     harris41 14648: 
                   14649: =item *
                   14650: 
1.481     raeburn  14651: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   14652: (a) files in /uploaded
                   14653:   (i) If a local copy of the file exists - 
                   14654:       compares modification date of local copy with last-modified date for 
                   14655:       definitive version stored on home server for course. If local copy is 
                   14656:       stale, requests a new version from the home server and stores it. 
                   14657:       If the original has been removed from the home server, then local copy 
                   14658:       is unlinked.
                   14659:   (ii) If local copy does not exist -
                   14660:       requests the file from the home server and stores it. 
                   14661:   
                   14662:   If $caller is 'uploadrep':  
                   14663:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   14664:     for request for files originally uploaded via DOCS. 
                   14665:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   14666:   
                   14667:   Otherwise:
                   14668:      This indicates a call from the content generation phase of the request.
                   14669:      -  returns the entire contents of the file or -1.
                   14670:      
                   14671: (b) files in /res
                   14672:    - returns the entire contents of a file or -1; 
                   14673:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 14674: 
1.712     albertel 14675: 
                   14676: =item *
                   14677: 
                   14678: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   14679:                   reference
                   14680: 
                   14681: returns either a stat() list of data about the file or an empty list
                   14682: if the file doesn't exist or couldn't find out about it (connection
                   14683: problems or user unknown)
                   14684: 
1.191     harris41 14685: =item *
                   14686: 
1.243     albertel 14687: filelocation($dir,$file) : returns file system location of a file
                   14688: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   14689: directory that relative $file lookups are to looked in ($dir of /a/dir
                   14690: and a file of ../bob will become /a/bob)
1.191     harris41 14691: 
                   14692: =item *
                   14693: 
                   14694: hreflocation($dir,$file) : returns file system location or a URL; same as
                   14695: filelocation except for hrefs
                   14696: 
                   14697: =item *
                   14698: 
1.1261    raeburn  14699: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   14700: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 14701: 
1.243     albertel 14702: =back
                   14703: 
1.608     albertel 14704: =head2 Usererfile file routines (/uploaded*)
                   14705: 
                   14706: =over 4
                   14707: 
                   14708: =item *
                   14709: 
                   14710: userfileupload(): main rotine for putting a file in a user or course's
                   14711:                   filespace, arguments are,
                   14712: 
1.620     albertel 14713:  formname - required - this is the name of the element in $env where the
1.608     albertel 14714:            filename, and the contents of the file to create/modifed exist
1.620     albertel 14715:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   14716:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  14717:  context - if coursedoc, store the file in the course of the active role
                   14718:              of the current user; 
                   14719:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   14720:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 14721:  subdir - required - subdirectory to put the file in under ../userfiles/
                   14722:          if undefined, it will be placed in "unknown"
                   14723: 
                   14724:  (This routine calls clean_filename() to remove any dangerous
                   14725:  characters from the filename, and then calls finuserfileupload() to
                   14726:  complete the transaction)
                   14727: 
                   14728:  returns either the url of the uploaded file (/uploaded/....) if successful
                   14729:  and /adm/notfound.html if unsuccessful
                   14730: 
                   14731: =item *
                   14732: 
                   14733: clean_filename(): routine for cleaing a filename up for storage in
                   14734:                  userfile space, argument is:
                   14735: 
                   14736:  filename - proposed filename
                   14737: 
                   14738: returns: the new clean filename
                   14739: 
                   14740: =item *
                   14741: 
1.1090    raeburn  14742: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 14743: userspace, probably shouldn't be called directly
                   14744: 
                   14745:   docuname: username or courseid of destination for the file
                   14746:   docudom: domain of user/course of destination for the file
                   14747:   formname: same as for userfileupload()
1.1090    raeburn  14748:   fname: filename (including subdirectories) for the file
                   14749:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   14750:   allfiles: reference to hash used to store objects found by parser
                   14751:   codebase: reference to hash used for codebases of java objects found by parser
                   14752:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   14753:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   14754:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   14755:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   14756:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   14757:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  14758:   mimetype: reference to scalar to accommodate mime type determined
                   14759:             from File::MMagic if $parser = parse.
1.608     albertel 14760: 
                   14761:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  14762:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   14763:  was 'overwrite').
                   14764:  
1.608     albertel 14765: 
                   14766: =item *
                   14767: 
                   14768: renameuserfile(): renames an existing userfile to a new name
                   14769: 
                   14770:   Args:
                   14771:    docuname: username or courseid of destination for the file
                   14772:    docudom: domain of user/course of destination for the file
                   14773:    old: current file name (including any subdirs under userfiles)
                   14774:    new: desired file name (including any subdirs under userfiles)
                   14775: 
                   14776: =item *
                   14777: 
                   14778: mkdiruserfile(): creates a directory is a userfiles dir
                   14779: 
                   14780:   Args:
                   14781:    docuname: username or courseid of destination for the file
                   14782:    docudom: domain of user/course of destination for the file
                   14783:    dir: dir to create (including any subdirs under userfiles)
                   14784: 
                   14785: =item *
                   14786: 
                   14787: removeuserfile(): removes a file that exists in userfiles
                   14788: 
                   14789:   Args:
                   14790:    docuname: username or courseid of destination for the file
                   14791:    docudom: domain of user/course of destination for the file
                   14792:    fname: filname to delete (including any subdirs under userfiles)
                   14793: 
                   14794: =item *
                   14795: 
                   14796: removeuploadedurl(): convience function for removeuserfile()
                   14797: 
                   14798:   Args:
                   14799:    url:  a full /uploaded/... url to delete
                   14800: 
1.747     albertel 14801: =item * 
                   14802: 
                   14803: get_portfile_permissions():
                   14804:   Args:
                   14805:     domain: domain of user or course contain the portfolio files
                   14806:     user: name of user or num of course contain the portfolio files
                   14807:   Returns:
                   14808:     hashref of a dump of the proper file_permissions.db
                   14809:    
                   14810: 
                   14811: =item * 
                   14812: 
                   14813: get_access_controls():
                   14814: 
                   14815: Args:
                   14816:   current_permissions: the hash ref returned from get_portfile_permissions()
                   14817:   group: (optional) the group you want the files associated with
                   14818:   file: (optional) the file you want access info on
                   14819: 
                   14820: Returns:
1.749     raeburn  14821:     a hash (keys are file names) of hashes containing
                   14822:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   14823:         values are XML containing access control settings (see below) 
1.747     albertel 14824: 
                   14825: Internal notes:
                   14826: 
1.749     raeburn  14827:  access controls are stored in file_permissions.db as key=value pairs.
                   14828:     key -> path to file/file_name\0uniqueID:scope_end_start
                   14829:         where scope -> public,guest,course,group,domains or users.
                   14830:               end -> UNIX time for end of access (0 -> no end date)
                   14831:               start -> UNIX time for start of access
                   14832: 
                   14833:     value -> XML description of access control
                   14834:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   14835:             <start></start>
                   14836:             <end></end>
                   14837: 
                   14838:             <password></password>  for scope type = guest
                   14839: 
                   14840:             <domain></domain>     for scope type = course or group
                   14841:             <number></number>
                   14842:             <roles id="">
                   14843:              <role></role>
                   14844:              <access></access>
                   14845:              <section></section>
                   14846:              <group></group>
                   14847:             </roles>
                   14848: 
                   14849:             <dom></dom>         for scope type = domains
                   14850: 
                   14851:             <users>             for scope type = users
                   14852:              <user>
                   14853:               <uname></uname>
                   14854:               <udom></udom>
                   14855:              </user>
                   14856:             </users>
                   14857:            </scope> 
                   14858:               
                   14859:  Access data is also aggregated for each file in an additional key=value pair:
                   14860:  key -> path to file/file_name\0accesscontrol 
                   14861:  value -> reference to hash
                   14862:           hash contains key = value pairs
                   14863:           where key = uniqueID:scope_end_start
                   14864:                 value = UNIX time record was last updated
                   14865: 
                   14866:           Used to improve speed of look-ups of access controls for each file.  
                   14867:  
                   14868:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   14869: 
1.1198    raeburn  14870: =item *
                   14871: 
1.749     raeburn  14872: modify_access_controls():
                   14873: 
                   14874: Modifies access controls for a portfolio file
                   14875: Args
                   14876: 1. file name
                   14877: 2. reference to hash of required changes,
                   14878: 3. domain
                   14879: 4. username
                   14880:   where domain,username are the domain of the portfolio owner 
                   14881:   (either a user or a course) 
                   14882: 
                   14883: Returns:
                   14884: 1. result of additions or updates ('ok' or 'error', with error message). 
                   14885: 2. result of deletions ('ok' or 'error', with error message).
                   14886: 3. reference to hash of any new or updated access controls.
                   14887: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   14888:    key = integer (inbound ID)
1.1198    raeburn  14889:    value = uniqueID
                   14890: 
                   14891: =item *
                   14892: 
                   14893: get_timebased_id():
                   14894: 
                   14895: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   14896: course via the Course Editor (e.g., folders, composite pages, 
                   14897: group bulletin boards).
                   14898: 
                   14899: Args: (first three required; six others optional)
                   14900: 
                   14901: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   14902:    docssequence, or name of group
                   14903: 
                   14904: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   14905:    e.g., num, boardids
                   14906: 
                   14907: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   14908:    file will be named nohist_namespace.db
                   14909: 
                   14910: 4. cdom: domain of course; default is current course domain from %env
                   14911: 
                   14912: 5. cnum: course number; default is current course number from %env
                   14913: 
                   14914: 6. idtype: set to concat if an additional digit is to be appended to the 
                   14915:    unix timestamp to form the suffix, if the plain timestamp is already
                   14916:    in use.  Default is to not do this, but simply increment the unix 
                   14917:    timestamp by 1 until a unique key is obtained.
                   14918: 
                   14919: 7. who: holder of locking key; defaults to user:domain for user.
                   14920: 
                   14921: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   14922:    retrying); default is 3.
                   14923: 
                   14924: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   14925: 
                   14926: Returns:
                   14927: 
                   14928: 1. suffix obtained (numeric)
                   14929: 
                   14930: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   14931: 
                   14932: 3. error: contains (localized) error message if an error occurred.
                   14933: 
1.747     albertel 14934: 
1.608     albertel 14935: =back
                   14936: 
1.243     albertel 14937: =head2 HTTP Helper Routines
                   14938: 
                   14939: =over 4
                   14940: 
1.191     harris41 14941: =item *
                   14942: 
                   14943: escape() : unpack non-word characters into CGI-compatible hex codes
                   14944: 
                   14945: =item *
                   14946: 
                   14947: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   14948: 
1.243     albertel 14949: =back
                   14950: 
                   14951: =head1 PRIVATE SUBROUTINES
                   14952: 
                   14953: =head2 Underlying communication routines (Shouldn't call)
                   14954: 
                   14955: =over 4
                   14956: 
                   14957: =item *
                   14958: 
                   14959: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   14960: 
                   14961: =item *
                   14962: 
                   14963: reply() : uses subreply to send a message to remote machine, logs all failures
                   14964: 
                   14965: =item *
                   14966: 
                   14967: critical() : passes a critical message to another server; if cannot
                   14968: get through then place message in connection buffer directory and
                   14969: returns con_delayed, if incapable of saving message, returns
                   14970: con_failed
                   14971: 
                   14972: =item *
                   14973: 
                   14974: reconlonc() : tries to reconnect lonc client processes.
                   14975: 
                   14976: =back
                   14977: 
                   14978: =head2 Resource Access Logging
                   14979: 
                   14980: =over 4
                   14981: 
                   14982: =item *
                   14983: 
                   14984: flushcourselogs() : flush (save) buffer logs and access logs
                   14985: 
                   14986: =item *
                   14987: 
                   14988: courselog($what) : save message for course in hash
                   14989: 
                   14990: =item *
                   14991: 
                   14992: courseacclog($what) : save message for course using &courselog().  Perform
                   14993: special processing for specific resource types (problems, exams, quizzes, etc).
                   14994: 
1.191     harris41 14995: =item *
                   14996: 
                   14997: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   14998: as a PerlChildExitHandler
1.243     albertel 14999: 
                   15000: =back
                   15001: 
                   15002: =head2 Other
                   15003: 
                   15004: =over 4
                   15005: 
                   15006: =item *
                   15007: 
                   15008: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15009: 
                   15010: =back
                   15011: 
                   15012: =cut
1.877     foxr     15013: 

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