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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1315  ! raeburn     4: # $Id: lonnet.pm,v 1.1314 2016/07/24 14:35:29 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:     }
        !           238:     if (($context ne 'cgi') || $uselocal) {
        !           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.1315  ! raeburn  2245:                                   'coursecategories','ssl','autoenroll'],$domain);
1.1305    raeburn  2246:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2247:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2248:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2249:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2250:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2251:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2252:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2253:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  2254:     } else {
                   2255:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2256:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2257:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2258:     }
1.976     raeburn  2259:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2260:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2261:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2262:         } else {
                   2263:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2264:         }
1.1177    raeburn  2265:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2266:         foreach my $item (@usertools) {
                   2267:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2268:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2269:             }
                   2270:         }
1.1229    raeburn  2271:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2272:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2273:         }
1.976     raeburn  2274:     }
1.985     raeburn  2275:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2276:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2277:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2278:         }
                   2279:     }
1.1183    raeburn  2280:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2281:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2282:     }
1.989     raeburn  2283:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2284:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2285:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2286:         }
                   2287:     }
1.1047    raeburn  2288:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2289:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2290:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2291:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2292:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2293:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2294:         }
1.1254    raeburn  2295:         foreach my $type (@coursetypes) {
                   2296:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2297:                 unless ($type eq 'community') {
                   2298:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2299:                 }
                   2300:             }
                   2301:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2302:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2303:             }
1.1277    raeburn  2304:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2305:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2306:                     $domdefaults{$type.'postsubtimeout'} = 
                   2307:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2308:                 }
                   2309:             }
1.1230    raeburn  2310:         }
1.1286    raeburn  2311:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2312:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2313:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2314:                 if (@clonecodes) {
                   2315:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2316:                 }
                   2317:             }
                   2318:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2319:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2320:         }
1.1047    raeburn  2321:     }
1.1073    raeburn  2322:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2323:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2324:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2325:         }
                   2326:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2327:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2328:         }
1.1279    raeburn  2329:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2330:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2331:         }
1.1073    raeburn  2332:     }
1.1254    raeburn  2333:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2334:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2335:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2336:                             'approval','limit');
                   2337:             foreach my $type (@coursetypes) {
                   2338:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2339:                     my @mgrdc = ();
                   2340:                     foreach my $item (@settings) {
                   2341:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2342:                             push(@mgrdc,$item);
                   2343:                         }
                   2344:                     }
                   2345:                     if (@mgrdc) {
                   2346:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2347:                     }
                   2348:                 }
                   2349:             }
                   2350:         }
                   2351:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2352:             foreach my $type (@coursetypes) {
                   2353:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2354:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2355:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2356:                     }
                   2357:                 }
                   2358:             }
                   2359:         }
                   2360:     }
1.1258    raeburn  2361:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2362:         $domdefaults{'catauth'} = 'std';
                   2363:         $domdefaults{'catunauth'} = 'std';
                   2364:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2365:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2366:         }
                   2367:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2368:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2369:         }
                   2370:     }
1.1315  ! raeburn  2371:     if (ref($domconfig{'ssl'}) eq 'HASH') {
        !          2372:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
        !          2373:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
        !          2374:         }
        !          2375:         if (ref($domconfig{'ssl'}{'connect'}) eq 'HASH') {
        !          2376:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connect'};
        !          2377:         }
        !          2378:     }
1.1314    raeburn  2379:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2380:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2381:     }
1.1219    raeburn  2382:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2383:     return %domdefaults;
                   2384: }
                   2385: 
1.1311    raeburn  2386: sub course_portal_url {
                   2387:     my ($cnum,$cdom) = @_;
                   2388:     my $chome = &homeserver($cnum,$cdom);
                   2389:     my $hostname = &hostname($chome);
                   2390:     my $protocol = $protocol{$chome};
                   2391:     $protocol = 'http' if ($protocol ne 'https');
                   2392:     my %domdefaults = &get_domain_defaults($cdom);
                   2393:     my $firsturl;
                   2394:     if ($domdefaults{'portal_def'}) {
                   2395:         $firsturl = $domdefaults{'portal_def'};
                   2396:     } else {
                   2397:         $firsturl = $protocol.'://'.$hostname;
                   2398:     }
                   2399:     return $firsturl;
                   2400: }
                   2401: 
1.344     www      2402: # --------------------------------------------------- Assign a key to a student
                   2403: 
                   2404: sub assign_access_key {
1.364     www      2405: #
                   2406: # a valid key looks like uname:udom#comments
                   2407: # comments are being appended
                   2408: #
1.498     www      2409:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2410:     $kdom=
1.620     albertel 2411:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2412:     $knum=
1.620     albertel 2413:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2414:     $cdom=
1.620     albertel 2415:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2416:     $cnum=
1.620     albertel 2417:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2418:     $udom=$env{'user.name'} unless (defined($udom));
                   2419:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2420:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2421:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2422:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2423:                                                   # assigned to this person
                   2424:                                                   # - this should not happen,
1.345     www      2425:                                                   # unless something went wrong
                   2426:                                                   # the first time around
                   2427: # ready to assign
1.364     www      2428:         $logentry=$1.'; '.$logentry;
1.496     www      2429:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2430:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2431: # key now belongs to user
1.346     www      2432: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2433:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2434:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2435:                 return 'ok';
                   2436:             } else {
                   2437:                 return 
                   2438:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2439: 	    }
                   2440:         } else {
                   2441:             return 'error: Could not assign key, try again later.';
                   2442:         }
1.364     www      2443:     } elsif (!$existing{$ckey}) {
1.345     www      2444: # the key does not exist
                   2445: 	return 'error: The key does not exist';
                   2446:     } else {
                   2447: # the key is somebody else's
                   2448: 	return 'error: The key is already in use';
                   2449:     }
1.344     www      2450: }
                   2451: 
1.364     www      2452: # ------------------------------------------ put an additional comment on a key
                   2453: 
                   2454: sub comment_access_key {
                   2455: #
                   2456: # a valid key looks like uname:udom#comments
                   2457: # comments are being appended
                   2458: #
                   2459:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2460:     $cdom=
1.620     albertel 2461:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2462:     $cnum=
1.620     albertel 2463:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2464:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2465:     if ($existing{$ckey}) {
                   2466:         $existing{$ckey}.='; '.$logentry;
                   2467: # ready to assign
1.367     www      2468:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2469:                                                  $cdom,$cnum) eq 'ok') {
                   2470: 	    return 'ok';
                   2471:         } else {
                   2472: 	    return 'error: Count not store comment.';
                   2473:         }
                   2474:     } else {
                   2475: # the key does not exist
                   2476: 	return 'error: The key does not exist';
                   2477:     }
                   2478: }
                   2479: 
1.344     www      2480: # ------------------------------------------------------ Generate a set of keys
                   2481: 
                   2482: sub generate_access_keys {
1.364     www      2483:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2484:     $cdom=
1.620     albertel 2485:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2486:     $cnum=
1.620     albertel 2487:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2488:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2489:     unless (($cdom) && ($cnum)) { return 0; }
                   2490:     if ($number>10000) { return 0; }
                   2491:     sleep(2); # make sure don't get same seed twice
                   2492:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2493:     my $total=0;
                   2494:     for (my $i=1;$i<=$number;$i++) {
                   2495:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2496:                   sprintf("%lx",int(100000*rand)).'-'.
                   2497:                   sprintf("%lx",int(100000*rand));
                   2498:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2499:        $newkey=~s/0/h/g; # and also 0 and O
                   2500:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2501:        if ($existing{$newkey}) {
                   2502:            $i--;
                   2503:        } else {
1.364     www      2504: 	  if (&put('accesskeys',
                   2505:               { $newkey => '# generated '.localtime().
1.620     albertel 2506:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2507:                            '; '.$logentry },
                   2508: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2509:               $total++;
                   2510: 	  }
                   2511:        }
                   2512:     }
1.620     albertel 2513:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2514:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2515:     return $total;
                   2516: }
                   2517: 
                   2518: # ------------------------------------------------------- Validate an accesskey
                   2519: 
                   2520: sub validate_access_key {
                   2521:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2522:     $cdom=
1.620     albertel 2523:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2524:     $cnum=
1.620     albertel 2525:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2526:     $udom=$env{'user.domain'} unless (defined($udom));
                   2527:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2528:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2529:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2530: }
                   2531: 
                   2532: # ------------------------------------- Find the section of student in a course
1.652     albertel 2533: sub devalidate_getsection_cache {
                   2534:     my ($udom,$unam,$courseid)=@_;
                   2535:     my $hashid="$udom:$unam:$courseid";
                   2536:     &devalidate_cache_new('getsection',$hashid);
                   2537: }
1.298     matthew  2538: 
1.815     albertel 2539: sub courseid_to_courseurl {
                   2540:     my ($courseid) = @_;
                   2541:     #already url style courseid
                   2542:     return $courseid if ($courseid =~ m{^/});
                   2543: 
                   2544:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2545: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2546: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2547: 	return "/$cdom/$cnum";
                   2548:     }
                   2549: 
                   2550:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2551:     if (exists($courseinfo{'num'})) {
                   2552: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2553:     }
                   2554: 
                   2555:     return undef;
                   2556: }
                   2557: 
1.298     matthew  2558: sub getsection {
                   2559:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2560:     my $cachetime=1800;
1.551     albertel 2561: 
                   2562:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2563:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2564:     if (defined($cached)) { return $result; }
                   2565: 
1.298     matthew  2566:     my %Pending; 
                   2567:     my %Expired;
                   2568:     #
                   2569:     # Each role can either have not started yet (pending), be active, 
                   2570:     #    or have expired.
                   2571:     #
                   2572:     # If there is an active role, we are done.
                   2573:     #
                   2574:     # If there is more than one role which has not started yet, 
                   2575:     #     choose the one which will start sooner
                   2576:     # If there is one role which has not started yet, return it.
                   2577:     #
                   2578:     # If there is more than one expired role, choose the one which ended last.
                   2579:     # If there is a role which has expired, return it.
                   2580:     #
1.815     albertel 2581:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2582:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2583:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2584:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2585:         my $section=$1;
                   2586:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2587:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2588:         my $now=time;
1.548     albertel 2589:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2590:             $Expired{$end}=$section;
                   2591:             next;
                   2592:         }
1.548     albertel 2593:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2594:             $Pending{$start}=$section;
                   2595:             next;
                   2596:         }
1.599     albertel 2597:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2598:     }
                   2599:     #
                   2600:     # Presumedly there will be few matching roles from the above
                   2601:     # loop and the sorting time will be negligible.
                   2602:     if (scalar(keys(%Pending))) {
                   2603:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2604:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2605:     } 
                   2606:     if (scalar(keys(%Expired))) {
                   2607:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2608:         my $time = pop(@sorted);
1.599     albertel 2609:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2610:     }
1.599     albertel 2611:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2612: }
1.70      www      2613: 
1.599     albertel 2614: sub save_cache {
                   2615:     &purge_remembered();
1.722     albertel 2616:     #&Apache::loncommon::validate_page();
1.620     albertel 2617:     undef(%env);
1.780     albertel 2618:     undef($env_loaded);
1.599     albertel 2619: }
1.452     albertel 2620: 
1.599     albertel 2621: my $to_remember=-1;
                   2622: my %remembered;
                   2623: my %accessed;
                   2624: my $kicks=0;
                   2625: my $hits=0;
1.849     albertel 2626: sub make_key {
                   2627:     my ($name,$id) = @_;
1.872     albertel 2628:     if (length($id) > 65 
                   2629: 	&& length(&escape($id)) > 200) {
                   2630: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2631:     }
1.849     albertel 2632:     return &escape($name.':'.$id);
                   2633: }
                   2634: 
1.599     albertel 2635: sub devalidate_cache_new {
                   2636:     my ($name,$id,$debug) = @_;
                   2637:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2638:     $id=&make_key($name,$id);
1.599     albertel 2639:     $memcache->delete($id);
                   2640:     delete($remembered{$id});
                   2641:     delete($accessed{$id});
                   2642: }
                   2643: 
                   2644: sub is_cached_new {
                   2645:     my ($name,$id,$debug) = @_;
1.849     albertel 2646:     $id=&make_key($name,$id);
1.599     albertel 2647:     if (exists($remembered{$id})) {
1.1133    foxr     2648: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2649: 	$accessed{$id}=[&gettimeofday()];
                   2650: 	$hits++;
                   2651: 	return ($remembered{$id},1);
                   2652:     }
                   2653:     my $value = $memcache->get($id);
                   2654:     if (!(defined($value))) {
                   2655: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2656: 	return (undef,undef);
1.416     albertel 2657:     }
1.599     albertel 2658:     if ($value eq '__undef__') {
                   2659: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2660: 	$value=undef;
                   2661:     }
                   2662:     &make_room($id,$value,$debug);
                   2663:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2664:     return ($value,1);
                   2665: }
                   2666: 
                   2667: sub do_cache_new {
                   2668:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2669:     $id=&make_key($name,$id);
1.599     albertel 2670:     my $setvalue=$value;
                   2671:     if (!defined($setvalue)) {
                   2672: 	$setvalue='__undef__';
                   2673:     }
1.623     albertel 2674:     if (!defined($time) ) {
                   2675: 	$time=600;
                   2676:     }
1.599     albertel 2677:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2678:     my $result = $memcache->set($id,$setvalue,$time);
                   2679:     if (! $result) {
1.872     albertel 2680: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2681: 	$memcache->disconnect_all();
1.872     albertel 2682:     }
1.600     albertel 2683:     # need to make a copy of $value
1.919     albertel 2684:     &make_room($id,$value,$debug);
1.599     albertel 2685:     return $value;
                   2686: }
                   2687: 
                   2688: sub make_room {
                   2689:     my ($id,$value,$debug)=@_;
1.919     albertel 2690: 
                   2691:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2692:                                     : $value;
1.599     albertel 2693:     if ($to_remember<0) { return; }
                   2694:     $accessed{$id}=[&gettimeofday()];
                   2695:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2696:     my $to_kick;
                   2697:     my $max_time=0;
                   2698:     foreach my $other (keys(%accessed)) {
                   2699: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2700: 	    $to_kick=$other;
                   2701: 	    $max_time=&tv_interval($accessed{$other});
                   2702: 	}
                   2703:     }
                   2704:     delete($remembered{$to_kick});
                   2705:     delete($accessed{$to_kick});
                   2706:     $kicks++;
                   2707:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2708:     return;
                   2709: }
                   2710: 
1.599     albertel 2711: sub purge_remembered {
1.604     albertel 2712:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2713:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2714:     undef(%remembered);
                   2715:     undef(%accessed);
1.428     albertel 2716: }
1.70      www      2717: # ------------------------------------- Read an entry from a user's environment
                   2718: 
                   2719: sub userenvironment {
                   2720:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2721:     my $items;
                   2722:     foreach my $item (@what) {
                   2723:         $items.=&escape($item).'&';
                   2724:     }
                   2725:     $items=~s/\&$//;
1.70      www      2726:     my %returnhash=();
1.1009    raeburn  2727:     my $uhome = &homeserver($unam,$udom);
                   2728:     unless ($uhome eq 'no_host') {
                   2729:         my @answer=split(/\&/, 
                   2730:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2731:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2732:             return %returnhash;
                   2733:         }
1.1009    raeburn  2734:         my $i;
                   2735:         for ($i=0;$i<=$#what;$i++) {
                   2736: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2737:         }
1.70      www      2738:     }
                   2739:     return %returnhash;
1.1       albertel 2740: }
                   2741: 
1.617     albertel 2742: # ---------------------------------------------------------- Get a studentphoto
                   2743: sub studentphoto {
                   2744:     my ($udom,$unam,$ext) = @_;
                   2745:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2746:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2747:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2748:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2749:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2750:             } else {
                   2751:                 my ($result,$perm_reqd)=
1.707     albertel 2752: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2753:                 if ($result eq 'ok') {
                   2754:                     if (!($perm_reqd eq 'yes')) {
                   2755:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2756:                     }
                   2757:                 }
                   2758:             }
                   2759:         }
                   2760:     } else {
                   2761:         my ($result,$perm_reqd) = 
1.707     albertel 2762: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2763:         if ($result eq 'ok') {
                   2764:             if (!($perm_reqd eq 'yes')) {
                   2765:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2766:             }
                   2767:         }
                   2768:     }
                   2769:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2770: }
                   2771: 
                   2772: sub retrievestudentphoto {
                   2773:     my ($udom,$unam,$ext,$type) = @_;
                   2774:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2775:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2776:     if ($ret eq 'ok') {
                   2777:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2778:         if ($type eq 'thumbnail') {
                   2779:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2780:         }
                   2781:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2782:         return $tokenurl;
                   2783:     } else {
                   2784:         if ($type eq 'thumbnail') {
                   2785:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2786:         } else { 
                   2787:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2788:         }
1.617     albertel 2789:     }
                   2790: }
                   2791: 
1.263     www      2792: # -------------------------------------------------------------------- New chat
                   2793: 
                   2794: sub chatsend {
1.724     raeburn  2795:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2796:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2797:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2798:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2799:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2800: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2801: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2802: }
                   2803: 
                   2804: # ------------------------------------------ Find current version of a resource
                   2805: 
                   2806: sub getversion {
                   2807:     my $fname=&clutter(shift);
1.1189    raeburn  2808:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2809:     return &currentversion(&filelocation('',$fname));
                   2810: }
                   2811: 
                   2812: sub currentversion {
                   2813:     my $fname=shift;
                   2814:     my $author=$fname;
                   2815:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2816:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2817:     my $home=&homeserver($uname,$udom);
1.292     www      2818:     if ($home eq 'no_host') { 
                   2819:         return -1; 
                   2820:     }
1.1112    www      2821:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2822:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2823: 	return -1;
                   2824:     }
1.1112    www      2825:     return $answer;
1.263     www      2826: }
                   2827: 
1.1111    www      2828: #
                   2829: # Return special version number of resource if set by override, empty otherwise
                   2830: #
                   2831: sub usedversion {
                   2832:     my $fname=shift;
                   2833:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2834:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2835:     if ($urlversion) { return $urlversion; }
                   2836:     return '';
                   2837: }
                   2838: 
1.1       albertel 2839: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2840: 
1.1       albertel 2841: sub subscribe {
                   2842:     my $fname=shift;
1.761     raeburn  2843:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2844:     $fname=~s/[\n\r]//g;
1.1       albertel 2845:     my $author=$fname;
                   2846:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2847:     my ($udom,$uname)=split(/\//,$author);
                   2848:     my $home=homeserver($uname,$udom);
1.335     albertel 2849:     if ($home eq 'no_host') {
                   2850:         return 'not_found';
1.1       albertel 2851:     }
                   2852:     my $answer=reply("sub:$fname",$home);
1.64      www      2853:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2854: 	$answer.=' by '.$home;
                   2855:     }
1.1       albertel 2856:     return $answer;
                   2857: }
                   2858:     
1.8       www      2859: # -------------------------------------------------------------- Replicate file
                   2860: 
                   2861: sub repcopy {
                   2862:     my $filename=shift;
1.23      www      2863:     $filename=~s/\/+/\//g;
1.1142    raeburn  2864:     my $londocroot = $perlvar{'lonDocRoot'};
                   2865:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2866:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2867:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2868: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2869: 	return &repcopy_userfile($filename);
                   2870:     }
1.532     albertel 2871:     $filename=~s/[\n\r]//g;
1.8       www      2872:     my $transname="$filename.in.transfer";
1.828     www      2873: # FIXME: this should flock
1.607     raeburn  2874:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2875:     my $remoteurl=subscribe($filename);
1.64      www      2876:     if ($remoteurl =~ /^con_lost by/) {
                   2877: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2878:            return 'unavailable';
1.8       www      2879:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2880: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2881: 	   return 'not_found';
1.64      www      2882:     } elsif ($remoteurl =~ /^rejected by/) {
                   2883: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2884:            return 'forbidden';
1.20      www      2885:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2886:            return 'ok';
1.8       www      2887:     } else {
1.290     www      2888:         my $author=$filename;
                   2889:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2890:         my ($udom,$uname)=split(/\//,$author);
                   2891:         my $home=homeserver($uname,$udom);
                   2892:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2893:            my @parts=split(/\//,$filename);
                   2894:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2895:            if ($path ne "$londocroot/res") {
1.8       www      2896:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2897: 	       return 'bad_request';
1.8       www      2898:            }
                   2899:            my $count;
                   2900:            for ($count=5;$count<$#parts;$count++) {
                   2901:                $path.="/$parts[$count]";
                   2902:                if ((-e $path)!=1) {
                   2903: 		   mkdir($path,0777);
                   2904:                }
                   2905:            }
                   2906:            my $ua=new LWP::UserAgent;
                   2907:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2908:            my $response=$ua->request($request,$transname);
                   2909:            if ($response->is_error()) {
                   2910: 	       unlink($transname);
                   2911:                my $message=$response->status_line;
1.672     albertel 2912:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2913:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2914:                return 'unavailable';
1.8       www      2915:            } else {
1.16      www      2916: 	       if ($remoteurl!~/\.meta$/) {
                   2917:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2918:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2919:                   if ($mresponse->is_error()) {
                   2920: 		      unlink($filename.'.meta');
                   2921:                       &logthis(
1.672     albertel 2922:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2923:                   }
                   2924: 	       }
1.8       www      2925:                rename($transname,$filename);
1.607     raeburn  2926:                return 'ok';
1.8       www      2927:            }
1.290     www      2928:        }
1.8       www      2929:     }
1.330     www      2930: }
                   2931: 
                   2932: # ------------------------------------------------ Get server side include body
                   2933: sub ssi_body {
1.381     albertel 2934:     my ($filelink,%form)=@_;
1.606     matthew  2935:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2936:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2937:     }
1.953     www      2938:     my $output='';
                   2939:     my $response;
1.980     raeburn  2940:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2941:        ($output,$response)=&externalssi($filelink);
1.953     www      2942:     } else {
1.1004    droeschl 2943:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2944:        $filelink .= 'inhibitmenu=yes';
1.953     www      2945:        ($output,$response)=&ssi($filelink,%form);
                   2946:     }
1.778     albertel 2947:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2948:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2949:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2950:     if (wantarray) {
                   2951:         return ($output, $response);
                   2952:     } else {
                   2953:         return $output;
                   2954:     }
1.8       www      2955: }
                   2956: 
1.15      www      2957: # --------------------------------------------------------- Server Side Include
                   2958: 
1.782     albertel 2959: sub absolute_url {
                   2960:     my ($host_name) = @_;
                   2961:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2962:     if ($host_name eq '') {
                   2963: 	$host_name = $ENV{'SERVER_NAME'};
                   2964:     }
                   2965:     return $protocol.$host_name;
                   2966: }
                   2967: 
1.942     foxr     2968: #
                   2969: #   Server side include.
                   2970: # Parameters:
                   2971: #  fn     Possibly encrypted resource name/id.
                   2972: #  form   Hash that describes how the rendering should be done
                   2973: #         and other things.
1.944     foxr     2974: # Returns:
1.950     raeburn  2975: #   Scalar context: The content of the response.
                   2976: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2977: #     
1.15      www      2978: sub ssi {
                   2979: 
1.944     foxr     2980:     my ($fn,%form)=@_;
1.15      www      2981:     my $ua=new LWP::UserAgent;
1.23      www      2982:     my $request;
1.711     albertel 2983: 
                   2984:     $form{'no_update_last_known'}=1;
1.895     albertel 2985:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2986:     if (%form) {
1.782     albertel 2987:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 2988:       $request->content(join('&',map { 
                   2989:             my $name = escape($_);
                   2990:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   2991:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   2992:             : &escape($form{$_}) );    
                   2993:         } keys(%form)));
1.23      www      2994:     } else {
1.782     albertel 2995:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2996:     }
                   2997: 
1.15      www      2998:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173    foxr     2999:     my $response= $ua->request($request);
1.1182    foxr     3000:     my $content = $response->content;
                   3001: 
                   3002: 
1.944     foxr     3003:     if (wantarray) {
1.1173    foxr     3004: 	return ($content, $response);
1.944     foxr     3005:     } else {
1.1173    foxr     3006: 	return $content;
1.942     foxr     3007:     }
1.324     www      3008: }
                   3009: 
                   3010: sub externalssi {
                   3011:     my ($url)=@_;
                   3012:     my $ua=new LWP::UserAgent;
                   3013:     my $request=new HTTP::Request('GET',$url);
                   3014:     my $response=$ua->request($request);
1.954     raeburn  3015:     if (wantarray) {
                   3016:         return ($response->content, $response);
                   3017:     } else {
                   3018:         return $response->content;
                   3019:     }
1.15      www      3020: }
1.254     www      3021: 
1.492     albertel 3022: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3023: 
                   3024: sub allowuploaded {
                   3025:     my ($srcurl,$url)=@_;
                   3026:     $url=&clutter(&declutter($url));
                   3027:     my $dir=$url;
                   3028:     $dir=~s/\/[^\/]+$//;
                   3029:     my %httpref=();
                   3030:     my $httpurl=&hreflocation('',$url);
                   3031:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3032:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3033: }
1.477     raeburn  3034: 
1.1193    raeburn  3035: #
                   3036: # Determine if the current user should be able to edit a particular resource,
                   3037: # when viewing in course context.
                   3038: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3039: #     Functions.
                   3040: # (b) When displaying folder contents in course editor, used to determine if
                   3041: #     "Edit" link will be displayed alongside resource.
                   3042: #
1.1196    raeburn  3043: #  input: six args -- filename (decluttered), course number, course domain,
                   3044: #                   url, symb (if registered) and group (if this is a group
                   3045: #                   item -- e.g., bulletin board, group page etc.).
                   3046: #  output: array of five scalars -- 
1.1193    raeburn  3047: #          $cfile -- url for file editing if editable on current server
                   3048: #          $home -- homeserver of resource (i.e., for author if published,
                   3049: #                                           or course if uploaded.).
                   3050: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3051: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3052: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3053: #
                   3054: 
                   3055: sub can_edit_resource {
1.1194    raeburn  3056:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3057:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3058: #
                   3059: # For aboutme pages user can only edit his/her own.
                   3060: #
1.1199    raeburn  3061:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3062:         my ($sdom,$sname) = ($1,$2);
                   3063:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3064:             $home = $env{'user.home'};
                   3065:             $cfile = $resurl;
                   3066:             if ($env{'form.forceedit'}) {
                   3067:                 $forceview = 1;
                   3068:             } else {
                   3069:                 $forceedit = 1;
                   3070:             }
                   3071:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3072:         } else {
                   3073:             return;
                   3074:         }
                   3075:     }
                   3076: 
                   3077:     if ($env{'request.course.id'}) {
                   3078:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3079:         if ($group ne '') {
                   3080: # if this is a group homepage or group bulletin board, check group privs
                   3081:             my $allowed = 0;
1.1197    raeburn  3082:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3083:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3084:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3085:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3086:                     $allowed = 1;
                   3087:                 }
1.1197    raeburn  3088:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3089:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3090:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3091:                     $allowed = 1;
                   3092:                 }
                   3093:             }
                   3094:             if ($allowed) {
                   3095:                 $home=&homeserver($cnum,$cdom);
                   3096:                 if ($env{'form.forceedit'}) {
                   3097:                     $forceview = 1;
                   3098:                 } else {
                   3099:                     $forceedit = 1;
                   3100:                 }
                   3101:                 $cfile = $resurl;
                   3102:             } else {
                   3103:                 return;
                   3104:             }
                   3105:         } else {
1.1208    raeburn  3106:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3107:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3108:                     return;
                   3109:                 }
                   3110:             } elsif (!$crsedit) {
1.1194    raeburn  3111: #
                   3112: # No edit allowed where CC has switched to student role.
                   3113: #
                   3114:                 return;
                   3115:             }
                   3116:         }
                   3117:     }
                   3118: 
1.1193    raeburn  3119:     if ($file ne '') {
                   3120:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3121:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3122:                 $uploaded = 1;
                   3123:                 $incourse = 1;
1.1193    raeburn  3124:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3125:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3126:                     if ($env{'form.forceedit'}) {
                   3127:                         $forceview = 1;
                   3128:                     } else {
                   3129:                         $forceedit = 1;
                   3130:                     }
1.1194    raeburn  3131:                 }
                   3132:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3133:                 $incourse = 1;
                   3134:                 if ($env{'form.forceedit'}) {
                   3135:                     $forceview = 1;
                   3136:                 } else {
                   3137:                     $forceedit = 1;
                   3138:                 }
                   3139:                 $cfile = $resurl;
                   3140:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3141:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3142:                     $incourse = 1;
                   3143:                     if ($env{'form.forceedit'}) {
                   3144:                         $forceview = 1;
                   3145:                     } else {
                   3146:                         $forceedit = 1;
                   3147:                     }
                   3148:                     $cfile = $resurl;
1.1199    raeburn  3149:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3150:                     $incourse = 1;
                   3151:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3152:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3153:                     $incourse = 1;
1.1199    raeburn  3154:                     if ($env{'form.forceedit'}) {
                   3155:                         $forceview = 1;
                   3156:                     } else {
                   3157:                         $forceedit = 1;
                   3158:                     }
                   3159:                     $cfile = $resurl;
1.1298    raeburn  3160:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) {
                   3161:                     $incourse = 1;
                   3162:                     if ($env{'form.forceedit'}) {
                   3163:                         $forceview = 1;
                   3164:                     } else {
                   3165:                         $forceedit = 1;
                   3166:                     }
                   3167:                     $cfile = $resurl;
1.1208    raeburn  3168:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3169:                     $incourse = 1;
                   3170:                     if ($env{'form.forceedit'}) {
                   3171:                         $forceview = 1;
                   3172:                     } else {
                   3173:                         $forceedit = 1;
                   3174:                     }
                   3175:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3176:                 }
                   3177:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3178:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3179:                 if (&is_on_map($template)) { 
                   3180:                     $incourse = 1;
                   3181:                     $forceview = 1;
                   3182:                     $cfile = $template;
1.1193    raeburn  3183:                 }
1.1199    raeburn  3184:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3185:                     $incourse = 1;
                   3186:                     if ($env{'form.forceedit'}) {
                   3187:                         $forceview = 1;
                   3188:                     } else {
                   3189:                         $forceedit = 1;
                   3190:                     }
                   3191:                     $cfile = $resurl;
1.1298    raeburn  3192:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3193:                 $incourse = 1;
                   3194:                 if ($env{'form.forceedit'}) {
                   3195:                     $forceview = 1;
                   3196:                 } else {
                   3197:                     $forceedit = 1;
                   3198:                 }
                   3199:                 $cfile = $resurl;
1.1199    raeburn  3200:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3201:                 $incourse = 1;
                   3202:                 $forceview = 1;
                   3203:                 if ($symb) {
                   3204:                     my ($map,$id,$res)=&decode_symb($symb);
                   3205:                     $env{'request.symb'} = $symb;
                   3206:                     $cfile = &clutter($res);
                   3207:                 } else {
                   3208:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3209:                     my $escfile = &unescape($cfile);
                   3210:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/exttools?$}) {
                   3211:                         $cfile = '/adm/wrapper'.$escfile;
                   3212:                     } else {
                   3213:                         $escfile =~ s{^http://}{};
                   3214:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3215:                     }
1.1199    raeburn  3216:                 }
1.1234    raeburn  3217:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3218:                 if ($env{'form.forceedit'}) {
                   3219:                     $forceview = 1;
                   3220:                 } else {
                   3221:                     $forceedit = 1;
                   3222:                 }
                   3223:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3224:             }
                   3225:         }
1.1194    raeburn  3226:         if ($uploaded || $incourse) {
                   3227:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3228:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3229:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3230:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3231:             # Check that the user has permission to edit this resource
                   3232:             my $setpriv = 1;
                   3233:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3234:             if (defined($cfudom)) {
                   3235:                 $home=&homeserver($cfuname,$cfudom);
                   3236:                 $cfile=$file;
                   3237:             }
                   3238:         }
1.1194    raeburn  3239:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3240:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3241:             my @ids=&current_machine_ids();
                   3242:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3243:                 $switchserver=1;
                   3244:             }
                   3245:         }
                   3246:     }
1.1194    raeburn  3247:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3248: }
                   3249: 
                   3250: sub is_course_upload {
                   3251:     my ($file,$cnum,$cdom) = @_;
                   3252:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3253:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3254:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3255:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3256:         return 1;
                   3257:     }
                   3258:     return;
                   3259: }
                   3260: 
1.1194    raeburn  3261: sub in_course {
1.1195    raeburn  3262:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3263:     if ($hideprivileged) {
                   3264:         my $skipuser;
1.1219    raeburn  3265:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3266:         my @possdoms = ($cdom);  
                   3267:         if ($coursehash{'checkforpriv'}) { 
                   3268:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3269:         }
                   3270:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3271:             $skipuser = 1;
                   3272:             if ($coursehash{'nothideprivileged'}) {
                   3273:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3274:                     my $user;
                   3275:                     if ($item =~ /:/) {
                   3276:                         $user = $item;
                   3277:                     } else {
                   3278:                         $user = join(':',split(/[\@]/,$item));
                   3279:                     }
                   3280:                     if ($user eq $uname.':'.$udom) {
                   3281:                         undef($skipuser);
                   3282:                         last;
                   3283:                     }
                   3284:                 }
                   3285:             }
                   3286:             if ($skipuser) {
                   3287:                 return 0;
                   3288:             }
                   3289:         }
                   3290:     }
1.1194    raeburn  3291:     $type ||= 'any';
                   3292:     if (!defined($cdom) || !defined($cnum)) {
                   3293:         my $cid  = $env{'request.course.id'};
                   3294:         $cdom = $env{'course.'.$cid.'.domain'};
                   3295:         $cnum = $env{'course.'.$cid.'.num'};
                   3296:     }
                   3297:     my $typesref;
1.1195    raeburn  3298:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3299:         $typesref = ['active','previous','future'];
                   3300:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3301:         $typesref = [$type];
                   3302:     }
                   3303:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3304:                               $typesref,undef,[$cdom]);
                   3305:     my ($tmp) = keys(%roles);
                   3306:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3307:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3308:     if (@course_roles > 0) {
                   3309:         return 1;
                   3310:     }
                   3311:     return 0;
                   3312: }
                   3313: 
1.478     albertel 3314: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3315: # input: action, courseID, current domain, intended
1.637     raeburn  3316: #        path to file, source of file, instruction to parse file for objects,
                   3317: #        ref to hash for embedded objects,
                   3318: #        ref to hash for codebase of java objects.
1.1095    raeburn  3319: #        reference to scalar to accommodate mime type determined
                   3320: #          from File::MMagic if $parser = parse.
1.637     raeburn  3321: #
1.485     raeburn  3322: # output: url to file (if action was uploaddoc), 
                   3323: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3324: #
1.478     albertel 3325: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3326: # course.
1.477     raeburn  3327: #
1.478     albertel 3328: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3329: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3330: #          course's home server.
1.477     raeburn  3331: #
1.478     albertel 3332: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3333: #          be copied from $source (current location) to 
                   3334: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3335: #         and will then be copied to
                   3336: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3337: #         course's home server.
1.485     raeburn  3338: #
1.481     raeburn  3339: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3340: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3341: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3342: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3343: #         in course's home server.
1.637     raeburn  3344: #
1.477     raeburn  3345: 
                   3346: sub process_coursefile {
1.1095    raeburn  3347:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3348:         $mimetype)=@_;
1.477     raeburn  3349:     my $fetchresult;
1.638     albertel 3350:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3351:     if ($action eq 'propagate') {
1.638     albertel 3352:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3353: 			     $home);
1.481     raeburn  3354:     } else {
1.477     raeburn  3355:         my $fpath = '';
                   3356:         my $fname = $file;
1.478     albertel 3357:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3358:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3359:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3360:         if ($action eq 'copy') {
                   3361:             if ($source eq '') {
                   3362:                 $fetchresult = 'no source file';
                   3363:                 return $fetchresult;
                   3364:             } else {
                   3365:                 my $destination = $filepath.'/'.$fname;
                   3366:                 rename($source,$destination);
                   3367:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3368:                                  $home);
1.481     raeburn  3369:             }
                   3370:         } elsif ($action eq 'uploaddoc') {
                   3371:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3372:             print $fh $env{'form.'.$source};
1.481     raeburn  3373:             close($fh);
1.637     raeburn  3374:             if ($parser eq 'parse') {
1.1024    raeburn  3375:                 my $mm = new File::MMagic;
1.1095    raeburn  3376:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3377:                 if ($type eq 'text/html') {
1.1024    raeburn  3378:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3379:                     unless ($parse_result eq 'ok') {
                   3380:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3381:                     }
1.637     raeburn  3382:                 }
1.1095    raeburn  3383:                 if (ref($mimetype)) {
                   3384:                     $$mimetype = $type;
                   3385:                 } 
1.637     raeburn  3386:             }
1.477     raeburn  3387:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3388:                                  $home);
1.481     raeburn  3389:             if ($fetchresult eq 'ok') {
                   3390:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3391:             } else {
                   3392:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3393:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3394:                 return '/adm/notfound.html';
                   3395:             }
1.477     raeburn  3396:         }
                   3397:     }
1.485     raeburn  3398:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3399:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3400:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3401:     }
                   3402:     return $fetchresult;
                   3403: }
                   3404: 
1.637     raeburn  3405: sub build_filepath {
                   3406:     my ($fpath) = @_;
                   3407:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3408:     unless ($fpath eq '') {
                   3409:         my @parts=split('/',$fpath);
                   3410:         foreach my $part (@parts) {
                   3411:             $filepath.= '/'.$part;
                   3412:             if ((-e $filepath)!=1) {
                   3413:                 mkdir($filepath,0777);
                   3414:             }
                   3415:         }
                   3416:     }
                   3417:     return $filepath;
                   3418: }
                   3419: 
                   3420: sub store_edited_file {
1.638     albertel 3421:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3422:     my $file = $primary_url;
                   3423:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3424:     my $fpath = '';
                   3425:     my $fname = $file;
                   3426:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3427:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3428:     my $filepath = &build_filepath($fpath);
                   3429:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3430:     print $fh $content;
                   3431:     close($fh);
1.638     albertel 3432:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3433:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3434: 			  $home);
1.637     raeburn  3435:     if ($$fetchresult eq 'ok') {
                   3436:         return '/uploaded/'.$fpath.'/'.$fname;
                   3437:     } else {
1.638     albertel 3438:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3439: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3440:         return '/adm/notfound.html';
                   3441:     }
                   3442: }
                   3443: 
1.531     albertel 3444: sub clean_filename {
1.831     albertel 3445:     my ($fname,$args)=@_;
1.315     www      3446: # Replace Windows backslashes by forward slashes
1.257     www      3447:     $fname=~s/\\/\//g;
1.831     albertel 3448:     if (!$args->{'keep_path'}) {
                   3449:         # Get rid of everything but the actual filename
                   3450: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3451:     }
1.315     www      3452: # Replace spaces by underscores
                   3453:     $fname=~s/\s+/\_/g;
                   3454: # Replace all other weird characters by nothing
1.831     albertel 3455:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3456: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3457: # numbers
                   3458:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3459:     return $fname;
                   3460: }
1.1051    raeburn  3461: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3462: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3463: # image with the same aspect ratio as the original, but with dimensions which do 
                   3464: # not exceed $resizewidth and $resizeheight.
                   3465:  
1.984     neumanie 3466: sub resizeImage {
1.1051    raeburn  3467:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3468:     my $ima = Image::Magick->new;
                   3469:     my $resized;
                   3470:     if (-e $img_path) {
                   3471:         $ima->Read($img_path);
                   3472:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3473:             my $width = $ima->Get('width');
                   3474:             my $height = $ima->Get('height');
                   3475:             if ($width > $resizewidth) {
                   3476: 	        my $factor = $width/$resizewidth;
                   3477:                 my $newheight = $height/$factor;
                   3478:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3479:                 $resized = 1;
                   3480:             }
                   3481:         }
                   3482:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3483:             my $width = $ima->Get('width');
                   3484:             my $height = $ima->Get('height');
                   3485:             if ($height > $resizeheight) {
                   3486:                 my $factor = $height/$resizeheight;
                   3487:                 my $newwidth = $width/$factor;
                   3488:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3489:                 $resized = 1;
                   3490:             }
                   3491:         }
                   3492:         if ($resized) {
                   3493:             $ima->Write($img_path);
                   3494:         }
                   3495:     }
                   3496:     return;
1.977     amueller 3497: }
                   3498: 
1.608     albertel 3499: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3500: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3501: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3502: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3503: #                                    canceloverwrite, or ''. 
                   3504: #                   if 'coursedoc': upload to the current course
                   3505: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3506: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3507: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3508: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3509: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3510: #        $allfiles - reference to hash for embedded objects
                   3511: #        $codebase - reference to hash for codebase of java objects
                   3512: #        $desuname - username for permanent storage of uploaded file
                   3513: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3514: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3515: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3516: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3517: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3518: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3519: #                    from File::MMagic.
1.858     raeburn  3520: # 
1.686     albertel 3521: # output: url of file in userspace, or error: <message> 
                   3522: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3523: 
1.531     albertel 3524: sub userfileupload {
1.1090    raeburn  3525:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3526:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3527:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3528:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3529:     $fname=&clean_filename($fname);
1.1090    raeburn  3530:     # See if there is anything left
1.257     www      3531:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3532:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3533:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3534:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3535:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3536:         my $now = time;
1.1090    raeburn  3537:         my $filepath;
1.1095    raeburn  3538:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3539:              $filepath = 'tmp/helprequests/'.$now;
                   3540:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3541:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3542:                          '_'.$env{'user.domain'}.'/pending';
                   3543:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3544:             my ($docuname,$docudom);
                   3545:             if ($destudom) {
                   3546:                 $docudom = $destudom;
                   3547:             } else {
                   3548:                 $docudom = $env{'user.domain'};
                   3549:             }
                   3550:             if ($destuname) {
                   3551:                 $docuname = $destuname;
                   3552:             } else {
                   3553:                 $docuname = $env{'user.name'};
                   3554:             }
                   3555:             if (exists($env{'form.group'})) {
                   3556:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3557:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3558:             }
                   3559:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3560:             if ($context eq 'canceloverwrite') {
                   3561:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3562:                 if (-e  $tempfile) {
                   3563:                     my @info = stat($tempfile);
                   3564:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3565:                         unlink($tempfile);
                   3566:                     }
                   3567:                 }
                   3568:                 return;
1.523     raeburn  3569:             }
                   3570:         }
1.1090    raeburn  3571:         # Create the directory if not present
1.741     raeburn  3572:         my @parts=split(/\//,$filepath);
                   3573:         my $fullpath = $perlvar{'lonDaemons'};
                   3574:         for (my $i=0;$i<@parts;$i++) {
                   3575:             $fullpath .= '/'.$parts[$i];
                   3576:             if ((-e $fullpath)!=1) {
                   3577:                 mkdir($fullpath,0777);
                   3578:             }
                   3579:         }
                   3580:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3581:         print $fh $env{'form.'.$formname};
                   3582:         close($fh);
1.1090    raeburn  3583:         if ($context eq 'existingfile') {
                   3584:             my @info = stat($fullpath.'/'.$fname);
                   3585:             return ($fullpath.'/'.$fname,$info[9]);
                   3586:         } else {
                   3587:             return $fullpath.'/'.$fname;
                   3588:         }
1.523     raeburn  3589:     }
1.995     raeburn  3590:     if ($subdir eq 'scantron') {
                   3591:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3592:     } else {
1.995     raeburn  3593:         $fname="$subdir/$fname";
                   3594:     }
1.1090    raeburn  3595:     if ($context eq 'coursedoc') {
1.638     albertel 3596: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3597: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3598:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3599:             return &finishuserfileupload($docuname,$docudom,
                   3600: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3601: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3602:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3603:         } else {
1.1218    raeburn  3604:             if ($env{'form.folder'}) {
                   3605:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3606:             }
1.638     albertel 3607:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3608: 				       $fname,$formname,$parser,
1.1095    raeburn  3609: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3610:         }
1.719     banghart 3611:     } elsif (defined($destuname)) {
                   3612:         my $docuname=$destuname;
                   3613:         my $docudom=$destudom;
1.860     raeburn  3614: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3615: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3616:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3617:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3618:     } else {
1.638     albertel 3619:         my $docuname=$env{'user.name'};
                   3620:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3621:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3622:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3623:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3624:         }
1.860     raeburn  3625: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3626: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3627:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3628:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3629:     }
1.271     www      3630: }
                   3631: 
                   3632: sub finishuserfileupload {
1.860     raeburn  3633:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3634:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3635:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3636:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3637:   
1.860     raeburn  3638:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3639:     $file=$fname;
                   3640:     if ($fname=~m|/|) {
                   3641:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3642: 	$path.=$fnamepath.'/';
                   3643:     }
1.259     www      3644:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3645:     my $count;
                   3646:     for ($count=4;$count<=$#parts;$count++) {
                   3647:         $filepath.="/$parts[$count]";
                   3648:         if ((-e $filepath)!=1) {
                   3649: 	    mkdir($filepath,0777);
                   3650:         }
                   3651:     }
1.984     neumanie 3652: 
1.258     www      3653: # Save the file
                   3654:     {
1.701     albertel 3655: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3656: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3657: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3658: 	    return '/adm/notfound.html';
                   3659: 	}
1.1090    raeburn  3660:         if ($context eq 'overwrite') {
1.1117    foxr     3661:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3662:             my $target = $filepath.'/'.$file;
                   3663:             if (-e $source) {
                   3664:                 my @info = stat($source);
                   3665:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3666:                     unless (&File::Copy::move($source,$target)) {
                   3667:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3668:                         return "Moving from $source failed";
                   3669:                     }
                   3670:                 } else {
                   3671:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3672:                 }
                   3673:             } else {
                   3674:                 return "Temporary file: $source missing";
                   3675:             }
                   3676:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3677: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3678: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3679: 	    return '/adm/notfound.html';
                   3680: 	}
1.570     albertel 3681: 	close(FH);
1.1051    raeburn  3682:         if ($resizewidth && $resizeheight) {
                   3683:             my $mm = new File::MMagic;
                   3684:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3685:             if ($mime_type =~ m{^image/}) {
                   3686: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3687:             }  
1.977     amueller 3688: 	}
1.258     www      3689:     }
1.1152    raeburn  3690:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3691:         if (ref($mimetype)) {
                   3692:             if ($$mimetype eq '') {
                   3693:                 my $mm = new File::MMagic;
                   3694:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3695:                 $$mimetype = $type;
                   3696:             }
                   3697:         }
                   3698:     }
1.637     raeburn  3699:     if ($parser eq 'parse') {
1.1152    raeburn  3700:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3701:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3702:                                                        $allfiles,$codebase);
                   3703:             unless ($parse_result eq 'ok') {
                   3704:                 &logthis('Failed to parse '.$filepath.$file.
                   3705: 	   	         ' for embedded media: '.$parse_result); 
                   3706:             }
1.637     raeburn  3707:         }
                   3708:     }
1.860     raeburn  3709:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3710:         my $input = $filepath.'/'.$file;
                   3711:         my $output = $filepath.'/'.'tn-'.$file;
                   3712:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3713:         system("convert -sample $thumbsize $input $output");
                   3714:         if (-e $filepath.'/'.'tn-'.$file) {
                   3715:             $fetchthumb  = 1; 
                   3716:         }
                   3717:     }
1.858     raeburn  3718:  
1.259     www      3719: # Notify homeserver to grep it
                   3720: #
1.984     neumanie 3721:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3722:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3723:     if ($fetchresult eq 'ok') {
1.860     raeburn  3724:         if ($fetchthumb) {
                   3725:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3726:             if ($thumbresult ne 'ok') {
                   3727:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3728:                          $docuhome.': '.$thumbresult);
                   3729:             }
                   3730:         }
1.259     www      3731: #
1.258     www      3732: # Return the URL to it
1.494     albertel 3733:         return '/uploaded/'.$path.$file;
1.263     www      3734:     } else {
1.494     albertel 3735:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3736: 		 ': '.$fetchresult);
1.263     www      3737:         return '/adm/notfound.html';
1.858     raeburn  3738:     }
1.493     albertel 3739: }
                   3740: 
1.637     raeburn  3741: sub extract_embedded_items {
1.961     raeburn  3742:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3743:     my @state = ();
1.1164    raeburn  3744:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3745:     my %javafiles = (
                   3746:                       codebase => '',
                   3747:                       code => '',
                   3748:                       archive => ''
                   3749:                     );
                   3750:     my %mediafiles = (
                   3751:                       src => '',
                   3752:                       movie => '',
                   3753:                      );
1.648     raeburn  3754:     my $p;
                   3755:     if ($content) {
                   3756:         $p = HTML::LCParser->new($content);
                   3757:     } else {
1.961     raeburn  3758:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3759:     }
1.641     albertel 3760:     while (my $t=$p->get_token()) {
1.640     albertel 3761: 	if ($t->[0] eq 'S') {
                   3762: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3763: 	    push(@state, $tagname);
1.648     raeburn  3764:             if (lc($tagname) eq 'allow') {
                   3765:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3766:             }
1.640     albertel 3767: 	    if (lc($tagname) eq 'img') {
                   3768: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3769: 	    }
1.886     albertel 3770: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  3771:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  3772:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3773:                 }
1.886     albertel 3774: 	    }
1.645     raeburn  3775:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3776:                 my $src;
1.645     raeburn  3777:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3778:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3779:                 } else {
1.1164    raeburn  3780:                     if ($attr->{'src'} ne '') {
                   3781:                         $src = $attr->{'src'};
                   3782:                         &add_filetype($allfiles,$src,'src');
                   3783:                     }
                   3784:                 }
                   3785:                 my $text = $p->get_trimmed_text();
                   3786:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3787:                     my @swfargs = split(/,/,$1);
                   3788:                     foreach my $item (@swfargs) {
                   3789:                         $item =~ s/["']//g;
                   3790:                         $item =~ s/^\s+//;
                   3791:                         $item =~ s/\s+$//;
                   3792:                     }
                   3793:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3794:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3795:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3796:                         } else {
                   3797:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3798:                         }
                   3799:                     }
1.645     raeburn  3800:                 }
                   3801:             }
                   3802:             if (lc($tagname) eq 'link') {
                   3803:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3804:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3805:                 }
                   3806:             }
1.640     albertel 3807: 	    if (lc($tagname) eq 'object' ||
                   3808: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3809: 		foreach my $item (keys(%javafiles)) {
                   3810: 		    $javafiles{$item} = '';
                   3811: 		}
1.1164    raeburn  3812:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3813:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3814:                 }
1.640     albertel 3815: 	    }
                   3816: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3817: 		my $name = lc($attr->{'name'});
                   3818: 		foreach my $item (keys(%javafiles)) {
                   3819: 		    if ($name eq $item) {
                   3820: 			$javafiles{$item} = $attr->{'value'};
                   3821: 			last;
                   3822: 		    }
                   3823: 		}
1.1164    raeburn  3824:                 my $pathfrom;
1.640     albertel 3825: 		foreach my $item (keys(%mediafiles)) {
                   3826: 		    if ($name eq $item) {
1.1164    raeburn  3827:                         $pathfrom = $attr->{'value'};
                   3828:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3829: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3830: 			last;
                   3831: 		    }
                   3832: 		}
1.1164    raeburn  3833:                 if ($name eq 'flashvars') {
                   3834:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3835:                 }
                   3836:                 if ($pathfrom ne '') {
                   3837:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3838:                                          $pathfrom);
                   3839:                 }
1.640     albertel 3840: 	    }
                   3841: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3842: 		foreach my $item (keys(%javafiles)) {
                   3843: 		    if ($attr->{$item}) {
                   3844: 			$javafiles{$item} = $attr->{$item};
                   3845: 			last;
                   3846: 		    }
                   3847: 		}
                   3848: 		foreach my $item (keys(%mediafiles)) {
                   3849: 		    if ($attr->{$item}) {
                   3850: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3851: 			last;
                   3852: 		    }
                   3853: 		}
1.1164    raeburn  3854:                 if (lc($tagname) eq 'embed') {
                   3855:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3856:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3857:                                              $attr->{'src'});
                   3858:                     }
                   3859:                 }
1.640     albertel 3860: 	    }
1.1243    raeburn  3861:             if (lc($tagname) eq 'iframe') {
                   3862:                 my $src = $attr->{'src'} ;
                   3863:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3864:                     &add_filetype($allfiles,$src,'src');
                   3865:                 } elsif ($src =~ m{^/}) {
                   3866:                     if ($env{'request.course.id'}) {
                   3867:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3868:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3869:                         my $url = &hreflocation('',$fullpath);
                   3870:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3871:                             my $relpath = $1;
                   3872:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3873:                                 &add_filetype($allfiles,$1,'src');
                   3874:                             }
                   3875:                         }
                   3876:                     }
                   3877:                 }
                   3878:             }
1.1164    raeburn  3879:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  3880:                 pop(@state);
1.1164    raeburn  3881:             }
1.640     albertel 3882: 	} elsif ($t->[0] eq 'E') {
                   3883: 	    my ($tagname) = ($t->[1]);
                   3884: 	    if ($javafiles{'codebase'} ne '') {
                   3885: 		$javafiles{'codebase'} .= '/';
                   3886: 	    }  
                   3887: 	    if (lc($tagname) eq 'applet' ||
                   3888: 		lc($tagname) eq 'object' ||
                   3889: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3890: 		) {
                   3891: 		foreach my $item (keys(%javafiles)) {
                   3892: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3893: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3894: 			&add_filetype($allfiles,$file,$item);
                   3895: 		    }
                   3896: 		}
                   3897: 	    } 
                   3898: 	    pop @state;
                   3899: 	}
                   3900:     }
1.1164    raeburn  3901:     foreach my $id (sort(keys(%flashvars))) {
                   3902:         if ($shockwave{$id} ne '') {
                   3903:             my @pairs = split(/\&/,$flashvars{$id});
                   3904:             foreach my $pair (@pairs) {
                   3905:                 my ($key,$value) = split(/\=/,$pair);
                   3906:                 if ($key eq 'thumb') {
                   3907:                     &add_filetype($allfiles,$value,$key);
                   3908:                 } elsif ($key eq 'content') {
                   3909:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3910:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3911:                     if ($ext ne '') {
                   3912:                         &add_filetype($allfiles,$path.$value,$ext);
                   3913:                     }
                   3914:                 }
                   3915:             }
                   3916:         }
                   3917:     }
1.637     raeburn  3918:     return 'ok';
                   3919: }
                   3920: 
1.639     albertel 3921: sub add_filetype {
                   3922:     my ($allfiles,$file,$type)=@_;
                   3923:     if (exists($allfiles->{$file})) {
                   3924: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3925: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3926: 	}
                   3927:     } else {
                   3928: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3929:     }
                   3930: }
                   3931: 
1.1164    raeburn  3932: sub embedded_dependency {
                   3933:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3934:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3935:         if (($identifier ne '') &&
                   3936:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3937:             ($pathfrom ne '')) {
                   3938:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3939:             foreach my $dep (@{$related->{$identifier}}) {
                   3940:                 &add_filetype($allfiles,$path.$dep,'object');
                   3941:             }
                   3942:         }
                   3943:     }
                   3944:     return;
                   3945: }
                   3946: 
1.493     albertel 3947: sub removeuploadedurl {
1.984     neumanie 3948:     my ($url)=@_;	
                   3949:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3950:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3951: }
                   3952: 
                   3953: sub removeuserfile {
                   3954:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3955:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3956:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3957:     if ($result eq 'ok') {	
1.798     raeburn  3958:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3959:             my $metafile = $fname.'.meta';
                   3960:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3961: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3962:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3963:             my $sqlresult = 
1.823     albertel 3964:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3965:                                         'portfolio_metadata',$group,
                   3966:                                         'delete');
1.798     raeburn  3967:         }
                   3968:     }
                   3969:     return $result;
1.257     www      3970: }
1.15      www      3971: 
1.530     albertel 3972: sub mkdiruserfile {
                   3973:     my ($docuname,$docudom,$dir)=@_;
                   3974:     my $home=&homeserver($docuname,$docudom);
                   3975:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3976: }
                   3977: 
1.531     albertel 3978: sub renameuserfile {
                   3979:     my ($docuname,$docudom,$old,$new)=@_;
                   3980:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3981:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3982:                         &escape("$old").':'.&escape("$new"),$home);
                   3983:     if ($result eq 'ok') {
                   3984:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3985:             my $oldmeta = $old.'.meta';
                   3986:             my $newmeta = $new.'.meta';
                   3987:             my $metaresult = 
                   3988:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3989: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3990:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3991:             my $sqlresult = 
1.823     albertel 3992:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3993:                                         'portfolio_metadata',$group,
                   3994:                                         'delete');
1.798     raeburn  3995:         }
                   3996:     }
                   3997:     return $result;
1.531     albertel 3998: }
                   3999: 
1.14      www      4000: # ------------------------------------------------------------------------- Log
                   4001: 
                   4002: sub log {
                   4003:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4004:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4005: }
                   4006: 
                   4007: # ------------------------------------------------------------------ Course Log
1.352     www      4008: #
                   4009: # This routine flushes several buffers of non-mission-critical nature
                   4010: #
1.157     www      4011: 
                   4012: sub flushcourselogs {
1.352     www      4013:     &logthis('Flushing log buffers');
                   4014: #
                   4015: # course logs
                   4016: # This is a log of all transactions in a course, which can be used
                   4017: # for data mining purposes
                   4018: #
                   4019: # It also collects the courseid database, which lists last transaction
                   4020: # times and course titles for all courseids
                   4021: #
                   4022:     my %courseidbuffer=();
1.921     raeburn  4023:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4024:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4025: 		          &escape($courselogs{$crsid}),
                   4026: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4027: 	    delete $courselogs{$crsid};
                   4028:         } else {
                   4029:             &logthis('Failed to flush log buffer for '.$crsid);
                   4030:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4031:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4032:                         " exceeded maximum size, deleting.</font>");
                   4033:                delete $courselogs{$crsid};
                   4034:             }
1.352     www      4035:         }
1.920     raeburn  4036:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4037:             'description' => $coursedescrbuf{$crsid},
                   4038:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4039:             'type'        => $coursetypebuf{$crsid},
                   4040:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4041:         };
1.191     harris41 4042:     }
1.352     www      4043: #
                   4044: # Write course id database (reverse lookup) to homeserver of courses 
                   4045: # Is used in pickcourse
                   4046: #
1.840     albertel 4047:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4048:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4049:                                     $courseidbuffer{$crs_home},
                   4050:                                     $crs_home,'timeonly');
1.352     www      4051:     }
                   4052: #
                   4053: # File accesses
                   4054: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4055: #
1.449     matthew  4056:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4057:         if ($entry =~ /___count$/) {
                   4058:             my ($dom,$name);
1.807     albertel 4059:             ($dom,$name,undef)=
1.811     albertel 4060: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4061:             if (! defined($dom) || $dom eq '' || 
                   4062:                 ! defined($name) || $name eq '') {
1.620     albertel 4063:                 my $cid = $env{'request.course.id'};
                   4064:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4065:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4066:             }
1.450     matthew  4067:             my $value = $accesshash{$entry};
                   4068:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4069:             my %temphash=($url => $value);
1.449     matthew  4070:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4071:             if ($result eq 'ok') {
                   4072:                 delete $accesshash{$entry};
                   4073:             }
                   4074:         } else {
1.811     albertel 4075:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4076:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4077:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4078:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4079:                 delete $accesshash{$entry};
                   4080:             }
1.185     www      4081:         }
1.191     harris41 4082:     }
1.352     www      4083: #
                   4084: # Roles
                   4085: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4086: #
1.800     albertel 4087:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4088:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4089: 	    split(/\:/,$entry);
                   4090:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4091:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4092:                 $rudom,$runame) eq 'ok') {
                   4093: 	    delete $userrolehash{$entry};
                   4094:         }
                   4095:     }
1.662     raeburn  4096: #
                   4097: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   4098: #
                   4099:     my %domrolebuffer = ();
1.1000    raeburn  4100:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4101:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4102:         if ($domrolebuffer{$rudom}) {
                   4103:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4104:                       '='.&escape($domainrolehash{$entry});
                   4105:         } else {
                   4106:             $domrolebuffer{$rudom}.=&escape($entry).
                   4107:                       '='.&escape($domainrolehash{$entry});
                   4108:         }
                   4109:         delete $domainrolehash{$entry};
                   4110:     }
                   4111:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 4112: 	my %servers = &get_servers($dom,'library');
                   4113: 	foreach my $tryserver (keys(%servers)) {
                   4114: 	    unless (&reply('domroleput:'.$dom.':'.
                   4115: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4116: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4117: 	    }
1.662     raeburn  4118:         }
                   4119:     }
1.186     www      4120:     $dumpcount++;
1.157     www      4121: }
                   4122: 
                   4123: sub courselog {
                   4124:     my $what=shift;
1.158     www      4125:     $what=time.':'.$what;
1.620     albertel 4126:     unless ($env{'request.course.id'}) { return ''; }
                   4127:     $coursedombuf{$env{'request.course.id'}}=
                   4128:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4129:     $coursenumbuf{$env{'request.course.id'}}=
                   4130:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4131:     $coursehombuf{$env{'request.course.id'}}=
                   4132:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4133:     $coursedescrbuf{$env{'request.course.id'}}=
                   4134:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4135:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4136:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4137:     $courseownerbuf{$env{'request.course.id'}}=
                   4138:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4139:     $coursetypebuf{$env{'request.course.id'}}=
                   4140:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4141:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4142: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4143:     } else {
1.620     albertel 4144: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4145:     }
1.620     albertel 4146:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4147: 	&flushcourselogs();
                   4148:     }
1.158     www      4149: }
                   4150: 
                   4151: sub courseacclog {
                   4152:     my $fnsymb=shift;
1.620     albertel 4153:     unless ($env{'request.course.id'}) { return ''; }
                   4154:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4155:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4156:         $what.=':POST';
1.583     matthew  4157:         # FIXME: Probably ought to escape things....
1.800     albertel 4158: 	foreach my $key (keys(%env)) {
                   4159:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4160:                 my $formitem = $1;
                   4161:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4162:                     $what.=':'.$formitem.'='.$env{$key};
                   4163:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4164:                     $what.=':'.$formitem.'='.$env{$key};
                   4165:                 }
1.158     www      4166:             }
1.191     harris41 4167:         }
1.583     matthew  4168:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4169:         # FIXME: We should not be depending on a form parameter that someone
                   4170:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4171:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4172:             $what.= ':POST';
                   4173:             # FIXME: Probably ought to escape things....
                   4174:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4175:                                  'crsdiscuss') {
1.620     albertel 4176:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4177:             }
                   4178:         }
1.158     www      4179:     }
                   4180:     &courselog($what);
1.149     www      4181: }
                   4182: 
1.185     www      4183: sub countacc {
                   4184:     my $url=&declutter(shift);
1.458     matthew  4185:     return if (! defined($url) || $url eq '');
1.620     albertel 4186:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4187: #
                   4188: # Mark that this url was used in this course
                   4189: #
1.620     albertel 4190:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4191: #
                   4192: # Increase the access count for this resource in this child process
                   4193: #
1.281     www      4194:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4195:     $accesshash{$key}++;
1.185     www      4196: }
1.349     www      4197: 
1.361     www      4198: sub linklog {
                   4199:     my ($from,$to)=@_;
                   4200:     $from=&declutter($from);
                   4201:     $to=&declutter($to);
                   4202:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4203:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4204: }
1.1160    www      4205: 
                   4206: sub statslog {
                   4207:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4208:     if ($users<2) { return; }
                   4209:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4210:             'course'       => $env{'request.course.id'},
                   4211:             'sections'     => '"all"',
                   4212:             'num_students' => $users,
                   4213:             'part'         => $part,
                   4214:             'symb'         => $symb,
                   4215:             'mean_tries'   => $av_attempts,
                   4216:             'deg_of_diff'  => $degdiff});
                   4217:     foreach my $key (keys(%dynstore)) {
                   4218:         $accesshash{$key}=$dynstore{$key};
                   4219:     }
                   4220: }
1.361     www      4221:   
1.349     www      4222: sub userrolelog {
                   4223:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4224:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4225:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4226:        $userrolehash
                   4227:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4228:                     =$tend.':'.$tstart;
1.662     raeburn  4229:     }
1.1169    droeschl 4230:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4231:        $userrolehash
                   4232:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4233:                     =$tend.':'.$tstart;
                   4234:     }
1.1169    droeschl 4235:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  4236:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4237:        $domainrolehash
                   4238:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4239:                     = $tend.':'.$tstart;
                   4240:     }
1.351     www      4241: }
                   4242: 
1.957     raeburn  4243: sub courserolelog {
                   4244:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4245:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4246:         my $cdom = $1;
                   4247:         my $cnum = $2;
                   4248:         my $sec = $3;
                   4249:         my $namespace = 'rolelog';
                   4250:         my %storehash = (
                   4251:                            role    => $trole,
                   4252:                            start   => $tstart,
                   4253:                            end     => $tend,
                   4254:                            selfenroll => $selfenroll,
                   4255:                            context    => $context,
                   4256:                         );
                   4257:         if ($trole eq 'gr') {
                   4258:             $namespace = 'groupslog';
                   4259:             $storehash{'group'} = $sec;
                   4260:         } else {
                   4261:             $storehash{'section'} = $sec;
                   4262:         }
1.1188    raeburn  4263:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4264:                    $domain,$cnum,$cdom);
1.1184    raeburn  4265:         if (($trole ne 'st') || ($sec ne '')) {
                   4266:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4267:         }
                   4268:     }
                   4269:     return;
                   4270: }
                   4271: 
1.1184    raeburn  4272: sub domainrolelog {
                   4273:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4274:     if ($area =~ m{^/($match_domain)/$}) {
                   4275:         my $cdom = $1;
                   4276:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4277:         my $namespace = 'rolelog';
                   4278:         my %storehash = (
                   4279:                            role    => $trole,
                   4280:                            start   => $tstart,
                   4281:                            end     => $tend,
                   4282:                            context => $context,
                   4283:                         );
1.1188    raeburn  4284:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4285:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4286:     }
                   4287:     return;
                   4288: 
                   4289: }
                   4290: 
                   4291: sub coauthorrolelog {
                   4292:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4293:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4294:         my $audom = $1;
                   4295:         my $auname = $2;
                   4296:         my $namespace = 'rolelog';
                   4297:         my %storehash = (
                   4298:                            role    => $trole,
                   4299:                            start   => $tstart,
                   4300:                            end     => $tend,
                   4301:                            context => $context,
                   4302:                         );
1.1188    raeburn  4303:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4304:                    $domain,$auname,$audom);
1.1184    raeburn  4305:     }
                   4306:     return;
                   4307: }
                   4308: 
1.351     www      4309: sub get_course_adv_roles {
1.948     raeburn  4310:     my ($cid,$codes) = @_;
1.620     albertel 4311:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4312:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4313:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4314:     my %nothide=();
1.800     albertel 4315:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4316:         if ($user !~ /:/) {
                   4317: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4318:         } else {
                   4319:             $nothide{$user}=1;
                   4320:         }
1.470     www      4321:     }
1.1219    raeburn  4322:     my @possdoms = ($coursehash{'domain'});
                   4323:     if ($coursehash{'checkforpriv'}) {
                   4324:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4325:     }
1.351     www      4326:     my %returnhash=();
                   4327:     my %dumphash=
                   4328:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4329:     my $now=time;
1.997     raeburn  4330:     my %privileged;
1.1000    raeburn  4331:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4332: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4333:         if (($tstart) && ($tstart<0)) { next; }
                   4334:         if (($tend) && ($tend<$now)) { next; }
                   4335:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4336:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4337: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4338:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4339:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4340: 	if ($role eq 'cr') { next; }
1.948     raeburn  4341:         if ($codes) {
                   4342:             if ($section) { $role .= ':'.$section; }
                   4343:             if ($returnhash{$role}) {
                   4344:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4345:             } else {
                   4346:                 $returnhash{$role}=$username.':'.$domain;
                   4347:             }
1.351     www      4348:         } else {
1.988     raeburn  4349:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4350:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4351:             if ($returnhash{$key}) {
                   4352: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4353:             } else {
                   4354:                 $returnhash{$key}=$username.':'.$domain;
                   4355:             }
1.351     www      4356:         }
1.948     raeburn  4357:     }
1.400     www      4358:     return %returnhash;
                   4359: }
                   4360: 
                   4361: sub get_my_roles {
1.937     raeburn  4362:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4363:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4364:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4365:     my (%dumphash,%nothide);
1.1086    raeburn  4366:     if ($context eq 'userroles') {
1.1166    raeburn  4367:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4368:     } else {
1.1219    raeburn  4369:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4370:         if ($hidepriv) {
                   4371:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4372:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4373:                 if ($user !~ /:/) {
                   4374:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4375:                 } else {
                   4376:                     $nothide{$user} = 1;
                   4377:                 }
                   4378:             }
                   4379:         }
1.858     raeburn  4380:     }
1.400     www      4381:     my %returnhash=();
                   4382:     my $now=time;
1.999     raeburn  4383:     my %privileged;
1.800     albertel 4384:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4385:         my ($role,$tend,$tstart);
                   4386:         if ($context eq 'userroles') {
1.1149    raeburn  4387:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4388: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4389:         } else {
                   4390:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4391:         }
1.400     www      4392:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4393:         my $status = 'active';
1.939     raeburn  4394:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4395:             $status = 'previous';
                   4396:         } 
                   4397:         if (($tstart) && ($now<$tstart)) {
                   4398:             $status = 'future';
                   4399:         }
                   4400:         if (ref($types) eq 'ARRAY') {
                   4401:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4402:                 next;
                   4403:             } 
                   4404:         } else {
                   4405:             if ($status ne 'active') {
                   4406:                 next;
                   4407:             }
                   4408:         }
1.867     raeburn  4409:         my ($rolecode,$username,$domain,$section,$area);
                   4410:         if ($context eq 'userroles') {
1.1186    raeburn  4411:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4412:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4413:         } else {
                   4414:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4415:         }
1.832     raeburn  4416:         if (ref($roledoms) eq 'ARRAY') {
                   4417:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4418:                 next;
                   4419:             }
                   4420:         }
                   4421:         if (ref($roles) eq 'ARRAY') {
                   4422:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4423:                 if ($role =~ /^cr\//) {
                   4424:                     if (!grep(/^cr$/,@{$roles})) {
                   4425:                         next;
                   4426:                     }
1.1104    raeburn  4427:                 } elsif ($role =~ /^gr\//) {
                   4428:                     if (!grep(/^gr$/,@{$roles})) {
                   4429:                         next;
                   4430:                     }
1.922     raeburn  4431:                 } else {
                   4432:                     next;
                   4433:                 }
1.832     raeburn  4434:             }
1.867     raeburn  4435:         }
1.937     raeburn  4436:         if ($hidepriv) {
1.1219    raeburn  4437:             my @privroles = ('dc','su');
1.999     raeburn  4438:             if ($context eq 'userroles') {
1.1219    raeburn  4439:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4440:             } else {
1.1219    raeburn  4441:                 my $possdoms = [$domain];
                   4442:                 if (ref($roledoms) eq 'ARRAY') {
                   4443:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4444:                 }
1.1219    raeburn  4445:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4446:                     if (!$nothide{$username.':'.$domain}) {
                   4447:                         next;
                   4448:                     }
                   4449:                 }
1.937     raeburn  4450:             }
                   4451:         }
1.933     raeburn  4452:         if ($withsec) {
                   4453:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4454:                 $tstart.':'.$tend;
                   4455:         } else {
                   4456:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4457:         }
1.832     raeburn  4458:     }
1.373     www      4459:     return %returnhash;
1.399     www      4460: }
                   4461: 
                   4462: # ----------------------------------------------------- Frontpage Announcements
                   4463: #
                   4464: #
                   4465: 
                   4466: sub postannounce {
                   4467:     my ($server,$text)=@_;
1.844     albertel 4468:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4469:     unless ($text=~/\w/) { $text=''; }
                   4470:     return &reply('setannounce:'.&escape($text),$server);
                   4471: }
                   4472: 
                   4473: sub getannounce {
1.448     albertel 4474: 
                   4475:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4476: 	my $announcement='';
1.800     albertel 4477: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4478: 	close($fh);
1.399     www      4479: 	if ($announcement=~/\w/) { 
                   4480: 	    return 
                   4481:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4482:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4483: 	} else {
                   4484: 	    return '';
                   4485: 	}
                   4486:     } else {
                   4487: 	return '';
                   4488:     }
1.351     www      4489: }
1.353     www      4490: 
                   4491: # ---------------------------------------------------------- Course ID routines
                   4492: # Deal with domain's nohist_courseid.db files
                   4493: #
                   4494: 
                   4495: sub courseidput {
1.921     raeburn  4496:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4497:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4498:     my $outcome;
                   4499:     if ($caller eq 'timeonly') {
                   4500:         my $cids = '';
                   4501:         foreach my $item (keys(%$storehash)) {
                   4502:             $cids.=&escape($item).'&';
                   4503:         }
                   4504:         $cids=~s/\&$//;
                   4505:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4506:                           $coursehome);       
                   4507:     } else {
                   4508:         my $items = '';
                   4509:         foreach my $item (keys(%$storehash)) {
                   4510:             $items.= &escape($item).'='.
                   4511:                      &freeze_escape($$storehash{$item}).'&';
                   4512:         }
                   4513:         $items=~s/\&$//;
                   4514:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4515:                           $coursehome);
1.918     raeburn  4516:     }
                   4517:     if ($outcome eq 'unknown_cmd') {
                   4518:         my $what;
                   4519:         foreach my $cid (keys(%$storehash)) {
                   4520:             $what .= &escape($cid).'=';
1.921     raeburn  4521:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4522:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4523:             }
                   4524:             $what =~ s/\:$/&/;
                   4525:         }
                   4526:         $what =~ s/\&$//;  
                   4527:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4528:     } else {
                   4529:         return $outcome;
                   4530:     }
1.353     www      4531: }
                   4532: 
                   4533: sub courseiddump {
1.921     raeburn  4534:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4535:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4536:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  4537:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  4538:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4539:     my $as_hash = 1;
                   4540:     my %returnhash;
                   4541:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4542:     my %libserv = &all_library();
                   4543:     foreach my $tryserver (keys(%libserv)) {
                   4544:         if ( (  $hostidflag == 1 
                   4545: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4546: 	     || (!defined($hostidflag)) ) {
                   4547: 
1.918     raeburn  4548: 	    if (($domfilter eq '') ||
                   4549: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4550:                 my $rep;
                   4551:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4552:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4553:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   4554:                                 &escape($descfilter), &escape($instcodefilter), 
                   4555:                                 &escape($ownerfilter), &escape($coursefilter),
                   4556:                                 &escape($typefilter), &escape($regexp_ok), 
                   4557:                                 $as_hash, &escape($selfenrollonly), 
                   4558:                                 &escape($catfilter), $showhidden, $caller, 
                   4559:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   4560:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  4561:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   4562:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 4563:                 } else {
                   4564:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4565:                              $sincefilter.':'.&escape($descfilter).':'.
                   4566:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4567:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4568:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4569:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4570:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4571:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4572:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  4573:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   4574:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 4575:                 }
                   4576:                      
1.918     raeburn  4577:                 my @pairs=split(/\&/,$rep);
                   4578:                 foreach my $item (@pairs) {
                   4579:                     my ($key,$value)=split(/\=/,$item,2);
                   4580:                     $key = &unescape($key);
                   4581:                     next if ($key =~ /^error: 2 /);
                   4582:                     my $result = &thaw_unescape($value);
                   4583:                     if (ref($result) eq 'HASH') {
                   4584:                         $returnhash{$key}=$result;
                   4585:                     } else {
1.921     raeburn  4586:                         my @responses = split(/:/,$value);
                   4587:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4588:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4589:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4590:                         }
1.1008    raeburn  4591:                     }
1.353     www      4592:                 }
                   4593:             }
                   4594:         }
                   4595:     }
                   4596:     return %returnhash;
                   4597: }
                   4598: 
1.1055    raeburn  4599: sub courselastaccess {
                   4600:     my ($cdom,$cnum,$hostidref) = @_;
                   4601:     my %returnhash;
                   4602:     if ($cdom && $cnum) {
                   4603:         my $chome = &homeserver($cnum,$cdom);
                   4604:         if ($chome ne 'no_host') {
                   4605:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4606:             &extract_lastaccess(\%returnhash,$rep);
                   4607:         }
                   4608:     } else {
                   4609:         if (!$cdom) { $cdom=''; }
                   4610:         my %libserv = &all_library();
                   4611:         foreach my $tryserver (keys(%libserv)) {
                   4612:             if (ref($hostidref) eq 'ARRAY') {
                   4613:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4614:             } 
                   4615:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4616:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4617:                 &extract_lastaccess(\%returnhash,$rep);
                   4618:             }
                   4619:         }
                   4620:     }
                   4621:     return %returnhash;
                   4622: }
                   4623: 
                   4624: sub extract_lastaccess {
                   4625:     my ($returnhash,$rep) = @_;
                   4626:     if (ref($returnhash) eq 'HASH') {
                   4627:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4628:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4629:                  $rep eq '') {
                   4630:             my @pairs=split(/\&/,$rep);
                   4631:             foreach my $item (@pairs) {
                   4632:                 my ($key,$value)=split(/\=/,$item,2);
                   4633:                 $key = &unescape($key);
                   4634:                 next if ($key =~ /^error: 2 /);
                   4635:                 $returnhash->{$key} = &thaw_unescape($value);
                   4636:             }
                   4637:         }
                   4638:     }
                   4639:     return;
                   4640: }
                   4641: 
1.658     raeburn  4642: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4643: 
                   4644: sub dcmailput {
1.685     raeburn  4645:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4646:     my $status = &Apache::lonnet::critical(
1.740     www      4647:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4648:        &escape($message),$server);
1.662     raeburn  4649:     return $status;
                   4650: }
                   4651: 
1.658     raeburn  4652: sub dcmaildump {
                   4653:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4654:     my %returnhash=();
1.846     albertel 4655: 
                   4656:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4657:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4658:                                                          &escape($enddate).':';
                   4659: 	my @esc_senders=map { &escape($_)} @$senders;
                   4660: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4661: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4662:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4663:             if (($key) && ($value)) {
                   4664:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4665:             }
                   4666:         }
                   4667:     }
                   4668:     return %returnhash;
                   4669: }
1.662     raeburn  4670: # ---------------------------------------------------------- Domain roles
                   4671: 
                   4672: sub get_domain_roles {
                   4673:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4674:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4675:         $startdate = '.';
                   4676:     }
1.1018    raeburn  4677:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4678:         $enddate = '.';
                   4679:     }
1.922     raeburn  4680:     my $rolelist;
                   4681:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  4682:         $rolelist = join('&',@{$roles});
1.922     raeburn  4683:     }
1.662     raeburn  4684:     my %personnel = ();
1.841     albertel 4685: 
                   4686:     my %servers = &get_servers($dom,'library');
                   4687:     foreach my $tryserver (keys(%servers)) {
                   4688: 	%{$personnel{$tryserver}}=();
                   4689: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4690: 					    &escape($startdate).':'.
                   4691: 					    &escape($enddate).':'.
                   4692: 					    &escape($rolelist), $tryserver))) {
                   4693: 	    my ($key,$value) = split(/\=/,$line,2);
                   4694: 	    if (($key) && ($value)) {
                   4695: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4696: 	    }
                   4697: 	}
1.662     raeburn  4698:     }
                   4699:     return %personnel;
                   4700: }
1.658     raeburn  4701: 
1.1057    www      4702: # ----------------------------------------------------------- Interval timing 
1.149     www      4703: 
1.1153    www      4704: {
                   4705: # Caches needed for speedup of navmaps
                   4706: # We don't want to cache this for very long at all (5 seconds at most)
                   4707: # 
                   4708: # The user for whom we cache
                   4709: my $cachedkey='';
                   4710: # The cached times for this user
                   4711: my %cachedtimes=();
                   4712: # When this was last done
1.1282    raeburn  4713: my $cachedtime='';
1.1153    www      4714: 
                   4715: sub load_all_first_access {
1.1308    raeburn  4716:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      4717:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  4718:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   4719:         (!$ignorecache)) {
1.1154    raeburn  4720:         return;
                   4721:     }
                   4722:     $cachedtime=time;
                   4723:     $cachedkey=$uname.':'.$udom;
                   4724:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4725: }
                   4726: 
1.504     albertel 4727: sub get_first_access {
1.1308    raeburn  4728:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 4729:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4730:     if ($argsymb) { $symb=$argsymb; }
                   4731:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4732:     if ($argmap) { $map = $argmap; }
1.926     albertel 4733:     if ($type eq 'course') {
                   4734: 	$res='course';
                   4735:     } elsif ($type eq 'map') {
1.588     albertel 4736: 	$res=&symbread($map);
                   4737:     } else {
                   4738: 	$res=$symb;
                   4739:     }
1.1308    raeburn  4740:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      4741:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4742: }
                   4743: 
                   4744: sub set_first_access {
1.1162    raeburn  4745:     my ($type,$interval)=@_;
1.790     albertel 4746:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4747:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4748:     if ($type eq 'course') {
                   4749: 	$res='course';
                   4750:     } elsif ($type eq 'map') {
1.588     albertel 4751: 	$res=&symbread($map);
                   4752:     } else {
                   4753: 	$res=$symb;
                   4754:     }
1.1153    www      4755:     $cachedkey='';
1.1162    raeburn  4756:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4757:     if (!$firstaccess) {
1.1162    raeburn  4758:         my $start = time;
                   4759: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4760:                           $udom,$uname);
                   4761:         if ($putres eq 'ok') {
                   4762:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4763:                  $udom,$uname); 
                   4764:             &appenv(
                   4765:                      {
                   4766:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4767:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4768:                      }
                   4769:                   );
                   4770:         }
                   4771:         return $putres;
1.505     albertel 4772:     }
                   4773:     return 'already_set';
1.504     albertel 4774: }
1.1153    www      4775: }
1.1282    raeburn  4776: 
1.110     www      4777: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4778: 
                   4779: sub expirespread {
                   4780:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4781:     my $cid=$env{'request.course.id'}; 
1.110     www      4782:     if ($cid) {
                   4783:        my $now=time;
                   4784:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4785:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4786:                             $env{'course.'.$cid.'.num'}.
1.110     www      4787: 	        	    ':nohist_expirationdates:'.
                   4788:                             &escape($key).'='.$now,
1.620     albertel 4789:                             $env{'course.'.$cid.'.home'})
1.110     www      4790:     }
                   4791:     return 'ok';
1.14      www      4792: }
                   4793: 
1.109     www      4794: # ----------------------------------------------------- Devalidate Spreadsheets
                   4795: 
                   4796: sub devalidate {
1.325     www      4797:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4798:     my $cid=$env{'request.course.id'}; 
1.109     www      4799:     if ($cid) {
1.391     matthew  4800:         # delete the stored spreadsheets for
                   4801:         # - the student level sheet of this user in course's homespace
                   4802:         # - the assessment level sheet for this resource 
                   4803:         #   for this user in user's homespace
1.553     albertel 4804: 	# - current conditional state info
1.325     www      4805: 	my $key=$uname.':'.$udom.':';
1.109     www      4806:         my $status=
1.299     matthew  4807: 	    &del('nohist_calculatedsheets',
1.391     matthew  4808: 		 [$key.'studentcalc:'],
1.620     albertel 4809: 		 $env{'course.'.$cid.'.domain'},
                   4810: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4811: 		.' '.
                   4812: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4813: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4814:         unless ($status eq 'ok ok') {
                   4815:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4816:                     $uname.' at '.$udom.' for '.
1.109     www      4817: 		    $symb.': '.$status);
1.133     albertel 4818:         }
1.553     albertel 4819: 	&delenv('user.state.'.$cid);
1.109     www      4820:     }
                   4821: }
                   4822: 
1.265     albertel 4823: sub get_scalar {
                   4824:     my ($string,$end) = @_;
                   4825:     my $value;
                   4826:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4827: 	$value = $1;
                   4828:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4829: 	$value = $1;
                   4830:     }
                   4831:     return &unescape($value);
                   4832: }
                   4833: 
                   4834: sub array2str {
                   4835:   my (@array) = @_;
                   4836:   my $result=&arrayref2str(\@array);
                   4837:   $result=~s/^__ARRAY_REF__//;
                   4838:   $result=~s/__END_ARRAY_REF__$//;
                   4839:   return $result;
                   4840: }
                   4841: 
1.204     albertel 4842: sub arrayref2str {
                   4843:   my ($arrayref) = @_;
1.265     albertel 4844:   my $result='__ARRAY_REF__';
1.204     albertel 4845:   foreach my $elem (@$arrayref) {
1.265     albertel 4846:     if(ref($elem) eq 'ARRAY') {
                   4847:       $result.=&arrayref2str($elem).'&';
                   4848:     } elsif(ref($elem) eq 'HASH') {
                   4849:       $result.=&hashref2str($elem).'&';
                   4850:     } elsif(ref($elem)) {
                   4851:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4852:     } else {
                   4853:       $result.=&escape($elem).'&';
                   4854:     }
                   4855:   }
                   4856:   $result=~s/\&$//;
1.265     albertel 4857:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4858:   return $result;
                   4859: }
                   4860: 
1.168     albertel 4861: sub hash2str {
1.204     albertel 4862:   my (%hash) = @_;
                   4863:   my $result=&hashref2str(\%hash);
1.265     albertel 4864:   $result=~s/^__HASH_REF__//;
                   4865:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4866:   return $result;
                   4867: }
                   4868: 
                   4869: sub hashref2str {
                   4870:   my ($hashref)=@_;
1.265     albertel 4871:   my $result='__HASH_REF__';
1.800     albertel 4872:   foreach my $key (sort(keys(%$hashref))) {
                   4873:     if (ref($key) eq 'ARRAY') {
                   4874:       $result.=&arrayref2str($key).'=';
                   4875:     } elsif (ref($key) eq 'HASH') {
                   4876:       $result.=&hashref2str($key).'=';
                   4877:     } elsif (ref($key)) {
1.265     albertel 4878:       $result.='=';
1.800     albertel 4879:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4880:     } else {
1.1132    raeburn  4881: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4882:     }
                   4883: 
1.800     albertel 4884:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4885:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4886:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4887:       $result.=&hashref2str($hashref->{$key}).'&';
                   4888:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4889:        $result.='&';
1.800     albertel 4890:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4891:     } else {
1.800     albertel 4892:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4893:     }
                   4894:   }
1.168     albertel 4895:   $result=~s/\&$//;
1.265     albertel 4896:   $result .= '__END_HASH_REF__';
1.168     albertel 4897:   return $result;
                   4898: }
                   4899: 
                   4900: sub str2hash {
1.265     albertel 4901:     my ($string)=@_;
                   4902:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4903:     return %$hash;
                   4904: }
                   4905: 
                   4906: sub str2hashref {
1.168     albertel 4907:   my ($string) = @_;
1.265     albertel 4908: 
                   4909:   my %hash;
                   4910: 
                   4911:   if($string !~ /^__HASH_REF__/) {
                   4912:       if (! ($string eq '' || !defined($string))) {
                   4913: 	  $hash{'error'}='Not hash reference';
                   4914:       }
                   4915:       return (\%hash, $string);
                   4916:   }
                   4917: 
                   4918:   $string =~ s/^__HASH_REF__//;
                   4919: 
                   4920:   while($string !~ /^__END_HASH_REF__/) {
                   4921:       #key
                   4922:       my $key='';
                   4923:       if($string =~ /^__HASH_REF__/) {
                   4924:           ($key, $string)=&str2hashref($string);
                   4925:           if(defined($key->{'error'})) {
                   4926:               $hash{'error'}='Bad data';
                   4927:               return (\%hash, $string);
                   4928:           }
                   4929:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4930:           ($key, $string)=&str2arrayref($string);
                   4931:           if($key->[0] eq 'Array reference error') {
                   4932:               $hash{'error'}='Bad data';
                   4933:               return (\%hash, $string);
                   4934:           }
                   4935:       } else {
                   4936:           $string =~ s/^(.*?)=//;
1.267     albertel 4937: 	  $key=&unescape($1);
1.265     albertel 4938:       }
                   4939:       $string =~ s/^=//;
                   4940: 
                   4941:       #value
                   4942:       my $value='';
                   4943:       if($string =~ /^__HASH_REF__/) {
                   4944:           ($value, $string)=&str2hashref($string);
                   4945:           if(defined($value->{'error'})) {
                   4946:               $hash{'error'}='Bad data';
                   4947:               return (\%hash, $string);
                   4948:           }
                   4949:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4950:           ($value, $string)=&str2arrayref($string);
                   4951:           if($value->[0] eq 'Array reference error') {
                   4952:               $hash{'error'}='Bad data';
                   4953:               return (\%hash, $string);
                   4954:           }
                   4955:       } else {
                   4956: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4957:       }
                   4958:       $string =~ s/^&//;
                   4959: 
                   4960:       $hash{$key}=$value;
1.204     albertel 4961:   }
1.265     albertel 4962: 
                   4963:   $string =~ s/^__END_HASH_REF__//;
                   4964: 
                   4965:   return (\%hash, $string);
1.204     albertel 4966: }
                   4967: 
                   4968: sub str2array {
1.265     albertel 4969:     my ($string)=@_;
                   4970:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4971:     return @$array;
                   4972: }
                   4973: 
                   4974: sub str2arrayref {
1.204     albertel 4975:   my ($string) = @_;
1.265     albertel 4976:   my @array;
                   4977: 
                   4978:   if($string !~ /^__ARRAY_REF__/) {
                   4979:       if (! ($string eq '' || !defined($string))) {
                   4980: 	  $array[0]='Array reference error';
                   4981:       }
                   4982:       return (\@array, $string);
                   4983:   }
                   4984: 
                   4985:   $string =~ s/^__ARRAY_REF__//;
                   4986: 
                   4987:   while($string !~ /^__END_ARRAY_REF__/) {
                   4988:       my $value='';
                   4989:       if($string =~ /^__HASH_REF__/) {
                   4990:           ($value, $string)=&str2hashref($string);
                   4991:           if(defined($value->{'error'})) {
                   4992:               $array[0] ='Array reference error';
                   4993:               return (\@array, $string);
                   4994:           }
                   4995:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4996:           ($value, $string)=&str2arrayref($string);
                   4997:           if($value->[0] eq 'Array reference error') {
                   4998:               $array[0] ='Array reference error';
                   4999:               return (\@array, $string);
                   5000:           }
                   5001:       } else {
                   5002: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5003:       }
                   5004:       $string =~ s/^&//;
                   5005: 
                   5006:       push(@array, $value);
1.191     harris41 5007:   }
1.265     albertel 5008: 
                   5009:   $string =~ s/^__END_ARRAY_REF__//;
                   5010: 
                   5011:   return (\@array, $string);
1.168     albertel 5012: }
                   5013: 
1.167     albertel 5014: # -------------------------------------------------------------------Temp Store
                   5015: 
1.168     albertel 5016: sub tmpreset {
                   5017:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5018:   if (!$symb) {
                   5019:     $symb=&symbread();
1.620     albertel 5020:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5021:   }
                   5022:   $symb=escape($symb);
                   5023: 
1.620     albertel 5024:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5025:   $namespace=~s/\//\_/g;
                   5026:   $namespace=~s/\W//g;
                   5027: 
1.620     albertel 5028:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5029:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5030:   if ($domain eq 'public' && $stuname eq 'public') {
                   5031:       $stuname=$ENV{'REMOTE_ADDR'};
                   5032:   }
1.1117    foxr     5033:   my $path=LONCAPA::tempdir();
1.168     albertel 5034:   my %hash;
                   5035:   if (tie(%hash,'GDBM_File',
                   5036: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5037: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5038:     foreach my $key (keys(%hash)) {
1.180     albertel 5039:       if ($key=~ /:$symb/) {
1.168     albertel 5040: 	delete($hash{$key});
                   5041:       }
                   5042:     }
                   5043:   }
                   5044: }
                   5045: 
1.167     albertel 5046: sub tmpstore {
1.168     albertel 5047:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5048: 
                   5049:   if (!$symb) {
                   5050:     $symb=&symbread();
1.620     albertel 5051:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5052:   }
                   5053:   $symb=escape($symb);
                   5054: 
                   5055:   if (!$namespace) {
                   5056:     # I don't think we would ever want to store this for a course.
                   5057:     # it seems this will only be used if we don't have a course.
1.620     albertel 5058:     #$namespace=$env{'request.course.id'};
1.168     albertel 5059:     #if (!$namespace) {
1.620     albertel 5060:       $namespace=$env{'request.state'};
1.168     albertel 5061:     #}
                   5062:   }
                   5063:   $namespace=~s/\//\_/g;
                   5064:   $namespace=~s/\W//g;
1.620     albertel 5065:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5066:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5067:   if ($domain eq 'public' && $stuname eq 'public') {
                   5068:       $stuname=$ENV{'REMOTE_ADDR'};
                   5069:   }
1.168     albertel 5070:   my $now=time;
                   5071:   my %hash;
1.1117    foxr     5072:   my $path=LONCAPA::tempdir();
1.168     albertel 5073:   if (tie(%hash,'GDBM_File',
                   5074: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5075: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5076:     $hash{"version:$symb"}++;
                   5077:     my $version=$hash{"version:$symb"};
                   5078:     my $allkeys=''; 
                   5079:     foreach my $key (keys(%$storehash)) {
                   5080:       $allkeys.=$key.':';
1.591     albertel 5081:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5082:     }
                   5083:     $hash{"$version:$symb:timestamp"}=$now;
                   5084:     $allkeys.='timestamp';
                   5085:     $hash{"$version:keys:$symb"}=$allkeys;
                   5086:     if (untie(%hash)) {
                   5087:       return 'ok';
                   5088:     } else {
                   5089:       return "error:$!";
                   5090:     }
                   5091:   } else {
                   5092:     return "error:$!";
                   5093:   }
                   5094: }
1.167     albertel 5095: 
1.168     albertel 5096: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5097: 
1.168     albertel 5098: sub tmprestore {
                   5099:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5100: 
1.168     albertel 5101:   if (!$symb) {
                   5102:     $symb=&symbread();
1.620     albertel 5103:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5104:   }
                   5105:   $symb=escape($symb);
                   5106: 
1.620     albertel 5107:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5108: 
1.620     albertel 5109:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5110:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5111:   if ($domain eq 'public' && $stuname eq 'public') {
                   5112:       $stuname=$ENV{'REMOTE_ADDR'};
                   5113:   }
1.168     albertel 5114:   my %returnhash;
                   5115:   $namespace=~s/\//\_/g;
                   5116:   $namespace=~s/\W//g;
                   5117:   my %hash;
1.1117    foxr     5118:   my $path=LONCAPA::tempdir();
1.168     albertel 5119:   if (tie(%hash,'GDBM_File',
                   5120: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5121: 	  &GDBM_READER(),0640)) {
1.168     albertel 5122:     my $version=$hash{"version:$symb"};
                   5123:     $returnhash{'version'}=$version;
                   5124:     my $scope;
                   5125:     for ($scope=1;$scope<=$version;$scope++) {
                   5126:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5127:       my @keys=split(/:/,$vkeys);
                   5128:       my $key;
                   5129:       $returnhash{"$scope:keys"}=$vkeys;
                   5130:       foreach $key (@keys) {
1.591     albertel 5131: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5132: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5133:       }
                   5134:     }
1.168     albertel 5135:     if (!(untie(%hash))) {
                   5136:       return "error:$!";
                   5137:     }
                   5138:   } else {
                   5139:     return "error:$!";
                   5140:   }
                   5141:   return %returnhash;
1.167     albertel 5142: }
                   5143: 
1.9       www      5144: # ----------------------------------------------------------------------- Store
                   5145: 
                   5146: sub store {
1.1269    raeburn  5147:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5148:     my $home='';
                   5149: 
1.168     albertel 5150:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5151: 
1.213     www      5152:     $symb=&symbclean($symb);
1.122     albertel 5153:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5154: 
1.620     albertel 5155:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5156:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5157: 
                   5158:     &devalidate($symb,$stuname,$domain);
1.109     www      5159: 
                   5160:     $symb=escape($symb);
1.187     www      5161:     if (!$namespace) { 
1.620     albertel 5162:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5163:           return ''; 
                   5164:        } 
                   5165:     }
1.620     albertel 5166:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5167: 
                   5168:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5169:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5170: 
1.12      www      5171:     my $namevalue='';
1.800     albertel 5172:     foreach my $key (keys(%$storehash)) {
                   5173:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5174:     }
1.12      www      5175:     $namevalue=~s/\&$//;
1.187     www      5176:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  5177:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5178: }
                   5179: 
1.47      www      5180: # -------------------------------------------------------------- Critical Store
                   5181: 
                   5182: sub cstore {
1.1269    raeburn  5183:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5184:     my $home='';
                   5185: 
1.168     albertel 5186:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5187: 
1.213     www      5188:     $symb=&symbclean($symb);
1.122     albertel 5189:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5190: 
1.620     albertel 5191:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5192:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5193: 
                   5194:     &devalidate($symb,$stuname,$domain);
1.109     www      5195: 
                   5196:     $symb=escape($symb);
1.187     www      5197:     if (!$namespace) { 
1.620     albertel 5198:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5199:           return ''; 
                   5200:        } 
                   5201:     }
1.620     albertel 5202:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5203: 
                   5204:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5205:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5206: 
1.47      www      5207:     my $namevalue='';
1.800     albertel 5208:     foreach my $key (keys(%$storehash)) {
                   5209:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5210:     }
1.47      www      5211:     $namevalue=~s/\&$//;
1.187     www      5212:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5213:     return critical
1.1269    raeburn  5214:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5215: }
                   5216: 
1.9       www      5217: # --------------------------------------------------------------------- Restore
                   5218: 
                   5219: sub restore {
1.124     www      5220:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5221:     my $home='';
                   5222: 
1.168     albertel 5223:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5224: 
1.122     albertel 5225:     if (!$symb) {
1.1224    raeburn  5226:         return if ($namespace eq 'courserequests');
                   5227:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5228:     } else {
1.1224    raeburn  5229:         unless ($namespace eq 'courserequests') {
                   5230:             $symb=&escape(&symbclean($symb));
                   5231:         }
1.122     albertel 5232:     }
1.188     www      5233:     if (!$namespace) { 
1.620     albertel 5234:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5235:           return ''; 
                   5236:        } 
                   5237:     }
1.620     albertel 5238:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5239:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5240:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5241:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5242: 
1.12      www      5243:     my %returnhash=();
1.800     albertel 5244:     foreach my $line (split(/\&/,$answer)) {
                   5245: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5246:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5247:     }
1.75      www      5248:     my $version;
                   5249:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5250:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5251:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5252:        }
1.75      www      5253:     }
1.13      www      5254:     return %returnhash;
1.34      www      5255: }
                   5256: 
                   5257: # ---------------------------------------------------------- Course Description
1.1118    foxr     5258: #
                   5259: #  
1.34      www      5260: 
                   5261: sub coursedescription {
1.731     albertel 5262:     my ($courseid,$args)=@_;
1.34      www      5263:     $courseid=~s/^\///;
1.49      www      5264:     $courseid=~s/\_/\//g;
1.34      www      5265:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5266:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5267:     my $normalid=$cdomain.'_'.$cnum;
                   5268:     # need to always cache even if we get errors otherwise we keep 
                   5269:     # trying and trying and trying to get the course description.
                   5270:     my %envhash=();
                   5271:     my %returnhash=();
1.731     albertel 5272:     
                   5273:     my $expiretime=600;
                   5274:     if ($env{'request.course.id'} eq $normalid) {
                   5275: 	$expiretime=120;
                   5276:     }
                   5277: 
                   5278:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5279:     if (!$args->{'freshen_cache'}
                   5280: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5281: 	foreach my $key (keys(%env)) {
                   5282: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5283: 	    my ($setting) = $1;
                   5284: 	    $returnhash{$setting} = $env{$key};
                   5285: 	}
                   5286: 	return %returnhash;
                   5287:     }
                   5288: 
1.1118    foxr     5289:     # get the data again
                   5290: 
1.731     albertel 5291:     if (!$args->{'one_time'}) {
                   5292: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5293:     }
1.811     albertel 5294: 
1.34      www      5295:     if ($chome ne 'no_host') {
1.302     albertel 5296:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5297:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5298: 	   my $username = $env{'user.name'}; # Defult username
                   5299: 	   if(defined $args->{'user'}) {
                   5300: 	       $username = $args->{'user'};
                   5301: 	   }
1.129     albertel 5302:            $returnhash{'home'}= $chome;
                   5303: 	   $returnhash{'domain'} = $cdomain;
                   5304: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5305:            if (!defined($returnhash{'type'})) {
                   5306:                $returnhash{'type'} = 'Course';
                   5307:            }
1.130     albertel 5308:            while (my ($name,$value) = each %returnhash) {
1.53      www      5309:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5310:            }
1.270     www      5311:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5312:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5313: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5314:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5315:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5316:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5317:        }
                   5318:     }
1.731     albertel 5319:     if (!$args->{'one_time'}) {
1.949     raeburn  5320: 	&appenv(\%envhash);
1.731     albertel 5321:     }
1.302     albertel 5322:     return %returnhash;
1.461     www      5323: }
                   5324: 
1.1080    raeburn  5325: sub update_released_required {
                   5326:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5327:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5328:         $cid = $env{'request.course.id'};
                   5329:         $cdom = $env{'course.'.$cid.'.domain'};
                   5330:         $cnum = $env{'course.'.$cid.'.num'};
                   5331:         $chome = $env{'course.'.$cid.'.home'};
                   5332:     }
                   5333:     if ($needsrelease) {
                   5334:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5335:         my $needsupdate;
                   5336:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5337:             $needsupdate = 1;
                   5338:         } else {
                   5339:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5340:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5341:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5342:                 $needsupdate = 1;
                   5343:             }
                   5344:         }
                   5345:         if ($needsupdate) {
                   5346:             my %needshash = (
                   5347:                              'internal.releaserequired' => $needsrelease,
                   5348:                             );
                   5349:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5350:             if ($putresult eq 'ok') {
                   5351:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5352:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5353:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5354:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5355:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5356:                 }
                   5357:             }
                   5358:         }
                   5359:     }
                   5360:     return;
                   5361: }
                   5362: 
1.461     www      5363: # -------------------------------------------------See if a user is privileged
                   5364: 
                   5365: sub privileged {
1.1219    raeburn  5366:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5367:     my $now = time;
1.1219    raeburn  5368:     my $roles;
                   5369:     if (ref($possroles) eq 'ARRAY') {
                   5370:         $roles = $possroles; 
                   5371:     } else {
                   5372:         $roles = ['dc','su'];
                   5373:     }
                   5374:     if (ref($possdomains) eq 'ARRAY') {
                   5375:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5376:         foreach my $dom (@{$possdomains}) {
                   5377:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5378:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5379:                 foreach my $role (@{$roles}) {
                   5380:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5381:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5382:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5383:                             return 1 unless (($end && $end < $now) ||
                   5384:                                              ($start && $start > $now));
                   5385:                         }
                   5386:                     }
                   5387:                 }
                   5388:             }
                   5389:         }
                   5390:     } else {
                   5391:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5392:         my $now = time;
1.1170    droeschl 5393: 
1.1275    musolffc 5394:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5395:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5396:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5397:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5398:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5399:             }
1.1219    raeburn  5400:         }
                   5401:     }
                   5402:     return 0;
                   5403: }
1.1170    droeschl 5404: 
1.1219    raeburn  5405: sub privileged_by_domain {
                   5406:     my ($domains,$roles) = @_;
                   5407:     my %privileged = ();
                   5408:     my $cachetime = 60*60*24;
                   5409:     my $now = time;
                   5410:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5411:         return %privileged;
                   5412:     }
                   5413:     foreach my $dom (@{$domains}) {
                   5414:         next if (ref($privileged{$dom}) eq 'HASH');
                   5415:         my $needroles;
                   5416:         foreach my $role (@{$roles}) {
                   5417:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5418:             if (defined($cached)) {
                   5419:                 if (ref($result) eq 'HASH') {
                   5420:                     $privileged{$dom}{$role} = $result;
                   5421:                 }
                   5422:             } else {
                   5423:                 $needroles = 1;
                   5424:             }
                   5425:         }
                   5426:         if ($needroles) {
                   5427:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5428:             $privileged{$dom} = {};
                   5429:             foreach my $server (keys(%dompersonnel)) {
                   5430:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5431:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5432:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5433:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5434:                         next if ($end && $end < $now);
                   5435:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5436:                             $dompersonnel{$server}{$item};
                   5437:                     }
                   5438:                 }
                   5439:             }
                   5440:             if (ref($privileged{$dom}) eq 'HASH') {
                   5441:                 foreach my $role (@{$roles}) {
                   5442:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5443:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5444:                     } else {
                   5445:                         my %hash = ();
                   5446:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5447:                     }
                   5448:                 }
                   5449:             }
                   5450:         }
                   5451:     }
                   5452:     return %privileged;
1.9       www      5453: }
1.1       albertel 5454: 
1.103     harris41 5455: # -------------------------------------------------------- Get user privileges
1.11      www      5456: 
                   5457: sub rolesinit {
1.1169    droeschl 5458:     my ($domain, $username) = @_;
                   5459:     my %userroles = ('user.login.time' => time);
                   5460:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5461: 
                   5462:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5463:     # also, blocking can be triggered by an activating timer
                   5464:     # it's saved in the user's %env.
                   5465:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5466:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5467:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5468:         %timerintchk, %timerintenv);
                   5469: 
1.1162    raeburn  5470:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5471:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5472:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5473:     }
1.1169    droeschl 5474: 
1.1162    raeburn  5475:     foreach my $key (keys(%timerinterval)) {
                   5476:         my ($cid,$rest) = split(/\0/,$key);
                   5477:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5478:     }
1.1169    droeschl 5479: 
1.11      www      5480:     my %allroles=();
1.1162    raeburn  5481:     my %allgroups=();
1.11      www      5482: 
1.1274    raeburn  5483:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5484:         my $role = $rolesdump{$area};
                   5485:         $area =~ s/\_\w\w$//;
                   5486: 
                   5487:         my ($trole, $tend, $tstart, $group_privs);
                   5488: 
                   5489:         if ($role =~ /^cr/) {
                   5490:         # Custom role, defined by a user 
                   5491:         # e.g., user.role.cr/msu/smith/mynewrole
                   5492:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5493:                 $trole = $1;
                   5494:                 ($tend, $tstart) = split('_', $2);
                   5495:             } else {
                   5496:                 $trole = $role;
                   5497:             }
                   5498:         } elsif ($role =~ m|^gr/|) {
                   5499:         # Role of member in a group, defined within a course/community
                   5500:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5501:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5502:             next if $tstart eq '-1';
                   5503:             ($trole, $group_privs) = split(/\//, $trole);
                   5504:             $group_privs = &unescape($group_privs);
                   5505:         } else {
                   5506:         # Just a normal role, defined in roles.tab
                   5507:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5508:         }
                   5509: 
                   5510:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5511:                  $username);
                   5512:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5513: 
                   5514:         # role expired or not available yet?
                   5515:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5516:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5517: 
                   5518:         next if $area eq '' or $trole eq '';
                   5519: 
                   5520:         my $spec = "$trole.$area";
                   5521:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5522: 
                   5523:         if ($trole =~ /^cr\//) {
                   5524:         # Custom role, defined by a user
                   5525:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5526:         } elsif ($trole eq 'gr') {
                   5527:         # Role of a member in a group, defined within a course/community
                   5528:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5529:             next;
                   5530:         } else {
                   5531:         # Normal role, defined in roles.tab
                   5532:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5533:         }
                   5534: 
                   5535:         my $cid = $tdomain.'_'.$trest;
                   5536:         unless ($firstaccchk{$cid}) {
                   5537:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5538:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5539:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5540:                         $coursetimerstarts{$cid}{$item}; 
                   5541:                 }
                   5542:             }
                   5543:             $firstaccchk{$cid} = 1;
                   5544:         }
                   5545:         unless ($timerintchk{$cid}) {
                   5546:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5547:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5548:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5549:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5550:                 }
1.12      www      5551:             }
1.1169    droeschl 5552:             $timerintchk{$cid} = 1;
1.191     harris41 5553:         }
1.11      www      5554:     }
1.1169    droeschl 5555: 
                   5556:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5557:         \%allroles, \%allgroups);
                   5558:     $env{'user.adv'} = $userroles{'user.adv'};
                   5559: 
1.1162    raeburn  5560:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5561: }
                   5562: 
1.567     raeburn  5563: sub set_arearole {
1.1215    raeburn  5564:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5565:     unless ($nolog) {
1.567     raeburn  5566: # log the associated role with the area
1.1215    raeburn  5567:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5568:     }
1.743     albertel 5569:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5570: }
                   5571: 
                   5572: sub custom_roleprivs {
                   5573:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5574:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  5575:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5576:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5577:         my ($rdummy,$roledef)=
                   5578:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5579:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5580:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5581:             if (defined($syspriv)) {
1.1043    raeburn  5582:                 if ($trest =~ /^$match_community$/) {
                   5583:                     $syspriv =~ s/bre\&S//; 
                   5584:                 }
1.567     raeburn  5585:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5586:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5587:             }
                   5588:             if ($tdomain ne '') {
                   5589:                 if (defined($dompriv)) {
                   5590:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5591:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5592:                 }
                   5593:                 if (($trest ne '') && (defined($coursepriv))) {
                   5594:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5595:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5596:                 }
                   5597:             }
                   5598:         }
                   5599:     }
                   5600: }
                   5601: 
1.678     raeburn  5602: sub group_roleprivs {
                   5603:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5604:     my $access = 1;
                   5605:     my $now = time;
                   5606:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5607:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5608:     if ($access) {
1.811     albertel 5609:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5610:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5611:     }
                   5612: }
1.567     raeburn  5613: 
                   5614: sub standard_roleprivs {
                   5615:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5616:     if (defined($pr{$trole.':s'})) {
                   5617:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5618:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5619:     }
                   5620:     if ($tdomain ne '') {
                   5621:         if (defined($pr{$trole.':d'})) {
                   5622:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5623:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5624:         }
                   5625:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5626:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5627:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5628:         }
                   5629:     }
                   5630: }
                   5631: 
                   5632: sub set_userprivs {
1.1064    raeburn  5633:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5634:     my $author=0;
                   5635:     my $adv=0;
1.678     raeburn  5636:     my %grouproles = ();
                   5637:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5638:         my @groupkeys; 
1.1000    raeburn  5639:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5640:             push(@groupkeys,$role);
                   5641:         }
                   5642:         if (ref($groups_roles) eq 'HASH') {
                   5643:             foreach my $key (keys(%{$groups_roles})) {
                   5644:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5645:                     push(@groupkeys,$key);
                   5646:                 }
                   5647:             }
                   5648:         }
                   5649:         if (@groupkeys > 0) {
                   5650:             foreach my $role (@groupkeys) {
                   5651:                 my ($trole,$area,$sec,$extendedarea);
                   5652:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5653:                     $trole = $1;
                   5654:                     $area = $2;
                   5655:                     $sec = $3;
                   5656:                     $extendedarea = $area.$sec;
                   5657:                     if (exists($$allgroups{$area})) {
                   5658:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5659:                             my $spec = $trole.'.'.$extendedarea;
                   5660:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5661:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5662:                         }
1.678     raeburn  5663:                     }
                   5664:                 }
                   5665:             }
                   5666:         }
                   5667:     }
1.800     albertel 5668:     foreach my $group (keys(%grouproles)) {
                   5669:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5670:     }
1.800     albertel 5671:     foreach my $role (keys(%{$allroles})) {
                   5672:         my %thesepriv;
1.941     raeburn  5673:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5674:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5675:             if ($item ne '') {
                   5676:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5677:                 if ($restrictions eq '') {
                   5678:                     $thesepriv{$privilege}='F';
                   5679:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5680:                     $thesepriv{$privilege}.=$restrictions;
                   5681:                 }
                   5682:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5683:             }
                   5684:         }
                   5685:         my $thesestr='';
1.1104    raeburn  5686:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5687: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5688: 	}
                   5689:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5690:     }
                   5691:     return ($author,$adv);
                   5692: }
                   5693: 
1.994     raeburn  5694: sub role_status {
1.1104    raeburn  5695:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5696:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  5697:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5698:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5699:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  5700:             $$where = '/'.$two;
1.994     raeburn  5701:             $$trolecode=$$role.'.'.$$where;
                   5702:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5703:             $$tstatus='is';
1.1104    raeburn  5704:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5705:                 $$tstatus='future';
1.1034    raeburn  5706:                 if ($$tstart<$now) {
                   5707:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5708:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5709:                             my (%allroles,%allgroups,$group_privs,
                   5710:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5711:                             my %userroles = (
                   5712:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5713:                             );
1.1064    raeburn  5714:                             @rolecodes = ('cm'); 
1.1002    raeburn  5715:                             my $spec=$$role.'.'.$$where;
                   5716:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5717:                             if ($$role =~ /^cr\//) {
                   5718:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5719:                                 push(@rolecodes,'cr');
1.1002    raeburn  5720:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5721:                                 push(@rolecodes,$$role);
1.1002    raeburn  5722:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5723:                                                     $env{'user.name'});
1.1064    raeburn  5724:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5725:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5726:                                 $group_privs = &unescape($group_privs);
                   5727:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5728:                                 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  5729:                                 &get_groups_roles($tdomain,$trest,
                   5730:                                                   \%course_roles,\@rolecodes,
                   5731:                                                   \%groups_roles);
1.1002    raeburn  5732:                             } else {
1.1064    raeburn  5733:                                 push(@rolecodes,$$role);
1.1002    raeburn  5734:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5735:                             }
1.1064    raeburn  5736:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5737:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5738:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5739:                         }
                   5740:                     }
1.1034    raeburn  5741:                     $$tstatus = 'is';
1.1002    raeburn  5742:                 }
1.994     raeburn  5743:             }
                   5744:             if ($$tend) {
1.1104    raeburn  5745:                 if ($$tend<$update) {
1.994     raeburn  5746:                     $$tstatus='expired';
                   5747:                 } elsif ($$tend<$now) {
                   5748:                     $$tstatus='will_not';
                   5749:                 }
                   5750:             }
                   5751:         }
                   5752:     }
                   5753: }
                   5754: 
1.1104    raeburn  5755: sub get_groups_roles {
                   5756:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5757:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5758:                   (ref($rolecodes) eq 'ARRAY') && 
                   5759:                   (ref($groups_roles) eq 'HASH')); 
                   5760:     if (keys(%{$cdom_courseroles}) > 0) {
                   5761:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5762:         if ($cdom ne '' && $cnum ne '') {
                   5763:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5764:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5765:                     my $crsrole = $1;
                   5766:                     my $crssec = $2;
                   5767:                     if ($crsrole =~ /^cr/) {
                   5768:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5769:                             push(@{$rolecodes},'cr');
                   5770:                         }
                   5771:                     } else {
                   5772:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5773:                             push(@{$rolecodes},$crsrole);
                   5774:                         }
                   5775:                     }
                   5776:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5777:                     if ($crssec ne '') {
                   5778:                         $rolekey .= "/$crssec";
                   5779:                     }
                   5780:                     $rolekey .= './';
                   5781:                     $groups_roles->{$rolekey} = $rolecodes;
                   5782:                 }
                   5783:             }
                   5784:         }
                   5785:     }
                   5786:     return;
                   5787: }
                   5788: 
                   5789: sub delete_env_groupprivs {
                   5790:     my ($where,$courseroles,$possroles) = @_;
                   5791:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5792:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5793:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5794:         %{$courseroles->{$udom}} =
                   5795:             &get_my_roles('','','userroles',['active'],
                   5796:                           $possroles,[$udom],1);
                   5797:     }
                   5798:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5799:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5800:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5801:             my $area = '/'.$cdom.'/'.$cnum;
                   5802:             my $privkey = "user.priv.$crsrole.$area";
                   5803:             if ($crssec ne '') {
                   5804:                 $privkey .= '/'.$crssec;
                   5805:             }
                   5806:             $privkey .= ".$area/$group";
                   5807:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5808:         }
                   5809:     }
                   5810:     return;
                   5811: }
                   5812: 
1.994     raeburn  5813: sub check_adhoc_privs {
1.1104    raeburn  5814:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5815:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185    raeburn  5816:     my $setprivs;
1.994     raeburn  5817:     if ($env{$cckey}) {
                   5818:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5819:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5820:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5821:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5822:             $setprivs = 1;
1.994     raeburn  5823:         }
                   5824:     } else {
1.1088    raeburn  5825:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5826:         $setprivs = 1;
1.994     raeburn  5827:     }
1.1185    raeburn  5828:     return $setprivs;
1.994     raeburn  5829: }
                   5830: 
                   5831: sub set_adhoc_privileges {
                   5832: # role can be cc or ca
1.1088    raeburn  5833:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5834:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5835:     my $spec = $role.'.'.$area;
                   5836:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  5837:                                   $env{'user.name'},1);
1.994     raeburn  5838:     my %ccrole = ();
                   5839:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5840:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5841:     &appenv(\%userroles,[$role,'cm']);
                   5842:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5843:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5844:         &appenv( {'request.role'        => $spec,
                   5845:                   'request.role.domain' => $dcdom,
                   5846:                   'request.course.sec'  => ''
                   5847:                  }
                   5848:                );
                   5849:         my $tadv=0;
                   5850:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5851:         &appenv({'request.role.adv'    => $tadv});
                   5852:     }
1.994     raeburn  5853: }
                   5854: 
1.12      www      5855: # --------------------------------------------------------------- get interface
                   5856: 
                   5857: sub get {
1.131     albertel 5858:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5859:    my $items='';
1.800     albertel 5860:    foreach my $item (@$storearr) {
                   5861:        $items.=&escape($item).'&';
1.191     harris41 5862:    }
1.12      www      5863:    $items=~s/\&$//;
1.620     albertel 5864:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5865:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5866:    my $uhome=&homeserver($uname,$udomain);
                   5867: 
1.133     albertel 5868:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5869:    my @pairs=split(/\&/,$rep);
1.273     albertel 5870:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5871:      return @pairs;
                   5872:    }
1.15      www      5873:    my %returnhash=();
1.42      www      5874:    my $i=0;
1.800     albertel 5875:    foreach my $item (@$storearr) {
                   5876:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5877:       $i++;
1.191     harris41 5878:    }
1.15      www      5879:    return %returnhash;
1.27      www      5880: }
                   5881: 
                   5882: # --------------------------------------------------------------- del interface
                   5883: 
                   5884: sub del {
1.133     albertel 5885:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5886:    my $items='';
1.800     albertel 5887:    foreach my $item (@$storearr) {
                   5888:        $items.=&escape($item).'&';
1.191     harris41 5889:    }
1.984     neumanie 5890: 
1.27      www      5891:    $items=~s/\&$//;
1.620     albertel 5892:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5893:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5894:    my $uhome=&homeserver($uname,$udomain);
                   5895:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5896: }
                   5897: 
                   5898: # -------------------------------------------------------------- dump interface
                   5899: 
1.1180    droeschl 5900: sub unserialize {
                   5901:     my ($rep, $escapedkeys) = @_;
                   5902: 
                   5903:     return {} if $rep =~ /^error/;
                   5904: 
                   5905:     my %returnhash=();
1.1252    raeburn  5906: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 5907: 	    my ($key, $value) = split(/=/, $item, 2);
                   5908: 	    $key = unescape($key) unless $escapedkeys;
                   5909: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  5910: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 5911: 	}
                   5912:     #return %returnhash;
                   5913:     return \%returnhash;
                   5914: }        
                   5915: 
                   5916: # see Lond::dump_with_regexp
                   5917: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5918: sub dump {
1.1180    droeschl 5919:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5920:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5921:     if (!$uname) { $uname=$env{'user.name'}; }
                   5922:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5923: 
1.1266    raeburn  5924:     if ($regexp) {
                   5925:         $regexp=&escape($regexp);
                   5926:     } else {
                   5927:         $regexp='.';
                   5928:     }
1.1180    droeschl 5929:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   5930:         # user is hosted on this machine
1.1266    raeburn  5931:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  5932:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 5933:         return %{unserialize($reply, $escapedkeys)};
                   5934:     }
1.1166    raeburn  5935:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5936:     my @pairs=split(/\&/,$rep);
                   5937:     my %returnhash=();
1.1098    foxr     5938:     if (!($rep =~ /^error/ )) {
                   5939: 	foreach my $item (@pairs) {
                   5940: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 5941:         $key = unescape($key) unless $escapedkeys;
                   5942:         #$key = &unescape($key);
1.1098    foxr     5943: 	    next if ($key =~ /^error: 2 /);
                   5944: 	    $returnhash{$key}=&thaw_unescape($value);
                   5945: 	}
1.755     albertel 5946:     }
                   5947:     return %returnhash;
1.407     www      5948: }
                   5949: 
1.1098    foxr     5950: 
1.717     albertel 5951: # --------------------------------------------------------- dumpstore interface
                   5952: 
                   5953: sub dumpstore {
                   5954:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 5955:    # same as dump but keys must be escaped. They may contain colon separated
                   5956:    # lists of values that may themself contain colons (e.g. symbs).
                   5957:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5958: }
                   5959: 
1.407     www      5960: # -------------------------------------------------------------- keys interface
                   5961: 
                   5962: sub getkeys {
                   5963:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5964:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5965:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5966:    my $uhome=&homeserver($uname,$udomain);
                   5967:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5968:    my @keyarray=();
1.800     albertel 5969:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5970:       next if ($key =~ /^error: 2 /);
1.800     albertel 5971:       push(@keyarray,&unescape($key));
1.407     www      5972:    }
                   5973:    return @keyarray;
1.318     matthew  5974: }
                   5975: 
1.319     matthew  5976: # --------------------------------------------------------------- currentdump
                   5977: sub currentdump {
1.328     matthew  5978:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5979:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5980:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5981:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5982:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 5983:    my $rep;
                   5984: 
                   5985:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5986:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   5987:                    $courseid)));
                   5988:    } else {
                   5989:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5990:    }
                   5991: 
1.318     matthew  5992:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5993:    #
1.318     matthew  5994:    my %returnhash=();
1.319     matthew  5995:    #
                   5996:    if ($rep eq "unknown_cmd") { 
                   5997:        # an old lond will not know currentdump
                   5998:        # Do a dump and make it look like a currentdump
1.822     albertel 5999:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6000:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6001:        my %hash = @tmp;
                   6002:        @tmp=();
1.424     matthew  6003:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6004:    } else {
                   6005:        my @pairs=split(/\&/,$rep);
1.800     albertel 6006:        foreach my $pair (@pairs) {
                   6007:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6008:            my ($symb,$param) = split(/:/,$key);
                   6009:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6010:                                                         &thaw_unescape($value);
1.319     matthew  6011:        }
1.191     harris41 6012:    }
1.12      www      6013:    return %returnhash;
1.424     matthew  6014: }
                   6015: 
                   6016: sub convert_dump_to_currentdump{
                   6017:     my %hash = %{shift()};
                   6018:     my %returnhash;
                   6019:     # Code ripped from lond, essentially.  The only difference
                   6020:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6021:     # we might run in to problems with parameter names =~ /^v\./
                   6022:     while (my ($key,$value) = each(%hash)) {
                   6023:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6024: 	$symb  = &unescape($symb);
                   6025: 	$param = &unescape($param);
1.424     matthew  6026:         next if ($v eq 'version' || $symb eq 'keys');
                   6027:         next if (exists($returnhash{$symb}) &&
                   6028:                  exists($returnhash{$symb}->{$param}) &&
                   6029:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6030:         $returnhash{$symb}->{$param}=$value;
                   6031:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6032:     }
                   6033:     #
                   6034:     # Remove all of the keys in the hashes which keep track of
                   6035:     # the version of the parameter.
                   6036:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6037:         # use a foreach because we are going to delete from the hash.
                   6038:         foreach my $key (keys(%$param_hash)) {
                   6039:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6040:         }
                   6041:     }
                   6042:     return \%returnhash;
1.12      www      6043: }
                   6044: 
1.627     albertel 6045: # ------------------------------------------------------ critical inc interface
                   6046: 
                   6047: sub cinc {
                   6048:     return &inc(@_,'critical');
                   6049: }
                   6050: 
1.449     matthew  6051: # --------------------------------------------------------------- inc interface
                   6052: 
                   6053: sub inc {
1.627     albertel 6054:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6055:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6056:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6057:     my $uhome=&homeserver($uname,$udomain);
                   6058:     my $items='';
                   6059:     if (! ref($store)) {
                   6060:         # got a single value, so use that instead
                   6061:         $items = &escape($store).'=&';
                   6062:     } elsif (ref($store) eq 'SCALAR') {
                   6063:         $items = &escape($$store).'=&';        
                   6064:     } elsif (ref($store) eq 'ARRAY') {
                   6065:         $items = join('=&',map {&escape($_);} @{$store});
                   6066:     } elsif (ref($store) eq 'HASH') {
                   6067:         while (my($key,$value) = each(%{$store})) {
                   6068:             $items.= &escape($key).'='.&escape($value).'&';
                   6069:         }
                   6070:     }
                   6071:     $items=~s/\&$//;
1.627     albertel 6072:     if ($critical) {
                   6073: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6074:     } else {
                   6075: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6076:     }
1.449     matthew  6077: }
                   6078: 
1.12      www      6079: # --------------------------------------------------------------- put interface
                   6080: 
                   6081: sub put {
1.134     albertel 6082:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6083:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6084:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6085:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6086:    my $items='';
1.800     albertel 6087:    foreach my $item (keys(%$storehash)) {
                   6088:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6089:    }
1.12      www      6090:    $items=~s/\&$//;
1.134     albertel 6091:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6092: }
                   6093: 
1.631     albertel 6094: # ------------------------------------------------------------ newput interface
                   6095: 
                   6096: sub newput {
                   6097:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6098:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6099:    if (!$uname) { $uname=$env{'user.name'}; }
                   6100:    my $uhome=&homeserver($uname,$udomain);
                   6101:    my $items='';
                   6102:    foreach my $key (keys(%$storehash)) {
                   6103:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6104:    }
                   6105:    $items=~s/\&$//;
                   6106:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6107: }
                   6108: 
                   6109: # ---------------------------------------------------------  putstore interface
                   6110: 
1.524     raeburn  6111: sub putstore {
1.1269    raeburn  6112:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6113:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6114:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6115:    my $uhome=&homeserver($uname,$udomain);
                   6116:    my $items='';
1.715     albertel 6117:    foreach my $key (keys(%$storehash)) {
                   6118:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6119:    }
1.715     albertel 6120:    $items=~s/\&$//;
1.716     albertel 6121:    my $esc_symb=&escape($symb);
                   6122:    my $esc_v=&escape($version);
1.715     albertel 6123:    my $reply =
1.716     albertel 6124:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6125: 	      $uhome);
1.1269    raeburn  6126:    if (($tolog) && ($reply eq 'ok')) {
                   6127:        my $namevalue='';
                   6128:        foreach my $key (keys(%{$storehash})) {
                   6129:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6130:        }
                   6131:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6132:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6133:                      '&version='.$esc_v.
                   6134:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6135:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6136:    }
1.715     albertel 6137:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6138:        # gfall back to way things use to be done
1.715     albertel 6139:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6140: 			    $uname);
1.524     raeburn  6141:    }
1.715     albertel 6142:    return $reply;
                   6143: }
                   6144: 
                   6145: sub old_putstore {
1.716     albertel 6146:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6147:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6148:     if (!$uname) { $uname=$env{'user.name'}; }
                   6149:     my $uhome=&homeserver($uname,$udomain);
                   6150:     my %newstorehash;
1.800     albertel 6151:     foreach my $item (keys(%$storehash)) {
                   6152: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6153: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6154:     }
                   6155:     my $items='';
                   6156:     my %allitems = ();
1.800     albertel 6157:     foreach my $item (keys(%newstorehash)) {
                   6158: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6159: 	    my $key = $1.':keys:'.$2;
                   6160: 	    $allitems{$key} .= $3.':';
                   6161: 	}
1.800     albertel 6162: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6163:     }
1.800     albertel 6164:     foreach my $item (keys(%allitems)) {
                   6165: 	$allitems{$item} =~ s/\:$//;
                   6166: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6167:     }
                   6168:     $items=~s/\&$//;
                   6169:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6170: }
                   6171: 
1.47      www      6172: # ------------------------------------------------------ critical put interface
                   6173: 
                   6174: sub cput {
1.134     albertel 6175:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6176:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6177:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6178:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6179:    my $items='';
1.800     albertel 6180:    foreach my $item (keys(%$storehash)) {
                   6181:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6182:    }
1.47      www      6183:    $items=~s/\&$//;
1.134     albertel 6184:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6185: }
                   6186: 
                   6187: # -------------------------------------------------------------- eget interface
                   6188: 
                   6189: sub eget {
1.133     albertel 6190:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6191:    my $items='';
1.800     albertel 6192:    foreach my $item (@$storearr) {
                   6193:        $items.=&escape($item).'&';
1.191     harris41 6194:    }
1.12      www      6195:    $items=~s/\&$//;
1.620     albertel 6196:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6197:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6198:    my $uhome=&homeserver($uname,$udomain);
                   6199:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6200:    my @pairs=split(/\&/,$rep);
                   6201:    my %returnhash=();
1.42      www      6202:    my $i=0;
1.800     albertel 6203:    foreach my $item (@$storearr) {
                   6204:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6205:       $i++;
1.191     harris41 6206:    }
1.12      www      6207:    return %returnhash;
                   6208: }
                   6209: 
1.667     albertel 6210: # ------------------------------------------------------------ tmpput interface
                   6211: sub tmpput {
1.802     raeburn  6212:     my ($storehash,$server,$context)=@_;
1.667     albertel 6213:     my $items='';
1.800     albertel 6214:     foreach my $item (keys(%$storehash)) {
                   6215: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6216:     }
                   6217:     $items=~s/\&$//;
1.802     raeburn  6218:     if (defined($context)) {
                   6219:         $items .= ':'.&escape($context);
                   6220:     }
1.667     albertel 6221:     return &reply("tmpput:$items",$server);
                   6222: }
                   6223: 
                   6224: # ------------------------------------------------------------ tmpget interface
                   6225: sub tmpget {
1.688     albertel 6226:     my ($token,$server)=@_;
                   6227:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6228:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6229:     my %returnhash;
                   6230:     foreach my $item (split(/\&/,$rep)) {
                   6231: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  6232:         next if ($key =~ /^error: 2 /);
1.667     albertel 6233: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6234:     }
                   6235:     return %returnhash;
                   6236: }
                   6237: 
1.1113    raeburn  6238: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6239: sub tmpdel {
                   6240:     my ($token,$server)=@_;
                   6241:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6242:     return &reply("tmpdel:$token",$server);
                   6243: }
                   6244: 
1.1198    raeburn  6245: # ------------------------------------------------------------ get_timebased_id 
                   6246: 
                   6247: sub get_timebased_id {
                   6248:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6249:         $maxtries) = @_;
                   6250:     my ($newid,$error,$dellock);
                   6251:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   6252:         return ('','ok','invalid call to get suffix');
                   6253:     }
                   6254: 
                   6255: # set defaults for any optional args for which values were not supplied
                   6256:     if ($who eq '') {
                   6257:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6258:     }
                   6259:     if (!$locktries) {
                   6260:         $locktries = 3;
                   6261:     }
                   6262:     if (!$maxtries) {
                   6263:         $maxtries = 10;
                   6264:     }
                   6265:     
                   6266:     if (($cdom eq '') || ($cnum eq '')) {
                   6267:         if ($env{'request.course.id'}) {
                   6268:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6269:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6270:         }
                   6271:         if (($cdom eq '') || ($cnum eq '')) {
                   6272:             return ('','ok','call to get suffix not in course context');
                   6273:         }
                   6274:     }
                   6275: 
                   6276: # construct locking item
                   6277:     my $lockhash = {
                   6278:                       $prefix."\0".'locked_'.$keyid => $who,
                   6279:                    };
                   6280:     my $tries = 0;
                   6281: 
                   6282: # attempt to get lock on nohist_$namespace file
                   6283:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6284:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6285:         $tries ++;
                   6286:         sleep 1;
                   6287:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6288:     }
                   6289: 
                   6290: # attempt to get unique identifier, based on current timestamp
                   6291:     if ($gotlock eq 'ok') {
                   6292:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6293:         my $id = time;
                   6294:         $newid = $id;
1.1268    raeburn  6295:         if ($idtype eq 'addcode') {
                   6296:             $newid .= &sixnum_code();
                   6297:         }
1.1198    raeburn  6298:         my $idtries = 0;
                   6299:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6300:             if ($idtype eq 'concat') {
                   6301:                 $newid = $id.$idtries;
1.1268    raeburn  6302:             } elsif ($idtype eq 'addcode') {
                   6303:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6304:             } else {
                   6305:                 $newid ++;
                   6306:             }
                   6307:             $idtries ++;
                   6308:         }
                   6309:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6310:             my %new_item =  (
                   6311:                               $prefix."\0".$newid => $who,
                   6312:                             );
                   6313:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6314:                                                  $cdom,$cnum);
                   6315:             if ($putresult ne 'ok') {
                   6316:                 undef($newid);
                   6317:                 $error = 'error saving new item: '.$putresult;
                   6318:             }
                   6319:         } else {
1.1268    raeburn  6320:              undef($newid);
1.1198    raeburn  6321:              $error = ('error: no unique suffix available for the new item ');
                   6322:         }
                   6323: #  remove lock
                   6324:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6325:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6326:     } else {
                   6327:         $error = "error: could not obtain lockfile\n";
                   6328:         $dellock = 'ok';
1.1276    raeburn  6329:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6330:             $dellock = 'nolock';
                   6331:         }
1.1198    raeburn  6332:     }
                   6333:     return ($newid,$dellock,$error);
                   6334: }
                   6335: 
1.1268    raeburn  6336: sub sixnum_code {
                   6337:     my $code;
                   6338:     for (0..6) {
                   6339:         $code .= int( rand(9) );
                   6340:     }
                   6341:     return $code;
                   6342: }
                   6343: 
1.765     albertel 6344: # -------------------------------------------------- portfolio access checking
                   6345: 
                   6346: sub portfolio_access {
1.1270    raeburn  6347:     my ($requrl,$clientip) = @_;
1.765     albertel 6348:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  6349:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6350:     if ($result) {
                   6351:         my %setters;
                   6352:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6353:             my ($startblock,$endblock) =
                   6354:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6355:             if ($startblock && $endblock) {
                   6356:                 return 'B';
                   6357:             }
                   6358:         } else {
                   6359:             my ($startblock,$endblock) =
                   6360:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6361:             if ($startblock && $endblock) {
                   6362:                 return 'B';
                   6363:             }
                   6364:         }
                   6365:     }
1.765     albertel 6366:     if ($result eq 'ok') {
1.766     albertel 6367:        return 'F';
1.765     albertel 6368:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6369:        return 'A';
1.765     albertel 6370:     }
1.766     albertel 6371:     return '';
1.765     albertel 6372: }
                   6373: 
                   6374: sub get_portfolio_access {
1.1270    raeburn  6375:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6376: 
                   6377:     if (!ref($access_hash)) {
                   6378: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6379: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6380: 						   $file_name);
                   6381: 	$access_hash = $access_controls{$file_name};
                   6382:     }
                   6383: 
1.1270    raeburn  6384:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6385:     my $now = time;
                   6386:     if (ref($access_hash) eq 'HASH') {
                   6387:         foreach my $key (keys(%{$access_hash})) {
                   6388:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6389:             if ($start > $now) {
                   6390:                 next;
                   6391:             }
                   6392:             if ($end && $end<$now) {
                   6393:                 next;
                   6394:             }
                   6395:             if ($scope eq 'public') {
                   6396:                 $public = $key;
                   6397:                 last;
                   6398:             } elsif ($scope eq 'guest') {
                   6399:                 $guest = $key;
                   6400:             } elsif ($scope eq 'domains') {
                   6401:                 push(@domains,$key);
                   6402:             } elsif ($scope eq 'users') {
                   6403:                 push(@users,$key);
                   6404:             } elsif ($scope eq 'course') {
                   6405:                 push(@courses,$key);
                   6406:             } elsif ($scope eq 'group') {
                   6407:                 push(@groups,$key);
1.1270    raeburn  6408:             } elsif ($scope eq 'ip') {
                   6409:                 push(@ips,$key);
1.765     albertel 6410:             }
                   6411:         }
                   6412:         if ($public) {
                   6413:             return 'ok';
1.1270    raeburn  6414:         } elsif (@ips > 0) {
                   6415:             my $allowed;
                   6416:             foreach my $ipkey (@ips) {
                   6417:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6418:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6419:                         $allowed = 1;
                   6420:                         last; 
                   6421:                     }
                   6422:                 }
                   6423:             }
                   6424:             if ($allowed) {
                   6425:                 return 'ok';
                   6426:             }
1.765     albertel 6427:         }
                   6428:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6429:             if ($guest) {
                   6430:                 return $guest;
                   6431:             }
                   6432:         } else {
                   6433:             if (@domains > 0) {
                   6434:                 foreach my $domkey (@domains) {
                   6435:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6436:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6437:                             return 'ok';
                   6438:                         }
                   6439:                     }
                   6440:                 }
                   6441:             }
                   6442:             if (@users > 0) {
                   6443:                 foreach my $userkey (@users) {
1.865     raeburn  6444:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6445:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6446:                             if (ref($item) eq 'HASH') {
                   6447:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6448:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6449:                                     return 'ok';
                   6450:                                 }
                   6451:                             }
                   6452:                         }
                   6453:                     } 
1.765     albertel 6454:                 }
                   6455:             }
                   6456:             my %roleshash;
                   6457:             my @courses_and_groups = @courses;
                   6458:             push(@courses_and_groups,@groups); 
                   6459:             if (@courses_and_groups > 0) {
                   6460:                 my (%allgroups,%allroles); 
                   6461:                 my ($start,$end,$role,$sec,$group);
                   6462:                 foreach my $envkey (%env) {
1.1060    raeburn  6463:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6464:                         my $cid = $2.'_'.$3; 
                   6465:                         if ($1 eq 'gr') {
                   6466:                             $group = $4;
                   6467:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6468:                         } else {
                   6469:                             if ($4 eq '') {
                   6470:                                 $sec = 'none';
                   6471:                             } else {
                   6472:                                 $sec = $4;
                   6473:                             }
                   6474:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6475:                         }
1.811     albertel 6476:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6477:                         my $cid = $2.'_'.$3;
                   6478:                         if ($4 eq '') {
                   6479:                             $sec = 'none';
                   6480:                         } else {
                   6481:                             $sec = $4;
                   6482:                         }
                   6483:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6484:                     }
                   6485:                 }
                   6486:                 if (keys(%allroles) == 0) {
                   6487:                     return;
                   6488:                 }
                   6489:                 foreach my $key (@courses_and_groups) {
                   6490:                     my %content = %{$$access_hash{$key}};
                   6491:                     my $cnum = $content{'number'};
                   6492:                     my $cdom = $content{'domain'};
                   6493:                     my $cid = $cdom.'_'.$cnum;
                   6494:                     if (!exists($allroles{$cid})) {
                   6495:                         next;
                   6496:                     }    
                   6497:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6498:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6499:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6500:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6501:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6502:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6503:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6504:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6505:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6506:                                         if (grep/^all$/,@sections) {
                   6507:                                             return 'ok';
                   6508:                                         } else {
                   6509:                                             if (grep/^$sec$/,@sections) {
                   6510:                                                 return 'ok';
                   6511:                                             }
                   6512:                                         }
                   6513:                                     }
                   6514:                                 }
                   6515:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6516:                                     if (grep/^none$/,@groups) {
                   6517:                                         return 'ok';
                   6518:                                     }
                   6519:                                 } else {
                   6520:                                     if (grep/^all$/,@groups) {
                   6521:                                         return 'ok';
                   6522:                                     } 
                   6523:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6524:                                         if (grep/^$group$/,@groups) {
                   6525:                                             return 'ok';
                   6526:                                         }
                   6527:                                     }
                   6528:                                 } 
                   6529:                             }
                   6530:                         }
                   6531:                     }
                   6532:                 }
                   6533:             }
                   6534:             if ($guest) {
                   6535:                 return $guest;
                   6536:             }
                   6537:         }
                   6538:     }
                   6539:     return;
                   6540: }
                   6541: 
                   6542: sub course_group_datechecker {
                   6543:     my ($dates,$now,$status) = @_;
                   6544:     my ($start,$end) = split(/\./,$dates);
                   6545:     if (!$start && !$end) {
                   6546:         return 'ok';
                   6547:     }
                   6548:     if (grep/^active$/,@{$status}) {
                   6549:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6550:             return 'ok';
                   6551:         }
                   6552:     }
                   6553:     if (grep/^previous$/,@{$status}) {
                   6554:         if ($end > $now ) {
                   6555:             return 'ok';
                   6556:         }
                   6557:     }
                   6558:     if (grep/^future$/,@{$status}) {
                   6559:         if ($start > $now) {
                   6560:             return 'ok';
                   6561:         }
                   6562:     }
                   6563:     return; 
                   6564: }
                   6565: 
                   6566: sub parse_portfolio_url {
                   6567:     my ($url) = @_;
                   6568: 
                   6569:     my ($type,$udom,$unum,$group,$file_name);
                   6570:     
1.823     albertel 6571:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6572: 	$type = 1;
                   6573:         $udom = $1;
                   6574:         $unum = $2;
                   6575:         $file_name = $3;
1.823     albertel 6576:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6577: 	$type = 2;
                   6578:         $udom = $1;
                   6579:         $unum = $2;
                   6580:         $group = $3;
                   6581:         $file_name = $3.'/'.$4;
                   6582:     }
                   6583:     if (wantarray) {
                   6584: 	return ($type,$udom,$unum,$file_name,$group);
                   6585:     }
                   6586:     return $type;
                   6587: }
                   6588: 
                   6589: sub is_portfolio_url {
                   6590:     my ($url) = @_;
                   6591:     return scalar(&parse_portfolio_url($url));
                   6592: }
                   6593: 
1.798     raeburn  6594: sub is_portfolio_file {
                   6595:     my ($file) = @_;
1.820     raeburn  6596:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6597:         return 1;
                   6598:     }
                   6599:     return;
                   6600: }
                   6601: 
1.976     raeburn  6602: sub usertools_access {
1.1084    raeburn  6603:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6604:     my ($access,%tools);
                   6605:     if ($context eq '') {
                   6606:         $context = 'tools';
                   6607:     }
                   6608:     if ($context eq 'requestcourses') {
                   6609:         %tools = (
                   6610:                       official   => 1,
                   6611:                       unofficial => 1,
1.1006    raeburn  6612:                       community  => 1,
1.1246    raeburn  6613:                       textbook   => 1,
1.1305    raeburn  6614:                       placement  => 1,
1.985     raeburn  6615:                  );
1.1183    raeburn  6616:     } elsif ($context eq 'requestauthor') {
                   6617:         %tools = (
                   6618:                       requestauthor => 1,
                   6619:                  );
1.985     raeburn  6620:     } else {
                   6621:         %tools = (
                   6622:                       aboutme   => 1,
                   6623:                       blog      => 1,
1.1177    raeburn  6624:                       webdav    => 1,
1.985     raeburn  6625:                       portfolio => 1,
                   6626:                  );
                   6627:     }
1.976     raeburn  6628:     return if (!defined($tools{$tool}));
                   6629: 
1.1242    raeburn  6630:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6631:         $udom = $env{'user.domain'};
                   6632:         $uname = $env{'user.name'};
                   6633:     }
                   6634: 
1.978     raeburn  6635:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6636:         if ($action ne 'reload') {
1.985     raeburn  6637:             if ($context eq 'requestcourses') {
                   6638:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  6639:             } elsif ($context eq 'requestauthor') {
                   6640:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6641:             } else {
                   6642:                 return $env{'environment.availabletools.'.$tool};
                   6643:             }
                   6644:         }
1.976     raeburn  6645:     }
                   6646: 
1.1183    raeburn  6647:     my ($toolstatus,$inststatus,$envkey);
                   6648:     if ($context eq 'requestauthor') {
                   6649:         $envkey = $context; 
                   6650:     } else {
                   6651:         $envkey = $context.'.'.$tool;
                   6652:     }
1.976     raeburn  6653: 
1.985     raeburn  6654:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6655:          ($action ne 'reload')) {
1.1183    raeburn  6656:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6657:         $inststatus = $env{'environment.inststatus'};
                   6658:     } else {
1.1084    raeburn  6659:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  6660:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6661:             $inststatus = $userenvref->{'inststatus'};
                   6662:         } else {
1.1183    raeburn  6663:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6664:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6665:             $inststatus = $userenv{'inststatus'};
                   6666:         }
1.976     raeburn  6667:     }
                   6668: 
                   6669:     if ($toolstatus ne '') {
                   6670:         if ($toolstatus) {
                   6671:             $access = 1;
                   6672:         } else {
                   6673:             $access = 0;
                   6674:         }
                   6675:         return $access;
                   6676:     }
                   6677: 
1.1084    raeburn  6678:     my ($is_adv,%domdef);
                   6679:     if (ref($is_advref) eq 'HASH') {
                   6680:         $is_adv = $is_advref->{'is_adv'};
                   6681:     } else {
                   6682:         $is_adv = &is_advanced_user($udom,$uname);
                   6683:     }
                   6684:     if (ref($domdefref) eq 'HASH') {
                   6685:         %domdef = %{$domdefref};
                   6686:     } else {
                   6687:         %domdef = &get_domain_defaults($udom);
                   6688:     }
1.976     raeburn  6689:     if (ref($domdef{$tool}) eq 'HASH') {
                   6690:         if ($is_adv) {
                   6691:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6692:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6693:                     $access = 1;
                   6694:                 } else {
                   6695:                     $access = 0;
                   6696:                 }
                   6697:                 return $access;
                   6698:             }
                   6699:         }
                   6700:         if ($inststatus ne '') {
                   6701:             my ($hasaccess,$hasnoaccess);
                   6702:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6703:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6704:                     if ($domdef{$tool}{$affiliation}) {
                   6705:                         $hasaccess = 1;
                   6706:                     } else {
                   6707:                         $hasnoaccess = 1;
                   6708:                     }
                   6709:                 }
                   6710:             }
                   6711:             if ($hasaccess || $hasnoaccess) {
                   6712:                 if ($hasaccess) {
                   6713:                     $access = 1;
                   6714:                 } elsif ($hasnoaccess) {
                   6715:                     $access = 0; 
                   6716:                 }
                   6717:                 return $access;
                   6718:             }
                   6719:         } else {
                   6720:             if ($domdef{$tool}{'default'} ne '') {
                   6721:                 if ($domdef{$tool}{'default'}) {
                   6722:                     $access = 1;
                   6723:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6724:                     $access = 0;
                   6725:                 }
                   6726:                 return $access;
                   6727:             }
                   6728:         }
                   6729:     } else {
1.1177    raeburn  6730:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6731:             $access = 1;
                   6732:         } else {
                   6733:             $access = 0;
                   6734:         }
1.976     raeburn  6735:         return $access;
                   6736:     }
                   6737: }
                   6738: 
1.1050    raeburn  6739: sub is_course_owner {
                   6740:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6741:     if (($udom eq '') || ($uname eq '')) {
                   6742:         $udom = $env{'user.domain'};
                   6743:         $uname = $env{'user.name'};
                   6744:     }
                   6745:     unless (($udom eq '') || ($uname eq '')) {
                   6746:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6747:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6748:                 return 1;
                   6749:             } else {
                   6750:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6751:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6752:                     return 1;
                   6753:                 }
                   6754:             }
                   6755:         }
                   6756:     }
                   6757:     return;
                   6758: }
                   6759: 
1.976     raeburn  6760: sub is_advanced_user {
                   6761:     my ($udom,$uname) = @_;
1.1085    raeburn  6762:     if ($udom ne '' && $uname ne '') {
                   6763:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6764:             if (wantarray) {
                   6765:                 return ($env{'user.adv'},$env{'user.author'});
                   6766:             } else {
                   6767:                 return $env{'user.adv'};
                   6768:             }
1.1085    raeburn  6769:         }
                   6770:     }
1.976     raeburn  6771:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6772:     my %allroles;
1.1128    raeburn  6773:     my ($is_adv,$is_author);
1.976     raeburn  6774:     foreach my $role (keys(%roleshash)) {
                   6775:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6776:         my $area = '/'.$tdomain.'/'.$trest;
                   6777:         if ($sec ne '') {
                   6778:             $area .= '/'.$sec;
                   6779:         }
                   6780:         if (($area ne '') && ($trole ne '')) {
                   6781:             my $spec=$trole.'.'.$area;
                   6782:             if ($trole =~ /^cr\//) {
                   6783:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6784:             } elsif ($trole ne 'gr') {
                   6785:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6786:             }
1.1128    raeburn  6787:             if ($trole eq 'au') {
                   6788:                 $is_author = 1;
                   6789:             }
1.976     raeburn  6790:         }
                   6791:     }
                   6792:     foreach my $role (keys(%allroles)) {
                   6793:         last if ($is_adv);
                   6794:         foreach my $item (split(/:/,$allroles{$role})) {
                   6795:             if ($item ne '') {
                   6796:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6797:                 if ($privilege eq 'adv') {
                   6798:                     $is_adv = 1;
                   6799:                     last;
                   6800:                 }
                   6801:             }
                   6802:         }
                   6803:     }
1.1128    raeburn  6804:     if (wantarray) {
                   6805:         return ($is_adv,$is_author);
                   6806:     }
1.976     raeburn  6807:     return $is_adv;
                   6808: }
1.798     raeburn  6809: 
1.1035    raeburn  6810: sub check_can_request {
1.1036    raeburn  6811:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6812:     my $canreq = 0;
                   6813:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6814:     my @options = ('approval','validate','autolimit');
                   6815:     my $optregex = join('|',@options);
                   6816:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6817:         foreach my $type (@{$types}) {
                   6818:             if (&usertools_access($env{'user.name'},
                   6819:                                   $env{'user.domain'},
                   6820:                                   $type,undef,'requestcourses')) {
                   6821:                 $canreq ++;
1.1036    raeburn  6822:                 if (ref($request_domains) eq 'HASH') {
                   6823:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6824:                 }
1.1035    raeburn  6825:                 if ($dom eq $env{'user.domain'}) {
                   6826:                     $can_request->{$type} = 1;
                   6827:                 }
                   6828:             }
                   6829:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6830:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6831:                 if (@curr > 0) {
1.1036    raeburn  6832:                     foreach my $item (@curr) {
                   6833:                         if (ref($request_domains) eq 'HASH') {
                   6834:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6835:                             if ($otherdom ne '') {
                   6836:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6837:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6838:                                         push(@{$request_domains->{$type}},$otherdom);
                   6839:                                     }
                   6840:                                 } else {
                   6841:                                     push(@{$request_domains->{$type}},$otherdom);
                   6842:                                 }
                   6843:                             }
                   6844:                         }
                   6845:                     }
                   6846:                     unless($dom eq $env{'user.domain'}) {
                   6847:                         $canreq ++;
1.1035    raeburn  6848:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6849:                             $can_request->{$type} = 1;
                   6850:                         }
                   6851:                     }
                   6852:                 }
                   6853:             }
                   6854:         }
                   6855:     }
                   6856:     return $canreq;
                   6857: }
                   6858: 
1.341     www      6859: # ---------------------------------------------- Custom access rule evaluation
                   6860: 
                   6861: sub customaccess {
                   6862:     my ($priv,$uri)=@_;
1.807     albertel 6863:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6864:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6865:     $udom = &LONCAPA::clean_domain($udom);
                   6866:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6867:     my $access=0;
1.800     albertel 6868:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6869: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6870: 	if ($type eq 'user') {
                   6871: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6872: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6873: 		if ($tdom) {
                   6874: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6875: 		}
1.896     albertel 6876: 		if ($tuname) {
                   6877: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6878: 		}
                   6879: 		$access=($effect eq 'allow');
                   6880: 		last;
                   6881: 	    }
                   6882: 	} else {
                   6883: 	    if ($role) {
                   6884: 		if ($role ne $urole) { next; }
                   6885: 	    }
                   6886: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6887: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6888: 		if ($tdom) {
                   6889: 		    if ($tdom ne $udom) { next; }
                   6890: 		}
                   6891: 		if ($tcrs) {
                   6892: 		    if ($tcrs ne $ucrs) { next; }
                   6893: 		}
                   6894: 		if ($tsec) {
                   6895: 		    if ($tsec ne $usec) { next; }
                   6896: 		}
                   6897: 		$access=($effect eq 'allow');
                   6898: 		last;
                   6899: 	    }
                   6900: 	    if ($realm eq '' && $role eq '') {
                   6901: 		$access=($effect eq 'allow');
                   6902: 	    }
1.402     bowersj2 6903: 	}
1.341     www      6904:     }
                   6905:     return $access;
                   6906: }
                   6907: 
1.103     harris41 6908: # ------------------------------------------------- Check for a user privilege
1.12      www      6909: 
                   6910: sub allowed {
1.1281    raeburn  6911:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 6912:     my $ver_orguri=$uri;
1.439     www      6913:     $uri=&deversion($uri);
1.152     www      6914:     my $orguri=$uri;
1.52      www      6915:     $uri=&declutter($uri);
1.809     raeburn  6916: 
1.810     raeburn  6917:     if ($priv eq 'evb') {
                   6918: # Evade communication block restrictions for specified role in a course
                   6919:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6920:             return $1;
                   6921:         } else {
                   6922:             return;
                   6923:         }
                   6924:     }
                   6925: 
1.620     albertel 6926:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6927: # Free bre access to adm and meta resources
1.775     albertel 6928:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6929: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6930: 	&& ($priv eq 'bre')) {
1.14      www      6931: 	return 'F';
1.159     www      6932:     }
                   6933: 
1.545     banghart 6934: # Free bre access to user's own portfolio contents
1.714     raeburn  6935:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6936:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6937: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6938:         my %setters;
                   6939:         my ($startblock,$endblock) = 
                   6940:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6941:         if ($startblock && $endblock) {
                   6942:             return 'B';
                   6943:         } else {
                   6944:             return 'F';
                   6945:         }
1.545     banghart 6946:     }
                   6947: 
1.762     raeburn  6948: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6949:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6950:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6951:         if (exists($env{'request.course.id'})) {
                   6952:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6953:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6954:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6955:                 my $courseprivid=$env{'request.course.id'};
                   6956:                 $courseprivid=~s/\_/\//;
                   6957:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6958:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6959:                     return $1; 
1.762     raeburn  6960:                 } else {
                   6961:                     if ($env{'request.course.sec'}) {
                   6962:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6963:                     }
                   6964:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6965:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6966:                         return $2;
                   6967:                     }
1.714     raeburn  6968:                 }
                   6969:             }
                   6970:         }
                   6971:     }
                   6972: 
1.159     www      6973: # Free bre to public access
                   6974: 
                   6975:     if ($priv eq 'bre') {
1.238     www      6976:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6977: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6978:            return 'F'; 
                   6979:         }
1.238     www      6980:         if ($copyright eq 'priv') {
                   6981:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6982: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6983: 		return '';
                   6984:             }
                   6985:         }
                   6986:         if ($copyright eq 'domain') {
                   6987:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6988: 	    unless (($env{'user.domain'} eq $1) ||
                   6989:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6990: 		return '';
                   6991:             }
1.262     matthew  6992:         }
1.620     albertel 6993:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6994:             # Library role, so allow browsing of resources in this domain.
                   6995:             return 'F';
1.238     www      6996:         }
1.341     www      6997:         if ($copyright eq 'custom') {
                   6998: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6999:         }
1.14      www      7000:     }
1.264     matthew  7001:     # Domain coordinator is trying to create a course
1.620     albertel 7002:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7003:         # uri is the requested domain in this case.
                   7004:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7005:         # a role of dc for the domain in question.
1.620     albertel 7006:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7007:     }
1.29      www      7008: 
1.52      www      7009:     my $thisallowed='';
                   7010:     my $statecond=0;
                   7011:     my $courseprivid='';
                   7012: 
1.1039    raeburn  7013:     my $ownaccess;
1.1043    raeburn  7014:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7015:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7016:         if ($uri eq '') {
                   7017:             $ownaccess = 1;
                   7018:         } else {
                   7019:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7020:                 my $udom = $env{'user.domain'};
                   7021:                 my $uname = $env{'user.name'};
                   7022:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7023:                     $ownaccess = 1;
1.1040    raeburn  7024:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7025:                     unless ($uri =~ m{\.\./}) {
                   7026:                         $ownaccess = 1;
                   7027:                     }
                   7028:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7029:                     my $now = time;
                   7030:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7031:                         my $adom = $1;
                   7032:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7033:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7034:                                 my ($start,$end) = split('.',$env{$key});
                   7035:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7036:                                     $ownaccess = 1;
                   7037:                                     last;
                   7038:                                 }
                   7039:                             }
                   7040:                         }
                   7041:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7042:                         my $adom = $1;
                   7043:                         my $aname = $2;
1.1042    raeburn  7044:                         foreach my $role ('ca','aa') { 
                   7045:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7046:                                 my ($start,$end) =
                   7047:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7048:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7049:                                     $ownaccess = 1;
                   7050:                                     last;
                   7051:                                 }
1.1039    raeburn  7052:                             }
                   7053:                         }
                   7054:                     }
                   7055:                 }
                   7056:             }
                   7057:         }
                   7058:     }
                   7059: 
1.52      www      7060: # Course
                   7061: 
1.620     albertel 7062:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7063:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7064:             $thisallowed.=$1;
                   7065:         }
1.52      www      7066:     }
1.29      www      7067: 
1.52      www      7068: # Domain
                   7069: 
1.620     albertel 7070:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7071:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7072:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7073:             $thisallowed.=$1;
                   7074:         }
1.12      www      7075:     }
1.52      www      7076: 
1.1141    raeburn  7077: # User who is not author or co-author might still be able to edit
                   7078: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7079:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7080:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7081:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7082:             $thisallowed.=$1;
                   7083:         }
                   7084:     }
                   7085: 
1.52      www      7086: # Course: uri itself is a course
1.66      www      7087:     my $courseuri=$uri;
                   7088:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7089:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7090: 
1.620     albertel 7091:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7092:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7093:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7094:             $thisallowed.=$1;
                   7095:         }
1.12      www      7096:     }
1.29      www      7097: 
1.665     albertel 7098: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7099: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7100:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7101: 	$thisallowed='';
1.671     raeburn  7102:         my ($match)=&is_on_map($uri);
                   7103:         if ($match) {
                   7104:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7105:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  7106:                 my $value = $1;
                   7107:                 if ($noblockcheck) {
                   7108:                     $thisallowed.=$value;
1.1162    raeburn  7109:                 } else {
1.1281    raeburn  7110:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7111:                     if (@blockers > 0) {
                   7112:                         $thisallowed = 'B';
                   7113:                     } else {
                   7114:                         $thisallowed.=$value;
                   7115:                     }
1.1162    raeburn  7116:                 }
1.671     raeburn  7117:             }
                   7118:         } else {
1.705     albertel 7119:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7120:             if ($refuri) {
                   7121:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7122:                     $thisallowed='F';
1.671     raeburn  7123:                 } else {
                   7124:                     $refuri=&declutter($refuri);
                   7125:                     my ($match) = &is_on_map($refuri);
                   7126:                     if ($match) {
1.1281    raeburn  7127:                         if ($noblockcheck) {
                   7128:                             $thisallowed='F';
1.1162    raeburn  7129:                         } else {
1.1281    raeburn  7130:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7131:                             if (@blockers > 0) {
                   7132:                                 $thisallowed = 'B';
                   7133:                             } else {
                   7134:                                 $thisallowed='F';
                   7135:                             }
1.1162    raeburn  7136:                         }
1.671     raeburn  7137:                     }
1.669     raeburn  7138:                 }
1.671     raeburn  7139:             }
                   7140:         }
1.314     www      7141:     }
1.492     albertel 7142: 
1.766     albertel 7143:     if ($priv eq 'bre'
                   7144: 	&& $thisallowed ne 'F' 
                   7145: 	&& $thisallowed ne '2'
                   7146: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  7147: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7148:     }
1.1250    raeburn  7149: 
1.52      www      7150: # Full access at system, domain or course-wide level? Exit.
1.29      www      7151:     if ($thisallowed=~/F/) {
                   7152: 	return 'F';
                   7153:     }
                   7154: 
1.52      www      7155: # If this is generating or modifying users, exit with special codes
1.29      www      7156: 
1.643     www      7157:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7158: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7159: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7160: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7161: 	    unless ($auname) { return $thisallowed; }
                   7162: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7163: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7164: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7165: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7166: 	}
1.52      www      7167: 	return $thisallowed;
                   7168:     }
                   7169: #
1.103     harris41 7170: # Gathered so far: system, domain and course wide privileges
1.52      www      7171: #
                   7172: # Course: See if uri or referer is an individual resource that is part of 
                   7173: # the course
                   7174: 
1.620     albertel 7175:     if ($env{'request.course.id'}) {
1.232     www      7176: 
1.620     albertel 7177:        $courseprivid=$env{'request.course.id'};
                   7178:        if ($env{'request.course.sec'}) {
                   7179:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7180:        }
                   7181:        $courseprivid=~s/\_/\//;
                   7182:        my $checkreferer=1;
1.232     www      7183:        my ($match,$cond)=&is_on_map($uri);
                   7184:        if ($match) {
                   7185:            $statecond=$cond;
1.620     albertel 7186:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7187:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7188:                my $value = $1;
                   7189:                if ($priv eq 'bre') {
1.1281    raeburn  7190:                    if ($noblockcheck) {
                   7191:                        $thisallowed.=$value;
1.1162    raeburn  7192:                    } else {
1.1281    raeburn  7193:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7194:                        if (@blockers > 0) {
                   7195:                            $thisallowed = 'B';
                   7196:                        } else {
                   7197:                            $thisallowed.=$value;
                   7198:                        }
1.1162    raeburn  7199:                    }
                   7200:                } else {
                   7201:                    $thisallowed.=$value;
                   7202:                }
1.52      www      7203:                $checkreferer=0;
                   7204:            }
1.29      www      7205:        }
1.83      www      7206:        
1.148     www      7207:        if ($checkreferer) {
1.620     albertel 7208: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7209:             unless ($refuri) {
1.800     albertel 7210:                 foreach my $key (keys(%env)) {
                   7211: 		    if ($key=~/^httpref\..*\*/) {
                   7212: 			my $pattern=$key;
1.156     www      7213:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7214:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7215:                         $pattern=~s/\//\\\//g;
1.152     www      7216:                         if ($orguri=~/$pattern/) {
1.800     albertel 7217: 			    $refuri=$env{$key};
1.148     www      7218:                         }
                   7219:                     }
1.191     harris41 7220:                 }
1.148     www      7221:             }
1.232     www      7222: 
1.148     www      7223:          if ($refuri) { 
1.152     www      7224: 	  $refuri=&declutter($refuri);
1.232     www      7225:           my ($match,$cond)=&is_on_map($refuri);
                   7226:             if ($match) {
                   7227:               my $refstatecond=$cond;
1.620     albertel 7228:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7229:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7230:                   my $value = $1;
                   7231:                   if ($priv eq 'bre') {
1.1281    raeburn  7232:                       if ($noblockcheck) {
                   7233:                           $thisallowed.=$value;
1.1162    raeburn  7234:                       } else {
1.1281    raeburn  7235:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7236:                           if (@blockers > 0) {
                   7237:                               $thisallowed = 'B';
                   7238:                           } else {
                   7239:                               $thisallowed.=$value;
                   7240:                           }
1.1162    raeburn  7241:                       }
                   7242:                   } else {
                   7243:                       $thisallowed.=$value;
                   7244:                   }
1.53      www      7245:                   $uri=$refuri;
                   7246:                   $statecond=$refstatecond;
1.52      www      7247:               }
                   7248:           }
1.148     www      7249:         }
1.29      www      7250:        }
1.52      www      7251:    }
1.29      www      7252: 
1.52      www      7253: #
1.103     harris41 7254: # Gathered now: all privileges that could apply, and condition number
1.52      www      7255: # 
                   7256: #
                   7257: # Full or no access?
                   7258: #
1.29      www      7259: 
1.52      www      7260:     if ($thisallowed=~/F/) {
                   7261: 	return 'F';
                   7262:     }
1.29      www      7263: 
1.52      www      7264:     unless ($thisallowed) {
                   7265:         return '';
                   7266:     }
1.29      www      7267: 
1.52      www      7268: # Restrictions exist, deal with them
                   7269: #
                   7270: #   C:according to course preferences
                   7271: #   R:according to resource settings
                   7272: #   L:unless locked
                   7273: #   X:according to user session state
                   7274: #
                   7275: 
                   7276: # Possibly locked functionality, check all courses
1.54      www      7277: # Locks might take effect only after 10 minutes cache expiration for other
                   7278: # courses, and 2 minutes for current course
1.52      www      7279: 
                   7280:     my $envkey;
                   7281:     if ($thisallowed=~/L/) {
1.1000    raeburn  7282:         foreach $envkey (keys(%env)) {
1.54      www      7283:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7284:                my $courseid=$2;
                   7285:                my $roleid=$1.'.'.$2;
1.92      www      7286:                $courseid=~s/^\///;
1.54      www      7287:                my $expiretime=600;
1.620     albertel 7288:                if ($env{'request.role'} eq $roleid) {
1.54      www      7289: 		  $expiretime=120;
                   7290:                }
                   7291: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7292:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7293:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7294: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7295:                }
1.620     albertel 7296:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7297:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7298: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7299:                        &log($env{'user.domain'},$env{'user.name'},
                   7300:                             $env{'user.home'},
1.57      www      7301:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7302:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7303:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7304: 		       return '';
                   7305:                    }
                   7306:                }
1.620     albertel 7307:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7308:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7309: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7310:                        &log($env{'user.domain'},$env{'user.name'},
                   7311:                             $env{'user.home'},
1.57      www      7312:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7313:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7314:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7315: 		       return '';
                   7316:                    }
                   7317:                }
                   7318: 	   }
1.29      www      7319:        }
1.52      www      7320:     }
                   7321:    
                   7322: #
                   7323: # Rest of the restrictions depend on selected course
                   7324: #
                   7325: 
1.620     albertel 7326:     unless ($env{'request.course.id'}) {
1.766     albertel 7327: 	if ($thisallowed eq 'A') {
                   7328: 	    return 'A';
1.814     raeburn  7329:         } elsif ($thisallowed eq 'B') {
                   7330:             return 'B';
1.766     albertel 7331: 	} else {
                   7332: 	    return '1';
                   7333: 	}
1.52      www      7334:     }
1.29      www      7335: 
1.52      www      7336: #
                   7337: # Now user is definitely in a course
                   7338: #
1.53      www      7339: 
                   7340: 
                   7341: # Course preferences
                   7342: 
                   7343:    if ($thisallowed=~/C/) {
1.620     albertel 7344:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7345:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7346:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7347: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  7348: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7349: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7350: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7351: 			$env{'request.course.id'});
                   7352: 	   }
1.237     www      7353:            return '';
                   7354:        }
                   7355: 
1.620     albertel 7356:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7357: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  7358: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7359: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7360: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7361: 			$env{'request.course.id'});
                   7362: 	   }
1.54      www      7363:            return '';
                   7364:        }
1.53      www      7365:    }
                   7366: 
                   7367: # Resource preferences
                   7368: 
                   7369:    if ($thisallowed=~/R/) {
1.620     albertel 7370:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7371:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7372: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7373: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7374: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7375: 	   }
                   7376: 	   return '';
1.54      www      7377:        }
1.53      www      7378:    }
1.30      www      7379: 
1.246     www      7380: # Restricted by state or randomout?
1.30      www      7381: 
1.52      www      7382:    if ($thisallowed=~/X/) {
1.620     albertel 7383:       if ($env{'acc.randomout'}) {
1.579     albertel 7384: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7385:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7386:             return ''; 
                   7387:          }
1.247     www      7388:       }
                   7389:       if (&condval($statecond)) {
1.52      www      7390: 	 return '2';
                   7391:       } else {
                   7392:          return '';
                   7393:       }
                   7394:    }
1.30      www      7395: 
1.766     albertel 7396:     if ($thisallowed eq 'A') {
                   7397: 	return 'A';
1.814     raeburn  7398:     } elsif ($thisallowed eq 'B') {
                   7399:         return 'B';
1.766     albertel 7400:     }
1.52      www      7401:    return 'F';
1.232     www      7402: }
1.1162    raeburn  7403: 
1.1192    raeburn  7404: # ------------------------------------------- Check construction space access
                   7405: 
                   7406: sub constructaccess {
                   7407:     my ($url,$setpriv)=@_;
                   7408: 
                   7409: # We do not allow editing of previous versions of files
                   7410:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7411: 
                   7412: # Get username and domain from URL
                   7413:     my ($ownername,$ownerdomain,$ownerhome);
                   7414: 
                   7415:     ($ownerdomain,$ownername) =
1.1297    damieng  7416:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)/});
1.1192    raeburn  7417: 
                   7418: # The URL does not really point to any authorspace, forget it
                   7419:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7420: 
                   7421: # Now we need to see if the user has access to the authorspace of
                   7422: # $ownername at $ownerdomain
                   7423: 
                   7424:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7425: # Real author for this?
                   7426:        $ownerhome = $env{'user.home'};
                   7427:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7428:           return ($ownername,$ownerdomain,$ownerhome);
                   7429:        }
                   7430:     } else {
                   7431: # Co-author for this?
                   7432:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7433:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7434:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7435:             return ($ownername,$ownerdomain,$ownerhome);
                   7436:         }
1.1312    raeburn  7437:         if ($env{'request.course.id'}) {
                   7438:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   7439:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   7440:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   7441:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   7442:                     return ($ownername,$ownerdomain,$ownerhome);
                   7443:                 }
                   7444:             }
                   7445:         }
1.1192    raeburn  7446:     }
                   7447: 
                   7448: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7449: # we might as well leave
                   7450:    unless ($setpriv) { return ''; }
                   7451: 
                   7452: # Backdoor access?
                   7453:     my $allowed=&allowed('eco',$ownerdomain);
                   7454: # Nope
                   7455:     unless ($allowed) { return ''; }
                   7456: # Looks like we may have access, but could be locked by the owner of the construction space
                   7457:     if ($allowed eq 'U') {
                   7458:         my %blocked=&get('environment',['domcoord.author'],
                   7459:                          $ownerdomain,$ownername);
                   7460: # Is blocked by owner
                   7461:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7462:     }
                   7463:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7464: # Grant temporary access
                   7465:         my $then=$env{'user.login.time'};
1.1209    raeburn  7466:         my $update=$env{'user.update.time'};
1.1192    raeburn  7467:         if (!$update) { $update = $then; }
                   7468:         my $refresh=$env{'user.refresh.time'};
                   7469:         if (!$refresh) { $refresh = $update; }
                   7470:         my $now = time;
                   7471:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7472:                            $now,'ca','constructaccess');
                   7473:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7474:         return($ownername,$ownerdomain,$ownerhome);
                   7475:     }
                   7476: # No business here
                   7477:     return '';
                   7478: }
                   7479: 
1.1282    raeburn  7480: # ----------------------------------------------------------- Content Blocking
                   7481: 
                   7482: {
                   7483: # Caches for faster Course Contents display where content blocking
                   7484: # is in operation (i.e., interval param set) for timed quiz.
                   7485: #
                   7486: # User for whom data are being temporarily cached.
                   7487: my $cacheduser='';
                   7488: # Cached blockers for this user (a hash of blocking items). 
                   7489: my %cachedblockers=();
                   7490: # When the data were last cached.
                   7491: my $cachedlast='';
                   7492: 
                   7493: sub load_all_blockers {
                   7494:     my ($uname,$udom,$blocks)=@_;
                   7495:     if (($uname ne '') && ($udom ne '')) { 
                   7496:         if (($cacheduser eq $uname.':'.$udom) &&
                   7497:             (abs($cachedlast-time)<5)) {
                   7498:             return;
                   7499:         }
                   7500:     }
                   7501:     $cachedlast=time;
                   7502:     $cacheduser=$uname.':'.$udom;
                   7503:     %cachedblockers = &get_commblock_resources($blocks);
                   7504: }
                   7505: 
1.1162    raeburn  7506: sub get_comm_blocks {
                   7507:     my ($cdom,$cnum) = @_;
                   7508:     if ($cdom eq '' || $cnum eq '') {
                   7509:         return unless ($env{'request.course.id'});
                   7510:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7511:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7512:     }
                   7513:     my %commblocks;
                   7514:     my $hashid=$cdom.'_'.$cnum;
                   7515:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7516:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7517:         %commblocks = %{$blocksref};
                   7518:     } else {
                   7519:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7520:         my $cachetime = 600;
                   7521:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7522:     }
                   7523:     return %commblocks;
                   7524: }
                   7525: 
1.1282    raeburn  7526: sub get_commblock_resources {
                   7527:     my ($blocks) = @_;
                   7528:     my %blockers = ();
                   7529:     return %blockers unless ($env{'request.course.id'});
                   7530:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7531:     my %commblocks;
                   7532:     if (ref($blocks) eq 'HASH') {
                   7533:         %commblocks = %{$blocks};
                   7534:     } else {
                   7535:         %commblocks = &get_comm_blocks();
                   7536:     }
1.1282    raeburn  7537:     return %blockers unless (keys(%commblocks) > 0); 
                   7538:     my $navmap = Apache::lonnavmaps::navmap->new();
                   7539:     return %blockers unless (ref($navmap));
1.1162    raeburn  7540:     my $now = time;
                   7541:     foreach my $block (keys(%commblocks)) {
                   7542:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7543:             my ($start,$end) = ($1,$2);
                   7544:             if ($start <= $now && $end >= $now) {
                   7545:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7546:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7547:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  7548:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7549:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  7550:                             }
                   7551:                         }
                   7552:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  7553:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7554:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  7555:                             }
                   7556:                         }
                   7557:                     }
                   7558:                 }
                   7559:             }
                   7560:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7561:             my $item = $1;
1.1163    raeburn  7562:             my @to_test;
1.1162    raeburn  7563:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7564:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  7565:                     my @interval;
                   7566:                     my $type = 'map';
                   7567:                     if ($item eq 'course') {
                   7568:                         $type = 'course';
                   7569:                         @interval=&EXT("resource.0.interval");
                   7570:                     } else {
                   7571:                         if ($item =~ /___\d+___/) {
                   7572:                             $type = 'resource';
                   7573:                             @interval=&EXT("resource.0.interval",$item);
                   7574:                             if (ref($navmap)) {                        
                   7575:                                 my $res = $navmap->getBySymb($item); 
                   7576:                                 push(@to_test,$res);
                   7577:                             }
1.1162    raeburn  7578:                         } else {
1.1282    raeburn  7579:                             my $mapsymb = &symbread($item,1);
                   7580:                             if ($mapsymb) {
                   7581:                                 if (ref($navmap)) {
                   7582:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   7583:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   7584:                                     foreach my $res (@to_test) {
                   7585:                                         my $symb = $res->symb();
                   7586:                                         next if ($symb eq $mapsymb);
                   7587:                                         if ($symb ne '') {
                   7588:                                             @interval=&EXT("resource.0.interval",$symb);
                   7589:                                             if ($interval[1] eq 'map') {
                   7590:                                                 last;
1.1162    raeburn  7591:                                             }
                   7592:                                         }
                   7593:                                     }
                   7594:                                 }
                   7595:                             }
                   7596:                         }
1.1282    raeburn  7597:                     }
1.1310    raeburn  7598:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  7599:                         my $timelimit = $1; 
1.1282    raeburn  7600:                         my $first_access;
                   7601:                         if ($type eq 'resource') {
                   7602:                             $first_access=&get_first_access($interval[1],$item);
                   7603:                         } elsif ($type eq 'map') {
                   7604:                             $first_access=&get_first_access($interval[1],undef,$item);
                   7605:                         } else {
                   7606:                             $first_access=&get_first_access($interval[1]);
                   7607:                         }
                   7608:                         if ($first_access) {
1.1292    raeburn  7609:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  7610:                             if ($timesup > $now) {
                   7611:                                 my $activeblock;
                   7612:                                 foreach my $res (@to_test) {
1.1283    raeburn  7613:                                     if ($res->answerable()) {
1.1282    raeburn  7614:                                         $activeblock = 1;
                   7615:                                         last;
                   7616:                                     }
                   7617:                                 }
                   7618:                                 if ($activeblock) {
                   7619:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7620:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7621:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   7622:                                          }
                   7623:                                     }
                   7624:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7625:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7626:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  7627:                                         }
1.1162    raeburn  7628:                                     }
                   7629:                                 }
                   7630:                             }
                   7631:                         }
                   7632:                     }
                   7633:                 }
                   7634:             }
                   7635:         }
                   7636:     }
1.1282    raeburn  7637:     return %blockers;
1.1162    raeburn  7638: }
                   7639: 
1.1282    raeburn  7640: sub has_comm_blocking {
                   7641:     my ($priv,$symb,$uri,$blocks) = @_;
                   7642:     my @blockers;
                   7643:     return unless ($env{'request.course.id'});
                   7644:     return unless ($priv eq 'bre');
                   7645:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7646:     return if ($env{'request.state'} eq 'construct');
                   7647:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   7648:     return unless (keys(%cachedblockers) > 0);
                   7649:     my (%possibles,@symbs);
                   7650:     if (!$symb) {
                   7651:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  7652:     }
1.1282    raeburn  7653:     if ($symb) {
                   7654:         @symbs = ($symb);
                   7655:     } elsif (keys(%possibles)) { 
                   7656:         @symbs = keys(%possibles);
                   7657:     }
                   7658:     my $noblock;
                   7659:     foreach my $symb (@symbs) {
                   7660:         last if ($noblock);
                   7661:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   7662:         foreach my $block (keys(%cachedblockers)) {
                   7663:             if ($block =~ /^firstaccess____(.+)$/) {
                   7664:                 my $item = $1;
                   7665:                 if (($item eq $map) || ($item eq $symb)) {
                   7666:                     $noblock = 1;
                   7667:                     last;
                   7668:                 }
                   7669:             }
                   7670:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   7671:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   7672:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   7673:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   7674:                             push(@blockers,$block);
                   7675:                         }
                   7676:                     }
                   7677:                 }
1.1162    raeburn  7678:             }
1.1282    raeburn  7679:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   7680:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   7681:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   7682:                         push(@blockers,$block);
                   7683:                     }
                   7684:                 }
1.1162    raeburn  7685:             }
                   7686:         }
                   7687:     }
1.1282    raeburn  7688:     return if ($noblock);
                   7689:     return @blockers;
                   7690: }
1.1162    raeburn  7691: }
                   7692: 
1.1282    raeburn  7693: # -------------------------------- Deversion and split uri into path an filename   
                   7694: 
1.1133    foxr     7695: #
1.1282    raeburn  7696: #   Removes the version from a URI and
1.1133    foxr     7697: #   splits it in to its filename and path to the filename.
                   7698: #   Seems like File::Basename could have done this more clearly.
                   7699: #   Parameters:
                   7700: #      $uri   - input URI
                   7701: #   Returns:
                   7702: #     Two element list consisting of 
                   7703: #     $pathname  - the URI up to and excluding the trailing /
                   7704: #     $filename  - The part of the URI following the last /
                   7705: #  NOTE:
                   7706: #    Another realization of this is simply:
                   7707: #    use File::Basename;
                   7708: #    ...
                   7709: #    $uri = shift;
                   7710: #    $filename = basename($uri);
                   7711: #    $path     = dirname($uri);
                   7712: #    return ($filename, $path);
                   7713: #
                   7714: #     The implementation below is probably faster however.
                   7715: #
1.710     albertel 7716: sub split_uri_for_cond {
                   7717:     my $uri=&deversion(&declutter(shift));
                   7718:     my @uriparts=split(/\//,$uri);
                   7719:     my $filename=pop(@uriparts);
                   7720:     my $pathname=join('/',@uriparts);
                   7721:     return ($pathname,$filename);
                   7722: }
1.232     www      7723: # --------------------------------------------------- Is a resource on the map?
                   7724: 
                   7725: sub is_on_map {
1.710     albertel 7726:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7727:     #Trying to find the conditional for the file
1.620     albertel 7728:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7729: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7730:     if ($match) {
1.289     bowersj2 7731: 	return (1,$1);
                   7732:     } else {
1.434     www      7733: 	return (0,0);
1.289     bowersj2 7734:     }
1.12      www      7735: }
                   7736: 
1.427     www      7737: # --------------------------------------------------------- Get symb from alias
                   7738: 
                   7739: sub get_symb_from_alias {
                   7740:     my $symb=shift;
                   7741:     my ($map,$resid,$url)=&decode_symb($symb);
                   7742: # Already is a symb
                   7743:     if ($url) { return $symb; }
                   7744: # Must be an alias
                   7745:     my $aliassymb='';
                   7746:     my %bighash;
1.620     albertel 7747:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7748:                             &GDBM_READER(),0640)) {
                   7749:         my $rid=$bighash{'mapalias_'.$symb};
                   7750: 	if ($rid) {
                   7751: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7752: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7753: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7754: 	}
                   7755:         untie %bighash;
                   7756:     }
                   7757:     return $aliassymb;
                   7758: }
                   7759: 
1.12      www      7760: # ----------------------------------------------------------------- Define Role
                   7761: 
                   7762: sub definerole {
                   7763:   if (allowed('mcr','/')) {
                   7764:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7765:     foreach my $role (split(':',$sysrole)) {
                   7766: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7767:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7768:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7769: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7770:                return "refused:s:$crole&$cqual"; 
                   7771:             }
                   7772:         }
1.191     harris41 7773:     }
1.800     albertel 7774:     foreach my $role (split(':',$domrole)) {
                   7775: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7776:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7777:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7778: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7779:                return "refused:d:$crole&$cqual"; 
                   7780:             }
                   7781:         }
1.191     harris41 7782:     }
1.800     albertel 7783:     foreach my $role (split(':',$courole)) {
                   7784: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7785:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7786:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7787: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7788:                return "refused:c:$crole&$cqual"; 
                   7789:             }
                   7790:         }
1.191     harris41 7791:     }
1.620     albertel 7792:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7793:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7794: 	        "rolesdef_$rolename=".
                   7795:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7796:     return reply($command,$env{'user.home'});
1.12      www      7797:   } else {
                   7798:     return 'refused';
                   7799:   }
1.105     harris41 7800: }
                   7801: 
                   7802: # ---------------- Make a metadata query against the network of library servers
                   7803: 
                   7804: sub metadata_query {
1.1237    raeburn  7805:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7806:     my %rhash;
1.845     albertel 7807:     my %libserv = &all_library();
1.244     matthew  7808:     my @server_list = (defined($server_array) ? @$server_array
                   7809:                                               : keys(%libserv) );
                   7810:     for my $server (@server_list) {
1.1237    raeburn  7811:         my $domains = ''; 
                   7812:         if (ref($domains_hash) eq 'HASH') {
                   7813:             $domains = $domains_hash->{$server}; 
                   7814:         }
1.118     harris41 7815: 	unless ($custom or $customshow) {
1.1237    raeburn  7816: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7817: 	    $rhash{$server}=$reply;
                   7818: 	}
                   7819: 	else {
                   7820: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  7821: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7822: 			     $server);
                   7823: 	    $rhash{$server}=$reply;
                   7824: 	}
1.112     harris41 7825:     }
1.118     harris41 7826:     return \%rhash;
1.240     www      7827: }
                   7828: 
                   7829: # ----------------------------------------- Send log queries and wait for reply
                   7830: 
                   7831: sub log_query {
                   7832:     my ($uname,$udom,$query,%filters)=@_;
                   7833:     my $uhome=&homeserver($uname,$udom);
                   7834:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7835:     my $uhost=&hostname($uhome);
1.800     albertel 7836:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7837:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7838:                        $uhome);
1.479     albertel 7839:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7840:     return get_query_reply($queryid);
                   7841: }
                   7842: 
1.818     raeburn  7843: # -------------------------- Update MySQL table for portfolio file
                   7844: 
                   7845: sub update_portfolio_table {
1.821     raeburn  7846:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7847:     if ($group ne '') {
                   7848:         $file_name =~s /^\Q$group\E//;
                   7849:     }
1.818     raeburn  7850:     my $homeserver = &homeserver($uname,$udom);
                   7851:     my $queryid=
1.821     raeburn  7852:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7853:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7854:     my $reply = &get_query_reply($queryid);
                   7855:     return $reply;
                   7856: }
                   7857: 
1.899     raeburn  7858: # -------------------------- Update MySQL allusers table
                   7859: 
                   7860: sub update_allusers_table {
                   7861:     my ($uname,$udom,$names) = @_;
                   7862:     my $homeserver = &homeserver($uname,$udom);
                   7863:     my $queryid=
                   7864:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7865:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7866:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7867:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7868:                'generation='.&escape($names->{'generation'}).'%%'.
                   7869:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7870:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7871:     return;
1.899     raeburn  7872: }
                   7873: 
1.508     raeburn  7874: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7875: 
                   7876: sub fetch_enrollment_query {
1.511     raeburn  7877:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7878:     my $homeserver;
1.547     raeburn  7879:     my $maxtries = 1;
1.508     raeburn  7880:     if ($context eq 'automated') {
                   7881:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7882:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7883:     } else {
                   7884:         $homeserver = &homeserver($cnum,$dom);
                   7885:     }
1.838     albertel 7886:     my $host=&hostname($homeserver);
1.506     raeburn  7887:     my $cmd = '';
1.1000    raeburn  7888:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7889:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7890:     }
                   7891:     $cmd =~ s/%%$//;
                   7892:     $cmd = &escape($cmd);
                   7893:     my $query = 'fetchenrollment';
1.620     albertel 7894:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7895:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7896:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7897:         return 'error: '.$queryid;
                   7898:     }
1.506     raeburn  7899:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7900:     my $tries = 1;
                   7901:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7902:         $reply = &get_query_reply($queryid);
                   7903:         $tries ++;
                   7904:     }
1.526     raeburn  7905:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7906:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7907:     } else {
1.901     albertel 7908:         my @responses = split(/:/,$reply);
1.515     raeburn  7909:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7910:             foreach my $line (@responses) {
                   7911:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7912:                 $$replyref{$key} = $value;
                   7913:             }
                   7914:         } else {
1.1117    foxr     7915:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7916:             foreach my $line (@responses) {
                   7917:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7918:                 $$replyref{$key} = $value;
                   7919:                 if ($value > 0) {
1.800     albertel 7920:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7921:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7922:                         my $destname = $pathname.'/'.$filename;
                   7923:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7924:                         if ($xml_classlist =~ /^error/) {
                   7925:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7926:                         } else {
1.506     raeburn  7927:                             if ( open(FILE,">$destname") ) {
                   7928:                                 print FILE &unescape($xml_classlist);
                   7929:                                 close(FILE);
1.526     raeburn  7930:                             } else {
                   7931:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7932:                             }
                   7933:                         }
                   7934:                     }
                   7935:                 }
                   7936:             }
                   7937:         }
                   7938:         return 'ok';
                   7939:     }
                   7940:     return 'error';
                   7941: }
                   7942: 
1.242     www      7943: sub get_query_reply {
                   7944:     my $queryid=shift;
1.1117    foxr     7945:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7946:     my $reply='';
                   7947:     for (1..100) {
1.1289    damieng  7948: 	sleep(0.2);
1.240     www      7949:         if (-e $replyfile.'.end') {
1.448     albertel 7950: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7951: 		$reply = join('',<$fh>);
                   7952: 		close($fh);
1.240     www      7953: 	   } else { return 'error: reply_file_error'; }
1.242     www      7954:            return &unescape($reply);
                   7955: 	}
1.240     www      7956:     }
1.242     www      7957:     return 'timeout:'.$queryid;
1.240     www      7958: }
                   7959: 
                   7960: sub courselog_query {
1.241     www      7961: #
                   7962: # possible filters:
                   7963: # url: url or symb
                   7964: # username
                   7965: # domain
                   7966: # action: view, submit, grade
                   7967: # start: timestamp
                   7968: # end: timestamp
                   7969: #
1.240     www      7970:     my (%filters)=@_;
1.620     albertel 7971:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7972:     if ($filters{'url'}) {
                   7973: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7974:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7975:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7976:     }
1.620     albertel 7977:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7978:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7979:     return &log_query($cname,$cdom,'courselog',%filters);
                   7980: }
                   7981: 
                   7982: sub userlog_query {
1.858     raeburn  7983: #
                   7984: # possible filters:
                   7985: # action: log check role
                   7986: # start: timestamp
                   7987: # end: timestamp
                   7988: #
1.240     www      7989:     my ($uname,$udom,%filters)=@_;
                   7990:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7991: }
                   7992: 
1.506     raeburn  7993: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7994: 
                   7995: sub auto_run {
1.508     raeburn  7996:     my ($cnum,$cdom) = @_;
1.876     raeburn  7997:     my $response = 0;
                   7998:     my $settings;
                   7999:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8000:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8001:         $settings = $domconfig{'autoenroll'};
                   8002:         if ($settings->{'run'} eq '1') {
                   8003:             $response = 1;
                   8004:         }
                   8005:     } else {
1.934     raeburn  8006:         my $homeserver;
                   8007:         if (&is_course($cdom,$cnum)) {
                   8008:             $homeserver = &homeserver($cnum,$cdom);
                   8009:         } else {
                   8010:             $homeserver = &domain($cdom,'primary');
                   8011:         }
                   8012:         if ($homeserver ne 'no_host') {
                   8013:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8014:         }
1.876     raeburn  8015:     }
1.506     raeburn  8016:     return $response;
                   8017: }
1.776     albertel 8018: 
1.506     raeburn  8019: sub auto_get_sections {
1.508     raeburn  8020:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8021:     my $homeserver;
                   8022:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8023:         $homeserver = &homeserver($cnum,$cdom);
                   8024:     }
                   8025:     if (!defined($homeserver)) { 
                   8026:         if ($cdom =~ /^$match_domain$/) {
                   8027:             $homeserver = &domain($cdom,'primary');
                   8028:         }
                   8029:     }
                   8030:     my @secs;
                   8031:     if (defined($homeserver)) {
                   8032:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8033:         unless ($response eq 'refused') {
                   8034:             @secs = split(/:/,$response);
                   8035:         }
1.506     raeburn  8036:     }
                   8037:     return @secs;
                   8038: }
1.776     albertel 8039: 
1.506     raeburn  8040: sub auto_new_course {
1.1099    raeburn  8041:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8042:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8043:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8044:     return $response;
                   8045: }
1.776     albertel 8046: 
1.506     raeburn  8047: sub auto_validate_courseID {
1.508     raeburn  8048:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8049:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8050:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8051:     return $response;
                   8052: }
1.776     albertel 8053: 
1.1007    raeburn  8054: sub auto_validate_instcode {
1.1020    raeburn  8055:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8056:     my ($homeserver,$response);
                   8057:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8058:         $homeserver = &homeserver($cnum,$cdom);
                   8059:     }
                   8060:     if (!defined($homeserver)) {
                   8061:         if ($cdom =~ /^$match_domain$/) {
                   8062:             $homeserver = &domain($cdom,'primary');
                   8063:         }
                   8064:     }
1.1065    raeburn  8065:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8066:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  8067:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8068:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8069: }
                   8070: 
1.506     raeburn  8071: sub auto_create_password {
1.873     raeburn  8072:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8073:     my ($homeserver,$response);
1.506     raeburn  8074:     my $create_passwd = 0;
                   8075:     my $authchk = '';
1.873     raeburn  8076:     if ($udom =~ /^$match_domain$/) {
                   8077:         $homeserver = &domain($udom,'primary');
                   8078:     }
                   8079:     if ($homeserver eq '') {
                   8080:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8081:             $homeserver = &homeserver($cnum,$cdom);
                   8082:         }
                   8083:     }
                   8084:     if ($homeserver eq '') {
                   8085:         $authchk = 'nodomain';
1.506     raeburn  8086:     } else {
1.873     raeburn  8087:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8088:         if ($response eq 'refused') {
                   8089:             $authchk = 'refused';
                   8090:         } else {
1.901     albertel 8091:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8092:         }
1.506     raeburn  8093:     }
                   8094:     return ($authparam,$create_passwd,$authchk);
                   8095: }
                   8096: 
1.706     raeburn  8097: sub auto_photo_permission {
                   8098:     my ($cnum,$cdom,$students) = @_;
                   8099:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8100:     my ($outcome,$perm_reqd,$conditions) = 
                   8101: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8102:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8103: 	return (undef,undef);
                   8104:     }
1.706     raeburn  8105:     return ($outcome,$perm_reqd,$conditions);
                   8106: }
                   8107: 
                   8108: sub auto_checkphotos {
                   8109:     my ($uname,$udom,$pid) = @_;
                   8110:     my $homeserver = &homeserver($uname,$udom);
                   8111:     my ($result,$resulttype);
                   8112:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8113: 				   &escape($uname).':'.&escape($pid),
                   8114: 				   $homeserver));
1.709     albertel 8115:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8116: 	return (undef,undef);
                   8117:     }
1.706     raeburn  8118:     if ($outcome) {
                   8119:         ($result,$resulttype) = split(/:/,$outcome);
                   8120:     } 
                   8121:     return ($result,$resulttype);
                   8122: }
                   8123: 
                   8124: sub auto_photochoice {
                   8125:     my ($cnum,$cdom) = @_;
                   8126:     my $homeserver = &homeserver($cnum,$cdom);
                   8127:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8128: 						       &escape($cdom),
                   8129: 						       $homeserver)));
1.709     albertel 8130:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8131: 	return (undef,undef);
                   8132:     }
1.706     raeburn  8133:     return ($update,$comment);
                   8134: }
                   8135: 
                   8136: sub auto_photoupdate {
                   8137:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8138:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8139:     my $host=&hostname($homeserver);
1.706     raeburn  8140:     my $cmd = '';
                   8141:     my $maxtries = 1;
1.800     albertel 8142:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8143:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8144:     }
                   8145:     $cmd =~ s/%%$//;
                   8146:     $cmd = &escape($cmd);
                   8147:     my $query = 'institutionalphotos';
                   8148:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8149:     unless ($queryid=~/^\Q$host\E\_/) {
                   8150:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8151:         return 'error: '.$queryid;
                   8152:     }
                   8153:     my $reply = &get_query_reply($queryid);
                   8154:     my $tries = 1;
                   8155:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8156:         $reply = &get_query_reply($queryid);
                   8157:         $tries ++;
                   8158:     }
                   8159:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8160:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8161:     } else {
                   8162:         my @responses = split(/:/,$reply);
                   8163:         my $outcome = shift(@responses); 
                   8164:         foreach my $item (@responses) {
                   8165:             my ($key,$value) = split(/=/,$item);
                   8166:             $$photo{$key} = $value;
                   8167:         }
                   8168:         return $outcome;
                   8169:     }
                   8170:     return 'error';
                   8171: }
                   8172: 
1.521     raeburn  8173: sub auto_instcode_format {
1.793     albertel 8174:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8175: 	$cat_order) = @_;
1.521     raeburn  8176:     my $courses = '';
1.772     raeburn  8177:     my @homeservers;
1.521     raeburn  8178:     if ($caller eq 'global') {
1.841     albertel 8179: 	my %servers = &get_servers($codedom,'library');
                   8180: 	foreach my $tryserver (keys(%servers)) {
                   8181: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8182: 		push(@homeservers,$tryserver);
                   8183: 	    }
1.584     raeburn  8184:         }
1.1022    raeburn  8185:     } elsif ($caller eq 'requests') {
                   8186:         if ($codedom =~ /^$match_domain$/) {
                   8187:             my $chome = &domain($codedom,'primary');
                   8188:             unless ($chome eq 'no_host') {
                   8189:                 push(@homeservers,$chome);
                   8190:             }
                   8191:         }
1.521     raeburn  8192:     } else {
1.772     raeburn  8193:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8194:     }
1.793     albertel 8195:     foreach my $code (keys(%{$instcodes})) {
                   8196:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8197:     }
                   8198:     chop($courses);
1.772     raeburn  8199:     my $ok_response = 0;
                   8200:     my $response;
                   8201:     while (@homeservers > 0 && $ok_response == 0) {
                   8202:         my $server = shift(@homeservers); 
                   8203:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8204:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8205:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8206: 		split(/:/,$response);
1.772     raeburn  8207:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8208:             push(@{$codetitles},&str2array($codetitles_str));
                   8209:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8210:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8211:             $ok_response = 1;
                   8212:         }
                   8213:     }
                   8214:     if ($ok_response) {
1.521     raeburn  8215:         return 'ok';
1.772     raeburn  8216:     } else {
                   8217:         return $response;
1.521     raeburn  8218:     }
                   8219: }
                   8220: 
1.792     raeburn  8221: sub auto_instcode_defaults {
                   8222:     my ($domain,$returnhash,$code_order) = @_;
                   8223:     my @homeservers;
1.841     albertel 8224: 
                   8225:     my %servers = &get_servers($domain,'library');
                   8226:     foreach my $tryserver (keys(%servers)) {
                   8227: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8228: 	    push(@homeservers,$tryserver);
                   8229: 	}
1.792     raeburn  8230:     }
1.841     albertel 8231: 
1.792     raeburn  8232:     my $response;
1.841     albertel 8233:     foreach my $server (@homeservers) {
1.792     raeburn  8234:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8235:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8236: 	
                   8237: 	foreach my $pair (split(/\&/,$response)) {
                   8238: 	    my ($name,$value)=split(/\=/,$pair);
                   8239: 	    if ($name eq 'code_order') {
                   8240: 		@{$code_order} = split(/\&/,&unescape($value));
                   8241: 	    } else {
                   8242: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8243: 	    }
                   8244: 	}
                   8245: 	return 'ok';
1.792     raeburn  8246:     }
1.841     albertel 8247: 
                   8248:     return $response;
1.1003    raeburn  8249: }
                   8250: 
                   8251: sub auto_possible_instcodes {
1.1007    raeburn  8252:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8253:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8254:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8255:         return;
                   8256:     }
1.1003    raeburn  8257:     my (@homeservers,$uhome);
                   8258:     if (defined(&domain($domain,'primary'))) {
                   8259:         $uhome=&domain($domain,'primary');
                   8260:         push(@homeservers,&domain($domain,'primary'));
                   8261:     } else {
                   8262:         my %servers = &get_servers($domain,'library');
                   8263:         foreach my $tryserver (keys(%servers)) {
                   8264:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8265:                 push(@homeservers,$tryserver);
                   8266:             }
                   8267:         }
                   8268:     }
                   8269:     my $response;
                   8270:     foreach my $server (@homeservers) {
                   8271:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8272:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8273:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8274:             split(':',$response);
                   8275:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8276:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8277:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8278:             my ($name,$value)=split('=',$item);
                   8279:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8280:         }
                   8281:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8282:             my ($name,$value)=split('=',$item);
                   8283:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8284:         }
                   8285:         return 'ok';
                   8286:     }
                   8287:     return $response;
                   8288: }
1.792     raeburn  8289: 
1.1010    raeburn  8290: sub auto_courserequest_checks {
                   8291:     my ($dom) = @_;
1.1020    raeburn  8292:     my ($homeserver,%validations);
                   8293:     if ($dom =~ /^$match_domain$/) {
                   8294:         $homeserver = &domain($dom,'primary');
                   8295:     }
                   8296:     unless ($homeserver eq 'no_host') {
                   8297:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8298:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8299:             my @items = split(/&/,$response);
                   8300:             foreach my $item (@items) {
                   8301:                 my ($key,$value) = split('=',$item);
                   8302:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8303:             }
                   8304:         }
                   8305:     }
1.1010    raeburn  8306:     return %validations; 
                   8307: }
                   8308: 
1.1020    raeburn  8309: sub auto_courserequest_validation {
1.1255    raeburn  8310:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8311:     my ($homeserver,$response);
                   8312:     if ($dom =~ /^$match_domain$/) {
                   8313:         $homeserver = &domain($dom,'primary');
                   8314:     }
1.1255    raeburn  8315:     unless ($homeserver eq 'no_host') {
                   8316:         my $customdata;
                   8317:         if (ref($custominfo) eq 'HASH') {
                   8318:             $customdata = &freeze_escape($custominfo);
                   8319:         }
1.1020    raeburn  8320:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8321:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  8322:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8323:                                     $customdata,$homeserver));
1.1020    raeburn  8324:     }
                   8325:     return $response;
                   8326: }
                   8327: 
1.777     albertel 8328: sub auto_validate_class_sec {
1.918     raeburn  8329:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8330:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8331:     my $ownerlist;
                   8332:     if (ref($owners) eq 'ARRAY') {
                   8333:         $ownerlist = join(',',@{$owners});
                   8334:     } else {
                   8335:         $ownerlist = $owners;
                   8336:     }
1.773     raeburn  8337:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8338:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8339:     return $response;
                   8340: }
                   8341: 
1.1248    raeburn  8342: sub auto_crsreq_update {
                   8343:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  8344:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  8345:     my ($homeserver,%crsreqresponse);
                   8346:     if ($cdom =~ /^$match_domain$/) {
                   8347:         $homeserver = &domain($cdom,'primary');
                   8348:     }
                   8349:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8350:         my $info;
                   8351:         if (ref($inbound) eq 'HASH') {
                   8352:             $info = &freeze_escape($inbound);
                   8353:         }
                   8354:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8355:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8356:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  8357:                             &escape($title).':'.&escape($code).':'.
                   8358:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   8359:                             $homeserver);
1.1248    raeburn  8360:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8361:             my @items = split(/&/,$response);
                   8362:             foreach my $item (@items) {
                   8363:                 my ($key,$value) = split('=',$item);
                   8364:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8365:             }
                   8366:         }
                   8367:     }
                   8368:     return \%crsreqresponse;
                   8369: }
                   8370: 
1.1305    raeburn  8371: sub auto_export_grades {
1.1309    raeburn  8372:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8373:     my ($homeserver,%exportresponse);
                   8374:     if ($cdom =~ /^$match_domain$/) {
                   8375:         $homeserver = &domain($cdom,'primary');
                   8376:     }
                   8377:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8378:         my $info;
                   8379:         if (ref($inforef) eq 'HASH') {
                   8380:             $info = &freeze_escape($inforef);
                   8381:         }
                   8382:         if (ref($gradesref) eq 'HASH') {
                   8383:             my $grades = &freeze_escape($gradesref);
                   8384:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   8385:                                 $info.':'.$grades,$homeserver);
                   8386:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   8387:                 my @items = split(/&/,$response);
                   8388:                 foreach my $item (@items) {
                   8389:                     my ($key,$value) = split('=',$item);
                   8390:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   8391:                 }
                   8392:             }
                   8393:         }
                   8394:     }
                   8395:     return \%exportresponse;
1.1305    raeburn  8396: }
                   8397: 
1.1287    raeburn  8398: sub check_instcode_cloning {
                   8399:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8400:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8401:         return;
                   8402:     }
                   8403:     my $canclone;
                   8404:     if (@{$code_order} > 0) {
                   8405:         my $instcoderegexp ='^';
                   8406:         my @clonecodes = split(/\&/,$cloner);
                   8407:         foreach my $item (@{$code_order}) {
                   8408:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8409:                 foreach my $pair (@clonecodes) {
                   8410:                     my ($key,$val) = split(/\=/,$pair,2);
                   8411:                     $val = &unescape($val);
                   8412:                     if ($key eq $item) {
                   8413:                         $instcoderegexp .= '('.$val.')';
                   8414:                         last;
                   8415:                     }
                   8416:                 }
                   8417:             } else {
                   8418:                 $instcoderegexp .= $codedefaults->{$item};
                   8419:             }
                   8420:         }
                   8421:         $instcoderegexp .= '$';
                   8422:         my (@from,@to);
                   8423:         eval {
                   8424:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8425:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8426:         };
                   8427:         if ((@from > 0) && (@to > 0)) {
                   8428:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8429:             if (!@diffs) {
                   8430:                 $canclone = 1;
                   8431:             }
                   8432:         }
                   8433:     }
                   8434:     return $canclone;
                   8435: }
                   8436: 
                   8437: sub default_instcode_cloning {
                   8438:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8439:     my (%codedefaults,@code_order,$canclone);
                   8440:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8441:         %codedefaults = %{$codedefaultsref};
                   8442:         @code_order = @{$codeorderref};
                   8443:     } elsif ($clonedom) {
                   8444:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8445:     }
                   8446:     if (($domdefclone) && (@code_order)) {
                   8447:         my @clonecodes = split(/\+/,$domdefclone);
                   8448:         my $instcoderegexp ='^';
                   8449:         foreach my $item (@code_order) {
                   8450:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8451:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8452:             } else {
                   8453:                 $instcoderegexp .= $codedefaults{$item};
                   8454:             }
                   8455:         }
                   8456:         $instcoderegexp .= '$';
                   8457:         my (@from,@to);
                   8458:         eval {
                   8459:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8460:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8461:         };
                   8462:         if ((@from > 0) && (@to > 0)) {
                   8463:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8464:             if (!@diffs) {
                   8465:                 $canclone = 1;
                   8466:             }
                   8467:         }
                   8468:     }
                   8469:     return $canclone;
                   8470: }
                   8471: 
1.679     raeburn  8472: # ------------------------------------------------------- Course Group routines
                   8473: 
                   8474: sub get_coursegroups {
1.809     raeburn  8475:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8476:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8477: }
                   8478: 
1.679     raeburn  8479: sub modify_coursegroup {
                   8480:     my ($cdom,$cnum,$groupsettings) = @_;
                   8481:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8482: }
                   8483: 
1.809     raeburn  8484: sub toggle_coursegroup_status {
                   8485:     my ($cdom,$cnum,$group,$action) = @_;
                   8486:     my ($from_namespace,$to_namespace);
                   8487:     if ($action eq 'delete') {
                   8488:         $from_namespace = 'coursegroups';
                   8489:         $to_namespace = 'deleted_groups';
                   8490:     } else {
                   8491:         $from_namespace = 'deleted_groups';
                   8492:         $to_namespace = 'coursegroups';
                   8493:     }
                   8494:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8495:     if (my $tmp = &error(%curr_group)) {
                   8496:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8497:         return ('read error',$tmp);
                   8498:     } else {
                   8499:         my %savedsettings = %curr_group; 
1.809     raeburn  8500:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8501:         my $deloutcome;
                   8502:         if ($result eq 'ok') {
1.809     raeburn  8503:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8504:         } else {
                   8505:             return ('write error',$result);
                   8506:         }
                   8507:         if ($deloutcome eq 'ok') {
                   8508:             return 'ok';
                   8509:         } else {
                   8510:             return ('delete error',$deloutcome);
                   8511:         }
                   8512:     }
                   8513: }
                   8514: 
1.679     raeburn  8515: sub modify_group_roles {
1.957     raeburn  8516:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8517:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8518:     my $role = 'gr/'.&escape($userprivs);
                   8519:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8520:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8521:     if ($result eq 'ok') {
                   8522:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8523:     }
1.679     raeburn  8524:     return $result;
                   8525: }
                   8526: 
                   8527: sub modify_coursegroup_membership {
                   8528:     my ($cdom,$cnum,$membership) = @_;
                   8529:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8530:     return $result;
                   8531: }
                   8532: 
1.682     raeburn  8533: sub get_active_groups {
                   8534:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8535:     my $now = time;
                   8536:     my %groups = ();
                   8537:     foreach my $key (keys(%env)) {
1.811     albertel 8538:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8539:             my ($start,$end) = split(/\./,$env{$key});
                   8540:             if (($end!=0) && ($end<$now)) { next; }
                   8541:             if (($start!=0) && ($start>$now)) { next; }
                   8542:             if ($1 eq $cdom && $2 eq $cnum) {
                   8543:                 $groups{$3} = $env{$key} ;
                   8544:             }
                   8545:         }
                   8546:     }
                   8547:     return %groups;
                   8548: }
                   8549: 
1.683     raeburn  8550: sub get_group_membership {
                   8551:     my ($cdom,$cnum,$group) = @_;
                   8552:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8553: }
                   8554: 
                   8555: sub get_users_groups {
                   8556:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8557:     my @usersgroups;
1.683     raeburn  8558:     my $cachetime=1800;
                   8559: 
                   8560:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8561:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8562:     if (defined($cached)) {
1.734     albertel 8563:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8564:     } else {  
                   8565:         $grouplist = '';
1.816     raeburn  8566:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8567:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8568:         my $access_end = $env{'course.'.$courseid.
                   8569:                               '.default_enrollment_end_date'};
                   8570:         my $now = time;
                   8571:         foreach my $key (keys(%roleshash)) {
                   8572:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8573:                 my $group = $1;
                   8574:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8575:                     my $start = $2;
                   8576:                     my $end = $1;
                   8577:                     if ($start == -1) { next; } # deleted from group
                   8578:                     if (($start!=0) && ($start>$now)) { next; }
                   8579:                     if (($end!=0) && ($end<$now)) {
                   8580:                         if ($access_end && $access_end < $now) {
                   8581:                             if ($access_end - $end < 86400) {
                   8582:                                 push(@usersgroups,$group);
1.733     raeburn  8583:                             }
                   8584:                         }
1.817     raeburn  8585:                         next;
1.733     raeburn  8586:                     }
1.817     raeburn  8587:                     push(@usersgroups,$group);
1.683     raeburn  8588:                 }
                   8589:             }
                   8590:         }
1.817     raeburn  8591:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8592:         $grouplist = join(':',@usersgroups);
                   8593:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8594:     }
1.733     raeburn  8595:     return @usersgroups;
1.683     raeburn  8596: }
                   8597: 
                   8598: sub devalidate_getgroups_cache {
                   8599:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8600:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8601: 
1.683     raeburn  8602:     my $hashid="$udom:$uname:$courseid";
                   8603:     &devalidate_cache_new('getgroups',$hashid);
                   8604: }
                   8605: 
1.12      www      8606: # ------------------------------------------------------------------ Plain Text
                   8607: 
                   8608: sub plaintext {
1.988     raeburn  8609:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8610:     if ($short =~ m{^cr/}) {
1.758     albertel 8611: 	return (split('/',$short))[-1];
                   8612:     }
1.742     raeburn  8613:     if (!defined($cid)) {
                   8614:         $cid = $env{'request.course.id'};
                   8615:     }
                   8616:     my %rolenames = (
1.1008    raeburn  8617:                       Course    => 'std',
                   8618:                       Community => 'alt1',
1.1305    raeburn  8619:                       Placement => 'std',
1.742     raeburn  8620:                     );
1.1037    raeburn  8621:     if ($cid ne '') {
                   8622:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8623:             unless ($forcedefault) {
                   8624:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8625:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8626:                 return &Apache::lonlocal::mt($roletext);
                   8627:             }
                   8628:         }
                   8629:     }
                   8630:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8631:         (defined($rolenames{$type})) && 
                   8632:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8633:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8634:     } elsif ($cid ne '') {
                   8635:         my $crstype = $env{'course.'.$cid.'.type'};
                   8636:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8637:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8638:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8639:         }
1.742     raeburn  8640:     }
1.1037    raeburn  8641:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8642: }
                   8643: 
                   8644: # ----------------------------------------------------------------- Assign Role
                   8645: 
                   8646: sub assignrole {
1.957     raeburn  8647:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8648:         $context)=@_;
1.21      www      8649:     my $mrole;
                   8650:     if ($role =~ /^cr\//) {
1.393     www      8651:         my $cwosec=$url;
1.811     albertel 8652:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8653: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8654:            my $refused = 1;
                   8655:            if ($context eq 'requestcourses') {
                   8656:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8657:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8658:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8659:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8660:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8661:                            if ($crsenv{'internal.courseowner'} eq
                   8662:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8663:                                $refused = '';
                   8664:                            }
                   8665:                        }
                   8666:                    }
                   8667:                }
                   8668:            }
                   8669:            if ($refused) {
                   8670:                &logthis('Refused custom assignrole: '.
                   8671:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8672:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8673:                return 'refused';
                   8674:            }
1.104     www      8675:         }
1.21      www      8676:         $mrole='cr';
1.678     raeburn  8677:     } elsif ($role =~ /^gr\//) {
                   8678:         my $cwogrp=$url;
1.811     albertel 8679:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8680:         unless (&allowed('mdg',$cwogrp)) {
                   8681:             &logthis('Refused group assignrole: '.
                   8682:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8683:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8684:             return 'refused';
                   8685:         }
                   8686:         $mrole='gr';
1.21      www      8687:     } else {
1.82      www      8688:         my $cwosec=$url;
1.811     albertel 8689:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8690:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8691:             my $refused;
                   8692:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8693:                 if (!(&allowed('c'.$role,$url))) {
                   8694:                     $refused = 1;
                   8695:                 }
                   8696:             } else {
                   8697:                 $refused = 1;
                   8698:             }
1.947     raeburn  8699:             if ($refused) {
1.1045    raeburn  8700:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8701:                 if (!$selfenroll && $context eq 'course') {
                   8702:                     my %crsenv;
                   8703:                     if ($role eq 'cc' || $role eq 'co') {
                   8704:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8705:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8706:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8707:                                 if ($crsenv{'internal.courseowner'} eq 
                   8708:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8709:                                     $refused = '';
                   8710:                                 }
                   8711:                             }
                   8712:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8713:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8714:                                 if ($crsenv{'internal.courseowner'} eq 
                   8715:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8716:                                     $refused = '';
                   8717:                                 }
                   8718:                             }
                   8719:                         }
                   8720:                     }
                   8721:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8722:                     $refused = '';
1.1017    raeburn  8723:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8724:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8725:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8726:                         my $wrongcc;
                   8727:                         if ($cnum =~ /^$match_community$/) {
                   8728:                             $wrongcc = 1 if ($role eq 'cc');
                   8729:                         } else {
                   8730:                             $wrongcc = 1 if ($role eq 'co');
                   8731:                         }
                   8732:                         unless ($wrongcc) {
                   8733:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8734:                             if ($crsenv{'internal.courseowner'} eq 
                   8735:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8736:                                 $refused = '';
                   8737:                             }
1.1017    raeburn  8738:                         }
                   8739:                     }
1.1183    raeburn  8740:                 } elsif ($context eq 'requestauthor') {
                   8741:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   8742:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8743:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8744:                             $refused = '';
                   8745:                         } else {
                   8746:                             my %domdefaults = &get_domain_defaults($udom);
                   8747:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8748:                                 my $checkbystatus;
                   8749:                                 if ($env{'user.adv'}) { 
                   8750:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8751:                                     if ($disposition eq 'automatic') {
                   8752:                                         $refused = '';
                   8753:                                     } elsif ($disposition eq '') {
                   8754:                                         $checkbystatus = 1;
                   8755:                                     } 
                   8756:                                 } else {
                   8757:                                     $checkbystatus = 1;
                   8758:                                 }
                   8759:                                 if ($checkbystatus) {
                   8760:                                     if ($env{'environment.inststatus'}) {
                   8761:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8762:                                         foreach my $type (@inststatuses) {
                   8763:                                             if (($type ne '') &&
                   8764:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8765:                                                 $refused = '';
                   8766:                                             }
                   8767:                                         }
                   8768:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8769:                                         $refused = '';
                   8770:                                     }
                   8771:                                 }
                   8772:                             }
                   8773:                         }
                   8774:                     }
1.1017    raeburn  8775:                 }
                   8776:                 if ($refused) {
1.947     raeburn  8777:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8778:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8779: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8780:                     return 'refused';
                   8781:                 }
1.932     raeburn  8782:             }
1.1131    raeburn  8783:         } elsif ($role eq 'au') {
                   8784:             if ($url ne '/'.$udom.'/') {
                   8785:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8786:                          ' to assign author role for '.$uname.':'.$udom.
                   8787:                          ' in domain: '.$url.' refused (wrong domain).');
                   8788:                 return 'refused';
                   8789:             }
1.104     www      8790:         }
1.21      www      8791:         $mrole=$role;
                   8792:     }
1.620     albertel 8793:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8794:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8795:     if ($end) { $command.='_'.$end; }
1.21      www      8796:     if ($start) {
                   8797: 	if ($end) { 
1.81      www      8798:            $command.='_'.$start; 
1.21      www      8799:         } else {
1.81      www      8800:            $command.='_0_'.$start;
1.21      www      8801:         }
                   8802:     }
1.739     raeburn  8803:     my $origstart = $start;
                   8804:     my $origend = $end;
1.957     raeburn  8805:     my $delflag;
1.357     www      8806: # actually delete
                   8807:     if ($deleteflag) {
1.373     www      8808: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8809: # modify command to delete the role
1.620     albertel 8810:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8811:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8812: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8813: # set start and finish to negative values for userrolelog
                   8814:            $start=-1;
                   8815:            $end=-1;
1.957     raeburn  8816:            $delflag = 1;
1.357     www      8817:         }
                   8818:     }
                   8819: # send command
1.349     www      8820:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8821: # log new user role if status is ok
1.349     www      8822:     if ($answer eq 'ok') {
1.663     raeburn  8823: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  8824:         if (($role eq 'cc') || ($role eq 'in') ||
                   8825:             ($role eq 'ep') || ($role eq 'ad') ||
                   8826:             ($role eq 'ta') || ($role eq 'st') ||
                   8827:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8828:             ($role eq 'co')) {
1.1200    raeburn  8829: # for course roles, perform group memberships changes triggered by role change.
                   8830:             unless ($role =~ /^gr/) {
                   8831:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8832:                                                  $origstart,$selfenroll,$context);
                   8833:             }
1.1184    raeburn  8834:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8835:                            $selfenroll,$context);
                   8836:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8837:                  ($role eq 'au') || ($role eq 'dc')) {
                   8838:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8839:                            $context);
                   8840:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8841:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8842:                              $context); 
                   8843:         }
1.1053    raeburn  8844:         if ($role eq 'cc') {
                   8845:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8846:         }
1.349     www      8847:     }
                   8848:     return $answer;
1.169     harris41 8849: }
                   8850: 
1.1053    raeburn  8851: sub autoupdate_coowners {
                   8852:     my ($url,$end,$start,$uname,$udom) = @_;
                   8853:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8854:     if (($cdom ne '') && ($cnum ne '')) {
                   8855:         my $now = time;
                   8856:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8857:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8858:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8859:             my $instcode = $coursehash{'internal.coursecode'};
                   8860:             if ($instcode ne '') {
1.1056    raeburn  8861:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8862:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8863:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8864:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8865:                         if ($result eq 'valid') {
                   8866:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8867:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8868:                                     push(@newcoowners,$coowner);
                   8869:                                 }
                   8870:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8871:                                     push(@newcoowners,$uname.':'.$udom);
                   8872:                                 }
                   8873:                                 @newcoowners = sort(@newcoowners);
                   8874:                             } else {
                   8875:                                 push(@newcoowners,$uname.':'.$udom);
                   8876:                             }
                   8877:                         } else {
                   8878:                             if ($coursehash{'internal.co-owners'}) {
                   8879:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8880:                                     unless ($coowner eq $uname.':'.$udom) {
                   8881:                                         push(@newcoowners,$coowner);
                   8882:                                     }
                   8883:                                 }
                   8884:                                 unless (@newcoowners > 0) {
                   8885:                                     $delcoowners = 1;
                   8886:                                     $coowners = '';
                   8887:                                 }
                   8888:                             }
                   8889:                         }
                   8890:                         if (@newcoowners || $delcoowners) {
                   8891:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8892:                                             $delcoowners,@newcoowners);
                   8893:                         }
                   8894:                     }
                   8895:                 }
                   8896:             }
                   8897:         }
                   8898:     }
                   8899: }
                   8900: 
                   8901: sub store_coowners {
                   8902:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8903:     my $cid = $cdom.'_'.$cnum;
                   8904:     my ($coowners,$delresult,$putresult);
                   8905:     if (@newcoowners) {
                   8906:         $coowners = join(',',@newcoowners);
                   8907:         my %coownershash = (
                   8908:                             'internal.co-owners' => $coowners,
                   8909:                            );
                   8910:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8911:         if ($putresult eq 'ok') {
                   8912:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8913:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8914:             }
                   8915:         }
                   8916:     }
                   8917:     if ($delcoowners) {
                   8918:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8919:         if ($delresult eq 'ok') {
                   8920:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8921:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8922:             }
                   8923:         }
                   8924:     }
                   8925:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8926:         my %crsinfo =
                   8927:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8928:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8929:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8930:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8931:         }
                   8932:     }
                   8933: }
                   8934: 
1.169     harris41 8935: # -------------------------------------------------- Modify user authentication
1.197     www      8936: # Overrides without validation
                   8937: 
1.169     harris41 8938: sub modifyuserauth {
                   8939:     my ($udom,$uname,$umode,$upass)=@_;
                   8940:     my $uhome=&homeserver($uname,$udom);
1.197     www      8941:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8942:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8943:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8944:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8945:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8946: 		     &escape($upass),$uhome);
1.620     albertel 8947:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8948:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8949:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8950:     &log($udom,,$uname,$uhome,
1.620     albertel 8951:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8952:                                      $env{'user.name'}.', '.$umode.
1.197     www      8953:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8954:     unless ($reply eq 'ok') {
1.197     www      8955:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8956: 	return 'error: '.$reply;
                   8957:     }   
1.170     harris41 8958:     return 'ok';
1.80      www      8959: }
                   8960: 
1.81      www      8961: # --------------------------------------------------------------- Modify a user
1.80      www      8962: 
1.81      www      8963: sub modifyuser {
1.206     matthew  8964:     my ($udom,    $uname, $uid,
                   8965:         $umode,   $upass, $first,
                   8966:         $middle,  $last,  $gene,
1.1058    raeburn  8967:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8968:     $udom= &LONCAPA::clean_domain($udom);
                   8969:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8970:     my $showcandelete = 'none';
                   8971:     if (ref($candelete) eq 'ARRAY') {
                   8972:         if (@{$candelete} > 0) {
                   8973:             $showcandelete = join(', ',@{$candelete});
                   8974:         }
                   8975:     }
1.81      www      8976:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8977:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8978: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8979:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8980:                                      ' desiredhome not specified'). 
1.620     albertel 8981:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8982:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8983:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8984:     my $newuser;
                   8985:     if ($uhome eq 'no_host') {
                   8986:         $newuser = 1;
                   8987:     }
1.80      www      8988: # ----------------------------------------------------------------- Create User
1.406     albertel 8989:     if (($uhome eq 'no_host') && 
                   8990: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8991:         my $unhome='';
1.844     albertel 8992:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8993:             $unhome = $desiredhome;
1.620     albertel 8994: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8995: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8996:         } else { # load balancing routine for determining $unhome
1.81      www      8997:             my $loadm=10000000;
1.841     albertel 8998: 	    my %servers = &get_servers($udom,'library');
                   8999: 	    foreach my $tryserver (keys(%servers)) {
                   9000: 		my $answer=reply('load',$tryserver);
                   9001: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9002: 		    $loadm=$answer;
                   9003: 		    $unhome=$tryserver;
                   9004: 		}
1.80      www      9005: 	    }
                   9006:         }
                   9007:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9008: 	    return 'error: unable to find a home server for '.$uname.
                   9009:                    ' in domain '.$udom;
1.80      www      9010:         }
                   9011:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9012:                          &escape($upass),$unhome);
                   9013: 	unless ($reply eq 'ok') {
                   9014:             return 'error: '.$reply;
                   9015:         }   
1.230     stredwic 9016:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9017:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9018: 	    return 'error: unable verify users home machine.';
1.80      www      9019:         }
1.209     matthew  9020:     }   # End of creation of new user
1.80      www      9021: # ---------------------------------------------------------------------- Add ID
                   9022:     if ($uid) {
                   9023:        $uid=~tr/A-Z/a-z/;
                   9024:        my %uidhash=&idrget($udom,$uname);
1.196     www      9025:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9026:          && (!$forceid)) {
1.80      www      9027: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9028: 	      return 'error: user id "'.$uid.'" does not match '.
                   9029:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9030:           }
                   9031:        } else {
1.1300    raeburn  9032: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      9033:        }
                   9034:     }
                   9035: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9036:     my @tmp=&get('environment',
1.899     raeburn  9037: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9038:                     'permanentemail','inststatus'],
1.134     albertel 9039: 		   $udom,$uname);
1.1075    raeburn  9040:     my (%names,%oldnames);
1.313     matthew  9041:     if ($tmp[0] =~ m/^error:.*/) { 
                   9042:         %names=(); 
                   9043:     } else {
                   9044:         %names = @tmp;
1.1075    raeburn  9045:         %oldnames = %names;
1.313     matthew  9046:     }
1.388     www      9047: #
1.1058    raeburn  9048: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9049: # of users did not contain them), do not overwrite existing values
                   9050: # unless field is in $candelete array ref.  
                   9051: #
                   9052: 
                   9053:     my @fields = ('firstname','middlename','lastname','generation',
                   9054:                   'permanentemail','id');
                   9055:     my %newvalues;
                   9056:     if (ref($candelete) eq 'ARRAY') {
                   9057:         foreach my $field (@fields) {
                   9058:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9059:                 if ($field eq 'firstname') {
                   9060:                     $names{$field} = $first;
                   9061:                 } elsif ($field eq 'middlename') {
                   9062:                     $names{$field} = $middle;
                   9063:                 } elsif ($field eq 'lastname') {
                   9064:                     $names{$field} = $last;
                   9065:                 } elsif ($field eq 'generation') { 
                   9066:                     $names{$field} = $gene;
                   9067:                 } elsif ($field eq 'permanentemail') {
                   9068:                     $names{$field} = $email;
                   9069:                 } elsif ($field eq 'id') {
                   9070:                     $names{$field}  = $uid;
                   9071:                 }
                   9072:             }
                   9073:         }
                   9074:     }
1.388     www      9075:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9076:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9077:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9078:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9079:     if ($email) {
                   9080:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9081:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9082:     }
1.899     raeburn  9083:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9084:     if (defined($inststatus)) {
                   9085:         $names{'inststatus'} = '';
                   9086:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9087:         if (ref($usertypes) eq 'HASH') {
                   9088:             my @okstatuses; 
                   9089:             foreach my $item (split(/:/,$inststatus)) {
                   9090:                 if (defined($usertypes->{$item})) {
                   9091:                     push(@okstatuses,$item);  
                   9092:                 }
                   9093:             }
                   9094:             if (@okstatuses) {
                   9095:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9096:             }
                   9097:         }
                   9098:     }
1.1075    raeburn  9099:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9100:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9101:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9102:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9103:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9104:     } else {
                   9105:         $logmsg .= ' during self creation';
                   9106:     }
1.1075    raeburn  9107:     my $changed;
                   9108:     if ($newuser) {
                   9109:         $changed = 1;
                   9110:     } else {
                   9111:         foreach my $field (@fields) {
                   9112:             if ($names{$field} ne $oldnames{$field}) {
                   9113:                 $changed = 1;
                   9114:                 last;
                   9115:             }
                   9116:         }
                   9117:     }
                   9118:     unless ($changed) {
                   9119:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9120:         &logthis($logmsg);
                   9121:         return 'ok';
                   9122:     }
                   9123:     my $reply = &put('environment', \%names, $udom,$uname);
                   9124:     if ($reply ne 'ok') { 
                   9125:         return 'error: '.$reply;
                   9126:     }
1.1087    raeburn  9127:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9128:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9129:     }
1.1075    raeburn  9130:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9131:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9132:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9133:     &logthis($logmsg);
1.134     albertel 9134:     return 'ok';
1.80      www      9135: }
                   9136: 
1.81      www      9137: # -------------------------------------------------------------- Modify student
1.80      www      9138: 
1.81      www      9139: sub modifystudent {
                   9140:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9141:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  9142:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9143:     if (!$cid) {
1.620     albertel 9144: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9145: 	    return 'not_in_class';
                   9146: 	}
1.80      www      9147:     }
                   9148: # --------------------------------------------------------------- Make the user
1.81      www      9149:     my $reply=&modifyuser
1.209     matthew  9150: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9151:          $desiredhome,$email,$inststatus);
1.80      www      9152:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9153:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  9154:     # student's environment
1.297     matthew  9155:     $uid = undef if (!$forceid);
1.455     albertel 9156:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  9157:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  9158:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9159:     return $reply;
                   9160: }
                   9161: 
                   9162: sub modify_student_enrollment {
1.1216    raeburn  9163:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  9164:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9165:     my ($cdom,$cnum,$chome);
                   9166:     if (!$cid) {
1.620     albertel 9167: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9168: 	    return 'not_in_class';
                   9169: 	}
1.620     albertel 9170: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9171: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9172:     } else {
                   9173: 	($cdom,$cnum)=split(/_/,$cid);
                   9174:     }
1.620     albertel 9175:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9176:     if (!$chome) {
1.457     raeburn  9177: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9178:     }
1.455     albertel 9179:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9180:     # Make sure the user exists
1.81      www      9181:     my $uhome=&homeserver($uname,$udom);
                   9182:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9183: 	return 'error: no such user';
                   9184:     }
1.297     matthew  9185:     # Get student data if we were not given enough information
                   9186:     if (!defined($first)  || $first  eq '' || 
                   9187:         !defined($last)   || $last   eq '' || 
                   9188:         !defined($uid)    || $uid    eq '' || 
                   9189:         !defined($middle) || $middle eq '' || 
                   9190:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9191:         # They did not supply us with enough data to enroll the student, so
                   9192:         # we need to pick up more information.
1.297     matthew  9193:         my %tmp = &get('environment',
1.294     matthew  9194:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9195:                        ,$udom,$uname);
                   9196: 
1.800     albertel 9197:         #foreach my $key (keys(%tmp)) {
                   9198:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9199:         #}
1.294     matthew  9200:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9201:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9202:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9203:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9204:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9205:     }
1.556     albertel 9206:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9207:     my $user = "$uname:$udom";
                   9208:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9209:     my $reply=cput('classlist',
1.1148    raeburn  9210: 		   {$user => 
1.1314    raeburn  9211: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9212: 		   $cdom,$cnum);
1.1148    raeburn  9213:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9214:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9215:     } else { 
1.81      www      9216: 	return 'error: '.$reply;
                   9217:     }
1.297     matthew  9218:     # Add student role to user
1.83      www      9219:     my $uurl='/'.$cid;
1.81      www      9220:     $uurl=~s/\_/\//g;
                   9221:     if ($usec) {
                   9222: 	$uurl.='/'.$usec;
                   9223:     }
1.1148    raeburn  9224:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9225:                              $selfenroll,$context);
                   9226:     if ($result ne 'ok') {
                   9227:         if ($old_entry{$user} ne '') {
                   9228:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9229:         } else {
                   9230:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9231:         }
                   9232:     }
                   9233:     return $result; 
1.21      www      9234: }
                   9235: 
1.556     albertel 9236: sub format_name {
                   9237:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9238:     my $name;
                   9239:     if ($first ne 'lastname') {
                   9240: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9241:     } else {
                   9242: 	if ($lastname=~/\S/) {
                   9243: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9244: 	    $name=~s/\s+,/,/;
                   9245: 	} else {
                   9246: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9247: 	}
                   9248:     }
                   9249:     $name=~s/^\s+//;
                   9250:     $name=~s/\s+$//;
                   9251:     $name=~s/\s+/ /g;
                   9252:     return $name;
                   9253: }
                   9254: 
1.84      www      9255: # ------------------------------------------------- Write to course preferences
                   9256: 
                   9257: sub writecoursepref {
                   9258:     my ($courseid,%prefs)=@_;
                   9259:     $courseid=~s/^\///;
                   9260:     $courseid=~s/\_/\//g;
                   9261:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9262:     my $chome=homeserver($cnum,$cdomain);
                   9263:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9264: 	return 'error: no such course';
                   9265:     }
                   9266:     my $cstring='';
1.800     albertel 9267:     foreach my $pref (keys(%prefs)) {
                   9268: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9269:     }
1.84      www      9270:     $cstring=~s/\&$//;
                   9271:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9272: }
                   9273: 
                   9274: # ---------------------------------------------------------- Make/modify course
                   9275: 
                   9276: sub createcourse {
1.741     raeburn  9277:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9278:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9279:     $url=&declutter($url);
                   9280:     my $cid='';
1.1028    raeburn  9281:     if ($context eq 'requestcourses') {
                   9282:         my $can_create = 0;
                   9283:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9284:         if ($udom eq $ownerdom) {
                   9285:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9286:                                   $context)) {
                   9287:                 $can_create = 1;
                   9288:             }
                   9289:         } else {
                   9290:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9291:                                            $category);
                   9292:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9293:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9294:                 if (@curr > 0) {
                   9295:                     my @options = qw(approval validate autolimit);
                   9296:                     my $optregex = join('|',@options);
                   9297:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9298:                         $can_create = 1;
                   9299:                     }
                   9300:                 }
                   9301:             }
                   9302:         }
                   9303:         if ($can_create) {
                   9304:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9305:                 unless (&allowed('ccc',$udom)) {
                   9306:                     return 'refused'; 
                   9307:                 }
1.1017    raeburn  9308:             }
                   9309:         } else {
                   9310:             return 'refused';
                   9311:         }
1.1028    raeburn  9312:     } elsif (!&allowed('ccc',$udom)) {
                   9313:         return 'refused';
1.84      www      9314:     }
1.1011    raeburn  9315: # --------------------------------------------------------------- Get Unique ID
                   9316:     my $uname;
                   9317:     if ($cnum =~ /^$match_courseid$/) {
                   9318:         my $chome=&homeserver($cnum,$udom,'true');
                   9319:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9320:             $uname = $cnum;
                   9321:         } else {
1.1038    raeburn  9322:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9323:         }
                   9324:     } else {
1.1038    raeburn  9325:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9326:     }
                   9327:     return $uname if ($uname =~ /^error/);
                   9328: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9329:     if (!defined($course_server)) {
                   9330:         if (defined(&domain($udom,'primary'))) {
                   9331:             $course_server = &domain($udom,'primary');
                   9332:         } else {
                   9333:             $course_server = $env{'user.home'}; 
                   9334:         }
                   9335:     }
                   9336:     my %host_servers =
                   9337:         &Apache::lonnet::get_servers($udom,'library');
                   9338:     unless ($host_servers{$course_server}) {
                   9339:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9340:     }
1.84      www      9341: # ------------------------------------------------------------- Make the course
                   9342:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9343:                       $course_server);
1.84      www      9344:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9345:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9346:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9347: 	return 'error: no such course';
                   9348:     }
1.271     www      9349: # ----------------------------------------------------------------- Course made
1.516     raeburn  9350: # log existence
1.1029    raeburn  9351:     my $now = time;
1.918     raeburn  9352:     my $newcourse = {
                   9353:                     $udom.'_'.$uname => {
1.921     raeburn  9354:                                      description => $description,
                   9355:                                      inst_code   => $inst_code,
                   9356:                                      owner       => $course_owner,
                   9357:                                      type        => $crstype,
1.1029    raeburn  9358:                                      creator     => $env{'user.name'}.':'.
                   9359:                                                     $env{'user.domain'},
                   9360:                                      created     => $now,
                   9361:                                      context     => $context,
1.918     raeburn  9362:                                                 },
                   9363:                     };
1.921     raeburn  9364:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9365: # set toplevel url
1.271     www      9366:     my $topurl=$url;
                   9367:     unless ($nonstandard) {
                   9368: # ------------------------------------------ For standard courses, make top url
                   9369:         my $mapurl=&clutter($url);
1.278     www      9370:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9371:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9372: <map>
                   9373: <resource id="1" type="start"></resource>
                   9374: <resource id="2" src="$mapurl"></resource>
                   9375: <resource id="3" type="finish"></resource>
                   9376: <link index="1" from="1" to="2"></link>
                   9377: <link index="2" from="2" to="3"></link>
                   9378: </map>
                   9379: ENDINITMAP
                   9380:         $topurl=&declutter(
1.638     albertel 9381:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9382:                           );
                   9383:     }
                   9384: # ----------------------------------------------------------- Write preferences
1.84      www      9385:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9386:                      ('description'              => $description,
                   9387:                       'url'                      => $topurl,
                   9388:                       'internal.creator'         => $env{'user.name'}.':'.
                   9389:                                                     $env{'user.domain'},
                   9390:                       'internal.created'         => $now,
                   9391:                       'internal.creationcontext' => $context)
                   9392:                     );
1.84      www      9393:     return '/'.$udom.'/'.$uname;
                   9394: }
                   9395: 
1.1011    raeburn  9396: # ------------------------------------------------------------------- Create ID
                   9397: sub generate_coursenum {
1.1038    raeburn  9398:     my ($udom,$crstype) = @_;
1.1011    raeburn  9399:     my $domdesc = &domain($udom);
                   9400:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9401:     my $first;
                   9402:     if ($crstype eq 'Community') {
                   9403:         $first = '0';
                   9404:     } else {
                   9405:         $first = int(1+rand(9)); 
                   9406:     } 
                   9407:     my $uname=$first.
1.1011    raeburn  9408:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9409:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9410:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9411: # ----------------------------------------------- Make sure that does not exist
                   9412:     my $uhome=&homeserver($uname,$udom,'true');
                   9413:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9414:         if ($crstype eq 'Community') {
                   9415:             $first = '0';
                   9416:         } else {
                   9417:             $first = int(1+rand(9));
                   9418:         }
                   9419:         $uname=$first.
1.1011    raeburn  9420:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9421:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9422:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9423:         $uhome=&homeserver($uname,$udom,'true');
                   9424:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9425:             return 'error: unable to generate unique course-ID';
                   9426:         }
                   9427:     }
                   9428:     return $uname;
                   9429: }
                   9430: 
1.813     albertel 9431: sub is_course {
1.1167    droeschl 9432:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9433:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   9434: 
                   9435:     return unless $cdom and $cnum;
                   9436: 
                   9437:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   9438:         '.');
                   9439: 
1.1219    raeburn  9440:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 9441:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9442: }
                   9443: 
1.1015    raeburn  9444: sub store_userdata {
                   9445:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9446:     my $result;
1.1016    raeburn  9447:     if ($datakey ne '') {
1.1013    raeburn  9448:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9449:             if ($udom eq '' || $uname eq '') {
                   9450:                 $udom = $env{'user.domain'};
                   9451:                 $uname = $env{'user.name'};
                   9452:             }
                   9453:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9454:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9455:                 $result = 'error: no_host';
                   9456:             } else {
                   9457:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9458:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9459: 
                   9460:                 my $namevalue='';
                   9461:                 foreach my $key (keys(%{$storehash})) {
                   9462:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9463:                 }
                   9464:                 $namevalue=~s/\&$//;
1.1224    raeburn  9465:                 unless ($namespace eq 'courserequests') {
                   9466:                     $datakey = &escape($datakey);
                   9467:                 }
1.1105    raeburn  9468:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9469:                                   $namevalue,$uhome);
1.1013    raeburn  9470:             }
                   9471:         } else {
                   9472:             $result = 'error: data to store was not a hash reference'; 
                   9473:         }
                   9474:     } else {
                   9475:         $result= 'error: invalid requestkey'; 
                   9476:     }
                   9477:     return $result;
                   9478: }
                   9479: 
1.21      www      9480: # ---------------------------------------------------------- Assign Custom Role
                   9481: 
                   9482: sub assigncustomrole {
1.957     raeburn  9483:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9484:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9485:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9486: }
                   9487: 
                   9488: # ----------------------------------------------------------------- Revoke Role
                   9489: 
                   9490: sub revokerole {
1.957     raeburn  9491:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9492:     my $now=time;
1.965     raeburn  9493:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9494: }
                   9495: 
                   9496: # ---------------------------------------------------------- Revoke Custom Role
                   9497: 
                   9498: sub revokecustomrole {
1.957     raeburn  9499:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9500:     my $now=time;
1.357     www      9501:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9502:            $deleteflag,$selfenroll,$context);
1.17      www      9503: }
                   9504: 
1.533     banghart 9505: # ------------------------------------------------------------ Disk usage
1.535     albertel 9506: sub diskusage {
1.955     raeburn  9507:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9508:     $directorypath =~ s/\/$//;
                   9509:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9510:                        .&escape($getpropath).':'.&escape($uname).':'
                   9511:                        .&escape($udom),homeserver($uname,$udom));
                   9512:     if ($listing eq 'unknown_cmd') {
                   9513:         if ($getpropath) {
                   9514:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9515:         }
                   9516:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9517:     }
1.514     albertel 9518:     return $listing;
1.512     banghart 9519: }
                   9520: 
1.566     banghart 9521: sub is_locked {
1.1096    raeburn  9522:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9523:     my @check;
                   9524:     my $is_locked;
1.1093    raeburn  9525:     push (@check,$file_name);
1.613     albertel 9526:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9527: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9528:     my ($tmp)=keys(%locked);
                   9529:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9530:     
1.566     banghart 9531:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9532:         $is_locked = 'false';
                   9533:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9534:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9535:                $is_locked = 'true';
1.1096    raeburn  9536:                if (ref($which) eq 'ARRAY') {
                   9537:                    push(@{$which},$entry);
                   9538:                } else {
                   9539:                    last;
                   9540:                }
1.745     raeburn  9541:            }
                   9542:        }
1.566     banghart 9543:     } else {
                   9544:         $is_locked = 'false';
                   9545:     }
1.1093    raeburn  9546:     return $is_locked;
1.566     banghart 9547: }
                   9548: 
1.759     albertel 9549: sub declutter_portfile {
                   9550:     my ($file) = @_;
1.833     albertel 9551:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9552:     return $file;
                   9553: }
                   9554: 
1.559     banghart 9555: # ------------------------------------------------------------- Mark as Read Only
                   9556: 
                   9557: sub mark_as_readonly {
                   9558:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9559:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9560:     my ($tmp)=keys(%current_permissions);
                   9561:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9562:     foreach my $file (@{$files}) {
1.759     albertel 9563: 	$file = &declutter_portfile($file);
1.561     banghart 9564:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9565:     }
1.613     albertel 9566:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9567:     return;
                   9568: }
                   9569: 
1.572     banghart 9570: # ------------------------------------------------------------Save Selected Files
                   9571: 
                   9572: sub save_selected_files {
                   9573:     my ($user, $path, @files) = @_;
                   9574:     my $filename = $user."savedfiles";
1.573     banghart 9575:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9576:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9577:     foreach my $file (@files) {
1.620     albertel 9578:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9579:     }
                   9580:     foreach my $file (@other_files) {
1.574     banghart 9581:         print (OUT $file."\n");
1.572     banghart 9582:     }
1.574     banghart 9583:     close (OUT);
1.572     banghart 9584:     return 'ok';
                   9585: }
                   9586: 
1.574     banghart 9587: sub clear_selected_files {
                   9588:     my ($user) = @_;
                   9589:     my $filename = $user."savedfiles";
1.1117    foxr     9590:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9591:     print (OUT undef);
                   9592:     close (OUT);
                   9593:     return ("ok");    
                   9594: }
                   9595: 
1.572     banghart 9596: sub files_in_path {
                   9597:     my ($user, $path) = @_;
                   9598:     my $filename = $user."savedfiles";
                   9599:     my %return_files;
1.1117    foxr     9600:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9601:     while (my $line_in = <IN>) {
1.574     banghart 9602:         chomp ($line_in);
                   9603:         my @paths_and_file = split (m!/!, $line_in);
                   9604:         my $file_part = pop (@paths_and_file);
                   9605:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9606:         $path_part.='/';
                   9607:         my $path_and_file = $path_part.$file_part;
                   9608:         if ($path_part eq $path) {
                   9609:             $return_files{$file_part}= 'selected';
                   9610:         }
                   9611:     }
1.574     banghart 9612:     close (IN);
                   9613:     return (\%return_files);
1.572     banghart 9614: }
                   9615: 
                   9616: # called in portfolio select mode, to show files selected NOT in current directory
                   9617: sub files_not_in_path {
                   9618:     my ($user, $path) = @_;
                   9619:     my $filename = $user."savedfiles";
                   9620:     my @return_files;
                   9621:     my $path_part;
1.1117    foxr     9622:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9623:     while (my $line = <IN>) {
1.572     banghart 9624:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9625:         my @paths_and_file = split(m|/|, $line);
                   9626:         my $file_part = pop(@paths_and_file);
                   9627:         chomp($file_part);
                   9628:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9629:         $path_part .= '/';
                   9630:         my $path_and_file = $path_part.$file_part;
                   9631:         if ($path_part ne $path) {
1.800     albertel 9632:             push(@return_files, ($path_and_file));
1.572     banghart 9633:         }
                   9634:     }
1.800     albertel 9635:     close(OUT);
1.574     banghart 9636:     return (@return_files);
1.572     banghart 9637: }
                   9638: 
1.1273    raeburn  9639: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   9640:  
                   9641: sub portfiles_versioning {
                   9642:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   9643:     my $portfolio_root = '/userfiles/portfolio';
                   9644:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   9645:     foreach my $file (@{$portfiles}) {
                   9646:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   9647:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   9648:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   9649:         my $getpropath = 1;
                   9650:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   9651:                                              $stu_name,$getpropath);
                   9652:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   9653:         my $new_answer = 
                   9654:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   9655:         if ($new_answer ne 'problem getting file') {
                   9656:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   9657:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   9658:                               [$symb,$env{'request.course.id'},'graded']);
                   9659:         }
                   9660:     }
                   9661: }
                   9662: 
                   9663: sub get_next_version {
                   9664:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   9665:     my $version;
                   9666:     if (ref($dir_list) eq 'ARRAY') {
                   9667:         foreach my $row (@{$dir_list}) {
                   9668:             my ($file) = split(/\&/,$row,2);
                   9669:             my ($file_name,$file_version,$file_ext) =
                   9670:                 &file_name_version_ext($file);
                   9671:             if (($file_name eq $answer_name) &&
                   9672:                 ($file_ext eq $answer_ext)) {
                   9673:                      # gets here if filename and extension match,
                   9674:                      # regardless of version
                   9675:                 if ($file_version ne '') {
                   9676:                     # a versioned file is found  so save it for later
                   9677:                     if ($file_version > $version) {
                   9678:                         $version = $file_version;
                   9679:                     }
                   9680:                 }
                   9681:             }
                   9682:         }
                   9683:     }
                   9684:     $version ++;
                   9685:     return($version);
                   9686: }
                   9687: 
                   9688: sub version_selected_portfile {
                   9689:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   9690:     my ($answer_name,$answer_ver,$answer_ext) =
                   9691:         &file_name_version_ext($file_name);
                   9692:     my $new_answer;
                   9693:     $env{'form.copy'} =
                   9694:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   9695:     if($env{'form.copy'} eq '-1') {
                   9696:         $new_answer = 'problem getting file';
                   9697:     } else {
                   9698:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   9699:         my $copy_result = 
                   9700:             &finishuserfileupload($stu_name,$domain,'copy',
                   9701:                                   '/portfolio'.$directory.$new_answer);
                   9702:     }
                   9703:     undef($env{'form.copy'});
                   9704:     return ($new_answer);
                   9705: }
                   9706: 
                   9707: sub file_name_version_ext {
                   9708:     my ($file)=@_;
                   9709:     my @file_parts = split(/\./, $file);
                   9710:     my ($name,$version,$ext);
                   9711:     if (@file_parts > 1) {
                   9712:         $ext=pop(@file_parts);
                   9713:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   9714:             $version=pop(@file_parts);
                   9715:         }
                   9716:         $name=join('.',@file_parts);
                   9717:     } else {
                   9718:         $name=join('.',@file_parts);
                   9719:     }
                   9720:     return($name,$version,$ext);
                   9721: }
                   9722: 
1.745     raeburn  9723: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9724: 
1.745     raeburn  9725: sub get_portfile_permissions {
                   9726:     my ($domain,$user) = @_;
1.613     albertel 9727:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9728:     my ($tmp)=keys(%current_permissions);
                   9729:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9730:     return \%current_permissions;
                   9731: }
                   9732: 
                   9733: #---------------------------------------------Get portfolio file access controls
                   9734: 
1.749     raeburn  9735: sub get_access_controls {
1.745     raeburn  9736:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9737:     my %access;
                   9738:     my $real_file = $file;
                   9739:     $file =~ s/\.meta$//;
1.745     raeburn  9740:     if (defined($file)) {
1.749     raeburn  9741:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9742:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9743:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9744:             }
                   9745:         }
1.745     raeburn  9746:     } else {
1.749     raeburn  9747:         foreach my $key (keys(%{$current_permissions})) {
                   9748:             if ($key =~ /\0accesscontrol$/) {
                   9749:                 if (defined($group)) {
                   9750:                     if ($key !~ m-^\Q$group\E/-) {
                   9751:                         next;
                   9752:                     }
                   9753:                 }
                   9754:                 my ($fullpath) = split(/\0/,$key);
                   9755:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9756:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9757:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9758:                     }
                   9759:                 }
                   9760:             }
                   9761:         }
                   9762:     }
                   9763:     return %access;
                   9764: }
                   9765: 
                   9766: sub modify_access_controls {
                   9767:     my ($file_name,$changes,$domain,$user)=@_;
                   9768:     my ($outcome,$deloutcome);
                   9769:     my %store_permissions;
                   9770:     my %new_values;
                   9771:     my %new_control;
                   9772:     my %translation;
                   9773:     my @deletions = ();
                   9774:     my $now = time;
                   9775:     if (exists($$changes{'activate'})) {
                   9776:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9777:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9778:             my $numnew = scalar(@newitems);
                   9779:             for (my $i=0; $i<$numnew; $i++) {
                   9780:                 my $newkey = $newitems[$i];
                   9781:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9782:                 if ($newkey =~ /^\d+:/) { 
                   9783:                     $newkey =~ s/^(\d+)/$newid/;
                   9784:                     $translation{$1} = $newid;
                   9785:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9786:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9787:                     $translation{$1} = $newid;
                   9788:                 }
1.749     raeburn  9789:                 $new_values{$file_name."\0".$newkey} = 
                   9790:                                           $$changes{'activate'}{$newitems[$i]};
                   9791:                 $new_control{$newkey} = $now;
                   9792:             }
                   9793:         }
                   9794:     }
                   9795:     my %todelete;
                   9796:     my %changed_items;
                   9797:     foreach my $action ('delete','update') {
                   9798:         if (exists($$changes{$action})) {
                   9799:             if (ref($$changes{$action}) eq 'HASH') {
                   9800:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9801:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9802:                     if ($action eq 'delete') { 
                   9803:                         $todelete{$itemnum} = 1;
                   9804:                     } else {
                   9805:                         $changed_items{$itemnum} = $key;
                   9806:                     }
                   9807:                 }
1.745     raeburn  9808:             }
                   9809:         }
1.749     raeburn  9810:     }
                   9811:     # get lock on access controls for file.
                   9812:     my $lockhash = {
                   9813:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9814:                                                        ':'.$env{'user.domain'},
                   9815:                    }; 
                   9816:     my $tries = 0;
                   9817:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9818:    
1.1288    damieng  9819:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  9820:         $tries ++;
1.1289    damieng  9821:         sleep(0.1);
1.749     raeburn  9822:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9823:     }
                   9824:     if ($gotlock eq 'ok') {
                   9825:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9826:         my ($tmp)=keys(%curr_permissions);
                   9827:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9828:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9829:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9830:             if (ref($curr_controls) eq 'HASH') {
                   9831:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9832:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9833:                     if (defined($todelete{$itemnum})) {
                   9834:                         push(@deletions,$file_name."\0".$control_item);
                   9835:                     } else {
                   9836:                         if (defined($changed_items{$itemnum})) {
                   9837:                             $new_control{$changed_items{$itemnum}} = $now;
                   9838:                             push(@deletions,$file_name."\0".$control_item);
                   9839:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9840:                         } else {
                   9841:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9842:                         }
                   9843:                     }
1.745     raeburn  9844:                 }
                   9845:             }
                   9846:         }
1.970     raeburn  9847:         my ($group);
                   9848:         if (&is_course($domain,$user)) {
                   9849:             ($group,my $file) = split(/\//,$file_name,2);
                   9850:         }
1.749     raeburn  9851:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9852:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9853:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9854:         #  remove lock
                   9855:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9856:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9857:         my $sqlresult =
1.970     raeburn  9858:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9859:                                     $group);
1.749     raeburn  9860:     } else {
                   9861:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9862:     }
1.749     raeburn  9863:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9864: }
                   9865: 
1.827     raeburn  9866: sub make_public_indefinitely {
1.1271    raeburn  9867:     my (@requrl) = @_;
                   9868:     return &automated_portfile_access('public',\@requrl);
                   9869: }
                   9870: 
                   9871: sub automated_portfile_access {
                   9872:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  9873:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   9874:         return 'invalid';
                   9875:     }
1.1271    raeburn  9876:     my %urls;
                   9877:     if (ref($addsref) eq 'ARRAY') {
                   9878:         foreach my $requrl (@{$addsref}) {
                   9879:             if (&is_portfolio_url($requrl)) {
                   9880:                 unless (exists($urls{$requrl})) {
                   9881:                     $urls{$requrl} = 'add';
                   9882:                 }
                   9883:             }
                   9884:         }
                   9885:     }
                   9886:     if (ref($delsref) eq 'ARRAY') {
                   9887:         foreach my $requrl (@{$delsref}) { 
                   9888:             if (&is_portfolio_url($requrl)) {
                   9889:                 unless (exists($urls{$requrl})) {
                   9890:                     $urls{$requrl} = 'delete'; 
                   9891:                 }
                   9892:             }
                   9893:         }
                   9894:     }
                   9895:     unless (keys(%urls)) {
                   9896:         return 'invalid';
                   9897:     }
                   9898:     my $ip;
                   9899:     if ($accesstype eq 'ip') {
                   9900:         if (ref($info) eq 'HASH') {
                   9901:             if ($info->{'ip'} ne '') {
                   9902:                 $ip = $info->{'ip'};
                   9903:             }
                   9904:         }
                   9905:         if ($ip eq '') {
                   9906:             return 'invalid';
                   9907:         }
                   9908:     }
                   9909:     my $errors;
1.827     raeburn  9910:     my $now = time;
1.1271    raeburn  9911:     my %current_perms;
                   9912:     foreach my $requrl (sort(keys(%urls))) {
                   9913:         my $action;
                   9914:         if ($urls{$requrl} eq 'add') {
                   9915:             $action = 'activate';
                   9916:         } else {
                   9917:             $action = 'none';
                   9918:         }
                   9919:         my $aclnum = 0;
1.827     raeburn  9920:         my (undef,$udom,$unum,$file_name,$group) =
                   9921:             &parse_portfolio_url($requrl);
1.1271    raeburn  9922:         unless (exists($current_perms{$unum.':'.$udom})) {
                   9923:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   9924:         }
                   9925:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  9926:                                                    $group,$file_name);
                   9927:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9928:             my ($num,$scope,$end,$start) = 
                   9929:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  9930:             if ($scope eq $accesstype) {
                   9931:                 if (($start <= $now) && ($end == 0)) {
                   9932:                     if ($accesstype eq 'ip') {
                   9933:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   9934:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   9935:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   9936:                                     if ($urls{$requrl} eq 'add') {
                   9937:                                         $action = 'none';
                   9938:                                         last;
                   9939:                                     } else {
                   9940:                                         $action = 'delete';
                   9941:                                         $aclnum = $num;
                   9942:                                         last;
                   9943:                                     }
                   9944:                                 }
                   9945:                             }
                   9946:                         }
                   9947:                     } elsif ($accesstype eq 'public') {
                   9948:                         if ($urls{$requrl} eq 'add') {
                   9949:                             $action = 'none';
                   9950:                             last;
                   9951:                         } else {
                   9952:                             $action = 'delete';
                   9953:                             $aclnum = $num;
                   9954:                             last;
                   9955:                         }
                   9956:                     }
                   9957:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  9958:                     $action = 'update';
                   9959:                     $aclnum = $num;
1.1271    raeburn  9960:                     last;
1.827     raeburn  9961:                 }
                   9962:             }
                   9963:         }
                   9964:         if ($action eq 'none') {
1.1271    raeburn  9965:             next;
1.827     raeburn  9966:         } else {
                   9967:             my %changes;
                   9968:             my $newend = 0;
                   9969:             my $newstart = $now;
1.1271    raeburn  9970:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  9971:             $changes{$action}{$newkey} = {
1.1271    raeburn  9972:                 type => $accesstype,
1.827     raeburn  9973:                 time => {
                   9974:                     start => $newstart,
                   9975:                     end   => $newend,
                   9976:                 },
                   9977:             };
1.1271    raeburn  9978:             if ($accesstype eq 'ip') {
                   9979:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   9980:             }
1.827     raeburn  9981:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9982:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  9983:             unless ($outcome eq 'ok') {
                   9984:                 $errors .= $outcome.' ';
                   9985:             }
1.827     raeburn  9986:         }
1.1271    raeburn  9987:     }
                   9988:     if ($errors) {
                   9989:         $errors =~ s/\s$//;
                   9990:         return $errors;
1.827     raeburn  9991:     } else {
1.1271    raeburn  9992:         return 'ok';
1.827     raeburn  9993:     }
                   9994: }
                   9995: 
1.745     raeburn  9996: #------------------------------------------------------Get Marked as Read Only
                   9997: 
                   9998: sub get_marked_as_readonly {
                   9999:     my ($domain,$user,$what,$group) = @_;
                   10000:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10001:     my @readonly_files;
1.629     banghart 10002:     my $cmp1=$what;
                   10003:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10004:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10005:         if (defined($group)) {
                   10006:             if ($file_name !~ m-^\Q$group\E/-) {
                   10007:                 next;
                   10008:             }
                   10009:         }
1.561     banghart 10010:         if (ref($value) eq "ARRAY"){
                   10011:             foreach my $stored_what (@{$value}) {
1.629     banghart 10012:                 my $cmp2=$stored_what;
1.759     albertel 10013:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10014:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10015:                 }
1.629     banghart 10016:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10017:                     push(@readonly_files, $file_name);
1.745     raeburn  10018:                     last;
1.563     banghart 10019:                 } elsif (!defined($what)) {
                   10020:                     push(@readonly_files, $file_name);
1.745     raeburn  10021:                     last;
1.561     banghart 10022:                 }
                   10023:             }
1.745     raeburn  10024:         }
1.561     banghart 10025:     }
                   10026:     return @readonly_files;
                   10027: }
1.577     banghart 10028: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10029: 
1.577     banghart 10030: sub get_marked_as_readonly_hash {
1.745     raeburn  10031:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10032:     my %readonly_files;
1.745     raeburn  10033:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10034:         if (defined($group)) {
                   10035:             if ($file_name !~ m-^\Q$group\E/-) {
                   10036:                 next;
                   10037:             }
                   10038:         }
1.577     banghart 10039:         if (ref($value) eq "ARRAY"){
                   10040:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10041:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10042:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10043:                         if ($lock_descriptor eq 'graded') {
                   10044:                             $readonly_files{$file_name} = 'graded';
                   10045:                         } elsif ($lock_descriptor eq 'handback') {
                   10046:                             $readonly_files{$file_name} = 'handback';
                   10047:                         } else {
                   10048:                             if (!exists($readonly_files{$file_name})) {
                   10049:                                 $readonly_files{$file_name} = 'locked';
                   10050:                             }
                   10051:                         }
1.745     raeburn  10052:                     }
1.750     banghart 10053:                 } 
1.577     banghart 10054:             }
                   10055:         } 
                   10056:     }
                   10057:     return %readonly_files;
                   10058: }
1.559     banghart 10059: # ------------------------------------------------------------ Unmark as Read Only
                   10060: 
                   10061: sub unmark_as_readonly {
1.629     banghart 10062:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10063:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10064:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10065:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10066:     my $symb_crs = $what;
                   10067:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10068:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10069:     my ($tmp)=keys(%current_permissions);
                   10070:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10071:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10072:     foreach my $file (@readonly_files) {
1.759     albertel 10073: 	my $clean_file = &declutter_portfile($file);
                   10074: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10075: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10076:         my @new_locks;
                   10077:         my @del_keys;
                   10078:         if (ref($current_locks) eq "ARRAY"){
                   10079:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10080:                 my $compare=$locker;
1.749     raeburn  10081:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10082:                     $compare=join('',@{$locker});
1.746     raeburn  10083:                     if ($compare ne $symb_crs) {
                   10084:                         push(@new_locks, $locker);
                   10085:                     }
1.563     banghart 10086:                 }
                   10087:             }
1.650     albertel 10088:             if (scalar(@new_locks) > 0) {
1.563     banghart 10089:                 $current_permissions{$file} = \@new_locks;
                   10090:             } else {
                   10091:                 push(@del_keys, $file);
1.613     albertel 10092:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10093:                 delete($current_permissions{$file});
1.563     banghart 10094:             }
                   10095:         }
1.561     banghart 10096:     }
1.613     albertel 10097:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10098:     return;
                   10099: }
1.512     banghart 10100: 
1.17      www      10101: # ------------------------------------------------------------ Directory lister
                   10102: 
                   10103: sub dirlist {
1.955     raeburn  10104:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10105:     $uri=~s/^\///;
                   10106:     $uri=~s/\/$//;
1.253     stredwic 10107:     my ($udom, $uname);
1.955     raeburn  10108:     if ($getuserdir) {
1.253     stredwic 10109:         $udom = $userdomain;
                   10110:         $uname = $username;
1.955     raeburn  10111:     } else {
                   10112:         (undef,$udom,$uname)=split(/\//,$uri);
                   10113:         if(defined($userdomain)) {
                   10114:             $udom = $userdomain;
                   10115:         }
                   10116:         if(defined($username)) {
                   10117:             $uname = $username;
                   10118:         }
1.253     stredwic 10119:     }
1.955     raeburn  10120:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10121: 
1.955     raeburn  10122:     $dirRoot = $perlvar{'lonDocRoot'};
                   10123:     if (defined($getpropath)) {
                   10124:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10125:         $dirRoot =~ s/\/$//;
1.955     raeburn  10126:     } elsif (defined($getuserdir)) {
                   10127:         my $subdir=$uname.'__';
                   10128:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10129:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10130:                    ."/$udom/$subdir/$uname";
                   10131:     } elsif (defined($alternateRoot)) {
                   10132:         $dirRoot = $alternateRoot;
1.751     banghart 10133:     }
1.253     stredwic 10134: 
                   10135:     if($udom) {
                   10136:         if($uname) {
1.1135    raeburn  10137:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10138:             if ($uhome eq 'no_host') {
                   10139:                 return ([],'no_host');
                   10140:             }
1.955     raeburn  10141:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10142:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10143:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10144:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10145:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10146:             } else {
                   10147:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10148:             }
1.605     matthew  10149:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10150:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10151:                 @listing_results = split(/:/,$listing);
                   10152:             } else {
                   10153:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10154:             }
1.1135    raeburn  10155:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10156:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10157:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10158:                 return ([],$listing);
                   10159:             } else {
                   10160:                 return (\@listing_results);
1.1135    raeburn  10161:             }
1.955     raeburn  10162:         } elsif(!$alternateRoot) {
1.1136    raeburn  10163:             my (%allusers,%listerror);
1.841     albertel 10164: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10165:  	    foreach my $tryserver (keys(%servers)) {
                   10166:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10167:                                   &escape($udom),$tryserver);
                   10168:                 if ($listing eq 'unknown_cmd') {
                   10169: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10170: 				      $udom, $tryserver);
                   10171:                 } else {
                   10172:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10173:                 }
1.841     albertel 10174: 		if ($listing eq 'unknown_cmd') {
                   10175: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10176: 				      $udom, $tryserver);
                   10177: 		    @listing_results = split(/:/,$listing);
                   10178: 		} else {
                   10179: 		    @listing_results =
                   10180: 			map { &unescape($_); } split(/:/,$listing);
                   10181: 		}
1.1136    raeburn  10182:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10183:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10184:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10185:                     $listerror{$tryserver} = $listing;
                   10186:                 } else {
1.841     albertel 10187: 		    foreach my $line (@listing_results) {
                   10188: 			my ($entry) = split(/&/,$line,2);
                   10189: 			$allusers{$entry} = 1;
                   10190: 		    }
                   10191: 		}
1.253     stredwic 10192:             }
1.1136    raeburn  10193:             my @alluserslist=();
1.800     albertel 10194:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10195:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10196:             }
1.1136    raeburn  10197:             return (\@alluserslist);
1.253     stredwic 10198:         } else {
1.1136    raeburn  10199:             return ([],'missing username');
1.253     stredwic 10200:         }
1.955     raeburn  10201:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10202:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10203:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10204:         return (\@all_domains);
1.955     raeburn  10205:     } else {
1.1136    raeburn  10206:         return ([],'missing domain');
1.275     stredwic 10207:     }
                   10208: }
                   10209: 
                   10210: # --------------------------------------------- GetFileTimestamp
                   10211: # This function utilizes dirlist and returns the date stamp for
                   10212: # when it was last modified.  It will also return an error of -1
                   10213: # if an error occurs
                   10214: 
                   10215: sub GetFileTimestamp {
1.955     raeburn  10216:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10217:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10218:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10219:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10220:                                     undef,$getuserdir);
                   10221:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10222:         return -1;
                   10223:     }
                   10224:     if (ref($fileref) eq 'ARRAY') {
                   10225:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10226:         # @stats contains first the filename, then the stat output
                   10227:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10228:     } else {
                   10229:         return -1;
1.253     stredwic 10230:     }
1.26      www      10231: }
                   10232: 
1.712     albertel 10233: sub stat_file {
                   10234:     my ($uri) = @_;
1.787     albertel 10235:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10236: 
1.955     raeburn  10237:     my ($udom,$uname,$file);
1.712     albertel 10238:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10239: 	($udom,$uname,$file) =
1.811     albertel 10240: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10241: 	$file = 'userfiles/'.$file;
                   10242:     }
                   10243:     if ($uri =~ m-^/res/-) {
                   10244: 	($udom,$uname) = 
1.807     albertel 10245: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10246: 	$file = $uri;
                   10247:     }
                   10248: 
                   10249:     if (!$udom || !$uname || !$file) {
                   10250: 	# unable to handle the uri
                   10251: 	return ();
                   10252:     }
1.956     raeburn  10253:     my $getpropath;
                   10254:     if ($file =~ /^userfiles\//) {
                   10255:         $getpropath = 1;
                   10256:     }
1.1136    raeburn  10257:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10258:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10259:         return ();
                   10260:     } else {
                   10261:         if (ref($listref) eq 'ARRAY') {
                   10262:             my @stats = split('&',$listref->[0]);
                   10263: 	    shift(@stats); #filename is first
                   10264: 	    return @stats;
                   10265:         }
1.712     albertel 10266:     }
                   10267:     return ();
                   10268: }
                   10269: 
1.1313    raeburn  10270: # --------------------------------------------------------- recursedirs
                   10271: # Recursive function to traverse either a specific user's Authoring Space
                   10272: # or corresponding Published Resource Space, and populate the hash ref:
                   10273: # $dirhashref with URLs of all directories, and if $filehashref hash
                   10274: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   10275: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   10276: # files in Authoring Space.
                   10277: #
                   10278: # Inputs:
                   10279: #
                   10280: # $is_home - true if current server is home server for user's space
                   10281: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   10282: # $docroot - Document root (i.e., /home/httpd/html
                   10283: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   10284: # $relpath - Current path (relative to top level).
                   10285: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   10286: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   10287: #
                   10288: # Returns: nothing
                   10289: #
                   10290: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   10291: #
                   10292: # Currently used by interface/londocs.pm to create linked select boxes for
                   10293: # directory and filename to import a Course "Author" resource into a course, and
                   10294: # also to create linked select boxes for Authoring Space and Directory to choose
                   10295: # save location for creation of a new "standard" problem from the Course Editor.
                   10296: #
                   10297: 
                   10298: sub recursedirs {
                   10299:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   10300:     return unless (ref($dirhashref) eq 'HASH');
                   10301:     my $currpath = $docroot.$toppath;
                   10302:     if ($relpath) {
                   10303:         $currpath .= "/$relpath";
                   10304:     }
                   10305:     my $savefile;
                   10306:     if (ref($filehashref)) {
                   10307:         $savefile = 1;
                   10308:     }
                   10309:     if ($is_home) {
                   10310:         if (opendir(my $dirh,$currpath)) {
                   10311:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   10312:                 next if ($item eq '');
                   10313:                 if (-d "$currpath/$item") {
                   10314:                     my $newpath;
                   10315:                     if ($relpath) {
                   10316:                         $newpath = "$relpath/$item";
                   10317:                     } else {
                   10318:                         $newpath = $item;
                   10319:                     }
                   10320:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10321:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10322:                 } elsif ($savefile) {
                   10323:                     if ($context eq 'priv') {
                   10324:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10325:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10326:                         }
                   10327:                     } else {
                   10328:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   10329:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10330:                         }
                   10331:                     }
                   10332:                 }
                   10333:             }
                   10334:             closedir($dirh);
                   10335:         }
                   10336:     } else {
                   10337:         my ($dirlistref,$listerror) =
                   10338:             &dirlist($toppath.$relpath);
                   10339:         my @dir_lines;
                   10340:         my $dirptr=16384;
                   10341:         if (ref($dirlistref) eq 'ARRAY') {
                   10342:             foreach my $dir_line (sort
                   10343:                               {
                   10344:                                   my ($afile)=split('&',$a,2);
                   10345:                                   my ($bfile)=split('&',$b,2);
                   10346:                                   return (lc($afile) cmp lc($bfile));
                   10347:                               } (@{$dirlistref})) {
                   10348:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   10349:                     split(/\&/,$dir_line,16);
                   10350:                 $item =~ s/\s+$//;
                   10351:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   10352:                 if ($dirptr&$testdir) {
                   10353:                     my $newpath;
                   10354:                     if ($relpath) {
                   10355:                         $newpath = "$relpath/$item";
                   10356:                     } else {
                   10357:                         $relpath = '/';
                   10358:                         $newpath = $item;
                   10359:                     }
                   10360:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10361:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10362:                 } elsif ($savefile) {
                   10363:                     if ($context eq 'priv') {
                   10364:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10365:                             $filehashref->{$relpath}{$item} = 1;
                   10366:                         }
                   10367:                     } else {
                   10368:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   10369:                             $filehashref->{$relpath}{$item} = 1;
                   10370:                         }
                   10371:                     }
                   10372:                 }
                   10373:             }
                   10374:         }
                   10375:     }
                   10376:     return;
                   10377: }
                   10378: 
1.26      www      10379: # -------------------------------------------------------- Value of a Condition
                   10380: 
1.713     albertel 10381: # gets the value of a specific preevaluated condition
                   10382: #    stored in the string  $env{user.state.<cid>}
                   10383: # or looks up a condition reference in the bighash and if if hasn't
                   10384: # already been evaluated recurses into docondval to get the value of
                   10385: # the condition, then memoizing it to 
                   10386: #   $env{user.state.<cid>.<condition>}
1.40      www      10387: sub directcondval {
                   10388:     my $number=shift;
1.620     albertel 10389:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10390: 	&Apache::lonuserstate::evalstate();
                   10391:     }
1.713     albertel 10392:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10393: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10394:     } elsif ($number =~ /^_/) {
                   10395: 	my $sub_condition;
                   10396: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10397: 		&GDBM_READER(),0640)) {
                   10398: 	    $sub_condition=$bighash{'conditions'.$number};
                   10399: 	    untie(%bighash);
                   10400: 	}
                   10401: 	my $value = &docondval($sub_condition);
1.949     raeburn  10402: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10403: 	return $value;
                   10404:     }
1.620     albertel 10405:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10406:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10407:     } else {
                   10408:        return 2;
                   10409:     }
                   10410: }
                   10411: 
1.713     albertel 10412: # get the collection of conditions for this resource
1.26      www      10413: sub condval {
                   10414:     my $condidx=shift;
1.54      www      10415:     my $allpathcond='';
1.713     albertel 10416:     foreach my $cond (split(/\|/,$condidx)) {
                   10417: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10418: 	    $allpathcond.=
                   10419: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10420: 	}
1.191     harris41 10421:     }
1.54      www      10422:     $allpathcond=~s/\|$//;
1.713     albertel 10423:     return &docondval($allpathcond);
                   10424: }
                   10425: 
                   10426: #evaluates an expression of conditions
                   10427: sub docondval {
                   10428:     my ($allpathcond) = @_;
                   10429:     my $result=0;
                   10430:     if ($env{'request.course.id'}
                   10431: 	&& defined($allpathcond)) {
                   10432: 	my $operand='|';
                   10433: 	my @stack;
                   10434: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10435: 	    if ($chunk eq '(') {
                   10436: 		push @stack,($operand,$result);
                   10437: 	    } elsif ($chunk eq ')') {
                   10438: 		my $before=pop @stack;
                   10439: 		if (pop @stack eq '&') {
                   10440: 		    $result=$result>$before?$before:$result;
                   10441: 		} else {
                   10442: 		    $result=$result>$before?$result:$before;
                   10443: 		}
                   10444: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10445: 		$operand=$chunk;
                   10446: 	    } else {
                   10447: 		my $new=directcondval($chunk);
                   10448: 		if ($operand eq '&') {
                   10449: 		    $result=$result>$new?$new:$result;
                   10450: 		} else {
                   10451: 		    $result=$result>$new?$result:$new;
                   10452: 		}
                   10453: 	    }
                   10454: 	}
1.26      www      10455:     }
                   10456:     return $result;
1.421     albertel 10457: }
                   10458: 
                   10459: # ---------------------------------------------------- Devalidate courseresdata
                   10460: 
                   10461: sub devalidatecourseresdata {
                   10462:     my ($coursenum,$coursedomain)=@_;
                   10463:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10464:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10465: }
                   10466: 
1.763     www      10467: 
1.200     www      10468: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10469: #
                   10470: #  Parameters:
                   10471: #      $coursenum    - Number of the course.
                   10472: #      $coursedomain - Domain at which the course was created.
                   10473: #  Returns:
                   10474: #     A hash of the course parameters along (I think) with timestamps
                   10475: #     and version info.
1.877     foxr     10476: 
1.624     albertel 10477: sub get_courseresdata {
                   10478:     my ($coursenum,$coursedomain)=@_;
1.200     www      10479:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10480:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10481:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10482:     my %dumpreply;
1.417     albertel 10483:     unless (defined($cached)) {
1.624     albertel 10484: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10485: 	$result=\%dumpreply;
1.251     albertel 10486: 	my ($tmp) = keys(%dumpreply);
                   10487: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10488: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10489: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10490: 	    return $tmp;
1.416     albertel 10491: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10492: 	    $result=undef;
1.599     albertel 10493: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10494: 	}
                   10495:     }
1.624     albertel 10496:     return $result;
                   10497: }
                   10498: 
1.633     albertel 10499: sub devalidateuserresdata {
                   10500:     my ($uname,$udom)=@_;
                   10501:     my $hashid="$udom:$uname";
                   10502:     &devalidate_cache_new('userres',$hashid);
                   10503: }
                   10504: 
1.624     albertel 10505: sub get_userresdata {
                   10506:     my ($uname,$udom)=@_;
                   10507:     #most student don\'t have any data set, check if there is some data
                   10508:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10509: 
                   10510:     my $hashid="$udom:$uname";
                   10511:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10512:     if (!defined($cached)) {
                   10513: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10514: 	$result=\%resourcedata;
                   10515: 	&do_cache_new('userres',$hashid,$result,600);
                   10516:     }
                   10517:     my ($tmp)=keys(%$result);
                   10518:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10519: 	return $result;
                   10520:     }
                   10521:     #error 2 occurs when the .db doesn't exist
                   10522:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  10523:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   10524: 	    &logthis("<font color=\"blue\">WARNING:".
                   10525: 		     " Trying to get resource data for ".
                   10526: 		     $uname." at ".$udom.": ".
                   10527: 		     $tmp."</font>");
                   10528:         }
1.624     albertel 10529:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10530: 	#&EXT_cache_set($udom,$uname);
                   10531: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10532: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10533:     }
                   10534:     return $tmp;
                   10535: }
1.879     foxr     10536: #----------------------------------------------- resdata - return resource data
                   10537: #  Purpose:
                   10538: #    Return resource data for either users or for a course.
                   10539: #  Parameters:
                   10540: #     $name      - Course/user name.
                   10541: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  10542: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  10543: #     $mapp      - decluttered URL of enclosing map  
                   10544: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   10545: #     $recurseup - Ref to array of map URLs, starting with map containing
                   10546: #                  $mapp up through hierarchy of nested maps to top level map.  
                   10547: #     $courseid  - CourseID (first part of param identifier).
                   10548: #     $modifier  - Middle part of param identifier.
                   10549: #     $what      - Last part of param identifier.
1.879     foxr     10550: #     @which     - Array of names of resources desired.
                   10551: #  Returns:
                   10552: #     The value of the first reasource in @which that is found in the
                   10553: #     resource hash.
                   10554: #  Exceptional Conditions:
                   10555: #     If the $type passed in is not valid (not the string 'course' or 
                   10556: #     'user', an undefined  reference is returned.
                   10557: #     If none of the resources are found, an undef is returned
1.624     albertel 10558: sub resdata {
1.1301    raeburn  10559:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   10560:         $modifier,$what,@which)=@_;
1.624     albertel 10561:     my $result;
                   10562:     if ($type eq 'course') {
                   10563: 	$result=&get_courseresdata($name,$domain);
                   10564:     } elsif ($type eq 'user') {
                   10565: 	$result=&get_userresdata($name,$domain);
                   10566:     }
                   10567:     if (!ref($result)) { return $result; }    
1.251     albertel 10568:     foreach my $item (@which) {
1.1301    raeburn  10569:         if ($item->[1] eq 'course') {
                   10570:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   10571:                 unless ($$recursed) {
1.1302    raeburn  10572:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  10573:                     $$recursed = 1;
                   10574:                 }
                   10575:                 foreach my $item (@${recurseup}) {
                   10576:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   10577:                     last if (defined($result->{$norecursechk}));
                   10578:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   10579:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   10580:                 }
                   10581:             }
                   10582:         }
                   10583:         if (defined($result->{$item->[0]})) {
1.927     albertel 10584: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 10585: 	}
1.250     albertel 10586:     }
1.291     albertel 10587:     return undef;
1.200     www      10588: }
                   10589: 
1.1298    raeburn  10590: sub get_domain_ltitools {
                   10591:     my ($cdom) = @_;
                   10592:     my %ltitools;
                   10593:     my ($result,$cached)=&is_cached_new('ltitools',$cdom);
                   10594:     if (defined($cached)) {
                   10595:         if (ref($result) eq 'HASH') {
                   10596:             %ltitools = %{$result};
                   10597:         }
                   10598:     } else {
                   10599:         my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
                   10600:         if (ref($domconfig{'ltitools'}) eq 'HASH') {
                   10601:             %ltitools = %{$domconfig{'ltitools'}};
                   10602:         }
                   10603:         my $cachetime = 24*60*60;
                   10604:         &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
                   10605:     }
                   10606:     return %ltitools;
                   10607: }
                   10608: 
1.1236    raeburn  10609: sub get_numsuppfiles {
                   10610:     my ($cnum,$cdom,$ignorecache)=@_;
                   10611:     my $hashid=$cnum.':'.$cdom;
                   10612:     my ($suppcount,$cached);
                   10613:     unless ($ignorecache) {
                   10614:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10615:     }
                   10616:     unless (defined($cached)) {
                   10617:         my $chome=&homeserver($cnum,$cdom);
                   10618:         unless ($chome eq 'no_host') {
                   10619:             ($suppcount,my $errors) = (0,0);
                   10620:             my $suppmap = 'supplemental.sequence';
                   10621:             ($suppcount,$errors) = 
                   10622:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10623:         }
                   10624:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10625:     }
                   10626:     return $suppcount;
                   10627: }
                   10628: 
1.379     matthew  10629: #
                   10630: # EXT resource caching routines
                   10631: #
                   10632: 
1.1302    raeburn  10633: {
                   10634: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   10635: #
                   10636: # The course for which we cache
                   10637: my $cachedmapkey='';
                   10638: # The cached recursive maps for this course
                   10639: my %cachedmaps=();
                   10640: # When this was last done
                   10641: my $cachedmaptime='';
                   10642: 
1.379     matthew  10643: sub clear_EXT_cache_status {
1.383     albertel 10644:     &delenv('cache.EXT.');
1.379     matthew  10645: }
                   10646: 
                   10647: sub EXT_cache_status {
                   10648:     my ($target_domain,$target_user) = @_;
1.383     albertel 10649:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10650:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10651:         # We know already the user has no data
                   10652:         return 1;
                   10653:     } else {
                   10654:         return 0;
                   10655:     }
                   10656: }
                   10657: 
                   10658: sub EXT_cache_set {
                   10659:     my ($target_domain,$target_user) = @_;
1.383     albertel 10660:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10661:     #&appenv({$cachename => time});
1.379     matthew  10662: }
                   10663: 
1.28      www      10664: # --------------------------------------------------------- Value of a Variable
1.58      www      10665: sub EXT {
1.715     albertel 10666: 
1.1228    raeburn  10667:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10668:     unless ($varname) { return ''; }
1.218     albertel 10669:     #get real user name/domain, courseid and symb
                   10670:     my $courseid;
1.359     albertel 10671:     my $publicuser;
1.427     www      10672:     if ($symbparm) {
                   10673: 	$symbparm=&get_symb_from_alias($symbparm);
                   10674:     }
1.218     albertel 10675:     if (!($uname && $udom)) {
1.790     albertel 10676:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10677:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10678:     } else {
1.620     albertel 10679: 	$courseid=$env{'request.course.id'};
1.218     albertel 10680:     }
1.48      www      10681:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10682:     my $rest;
1.320     albertel 10683:     if (defined($therest[0])) {
1.48      www      10684:        $rest=join('.',@therest);
                   10685:     } else {
                   10686:        $rest='';
                   10687:     }
1.320     albertel 10688: 
1.57      www      10689:     my $qualifierrest=$qualifier;
                   10690:     if ($rest) { $qualifierrest.='.'.$rest; }
                   10691:     my $spacequalifierrest=$space;
                   10692:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      10693:     if ($realm eq 'user') {
1.48      www      10694: # --------------------------------------------------------------- user.resource
                   10695: 	if ($space eq 'resource') {
1.651     albertel 10696: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   10697: 		  || defined($Apache::lonhomework::parsing_a_task))
                   10698: 		 &&
1.744     albertel 10699: 		 ($symbparm eq &symbread()) ) {	
                   10700: 		# if we are in the middle of processing the resource the
                   10701: 		# get the value we are planning on committing
                   10702:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   10703:                     return $Apache::lonhomework::results{$qualifierrest};
                   10704:                 } else {
                   10705:                     return $Apache::lonhomework::history{$qualifierrest};
                   10706:                 }
1.335     albertel 10707: 	    } else {
1.359     albertel 10708: 		my %restored;
1.620     albertel 10709: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 10710: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   10711: 		} else {
                   10712: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   10713: 		}
1.335     albertel 10714: 		return $restored{$qualifierrest};
                   10715: 	    }
1.48      www      10716: # ----------------------------------------------------------------- user.access
                   10717:         } elsif ($space eq 'access') {
1.218     albertel 10718: 	    # FIXME - not supporting calls for a specific user
1.48      www      10719:             return &allowed($qualifier,$rest);
                   10720: # ------------------------------------------ user.preferences, user.environment
                   10721:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 10722: 	    if (($uname eq $env{'user.name'}) &&
                   10723: 		($udom eq $env{'user.domain'})) {
                   10724: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10725: 	    } else {
1.359     albertel 10726: 		my %returnhash;
                   10727: 		if (!$publicuser) {
                   10728: 		    %returnhash=&userenvironment($udom,$uname,
                   10729: 						 $qualifierrest);
                   10730: 		}
1.218     albertel 10731: 		return $returnhash{$qualifierrest};
                   10732: 	    }
1.48      www      10733: # ----------------------------------------------------------------- user.course
                   10734:         } elsif ($space eq 'course') {
1.218     albertel 10735: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10736:             return $env{join('.',('request.course',$qualifier))};
1.48      www      10737: # ------------------------------------------------------------------- user.role
                   10738:         } elsif ($space eq 'role') {
1.218     albertel 10739: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10740:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      10741:             if ($qualifier eq 'value') {
                   10742: 		return $role;
                   10743:             } elsif ($qualifier eq 'extent') {
                   10744:                 return $where;
                   10745:             }
                   10746: # ----------------------------------------------------------------- user.domain
                   10747:         } elsif ($space eq 'domain') {
1.218     albertel 10748:             return $udom;
1.48      www      10749: # ------------------------------------------------------------------- user.name
                   10750:         } elsif ($space eq 'name') {
1.218     albertel 10751:             return $uname;
1.48      www      10752: # ---------------------------------------------------- Any other user namespace
1.29      www      10753:         } else {
1.359     albertel 10754: 	    my %reply;
                   10755: 	    if (!$publicuser) {
                   10756: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10757: 	    }
                   10758: 	    return $reply{$qualifierrest};
1.48      www      10759:         }
1.236     www      10760:     } elsif ($realm eq 'query') {
                   10761: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10762:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10763: 						[$spacequalifierrest]);
1.620     albertel 10764: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10765:    } elsif ($realm eq 'request') {
1.48      www      10766: # ------------------------------------------------------------- request.browser
                   10767:         if ($space eq 'browser') {
1.1145    bisitz   10768:             return $env{'browser.'.$qualifier};
1.57      www      10769: # ------------------------------------------------------------ request.filename
                   10770:         } else {
1.620     albertel 10771:             return $env{'request.'.$spacequalifierrest};
1.29      www      10772:         }
1.28      www      10773:     } elsif ($realm eq 'course') {
1.48      www      10774: # ---------------------------------------------------------- course.description
1.620     albertel 10775:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10776:     } elsif ($realm eq 'resource') {
1.165     www      10777: 
1.620     albertel 10778: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10779: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10780: 	}
1.693     albertel 10781: 
1.1232    raeburn  10782:         if ($qualifier eq '') {
                   10783: 	    if ($space eq 'title') {
                   10784: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10785: 	        return &gettitle($symbparm);
                   10786: 	    }
1.693     albertel 10787: 	
1.1232    raeburn  10788: 	    if ($space eq 'map') {
                   10789: 	        my ($map) = &decode_symb($symbparm);
                   10790: 	        return &symbread($map);
                   10791: 	    }
                   10792:             if ($space eq 'maptitle') {
                   10793:                 my ($map) = &decode_symb($symbparm);
                   10794:                 return &gettitle($map);
                   10795:             }
                   10796: 	    if ($space eq 'filename') {
                   10797: 	        if ($symbparm) {
                   10798: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10799: 	        }
                   10800: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10801: 	    }
1.1232    raeburn  10802: 
1.1233    raeburn  10803:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10804:                 if ($space eq 'visibleparts') {
                   10805:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10806:                     my $item;
                   10807:                     if (ref($navmap)) {
                   10808:                         my $res = $navmap->getBySymb($symbparm);
                   10809:                         my $parts = $res->parts();
                   10810:                         if (ref($parts) eq 'ARRAY') {
                   10811:                             $item = join(',',@{$parts});
                   10812:                         }
                   10813:                         undef($navmap);
1.1232    raeburn  10814:                     }
1.1233    raeburn  10815:                     return $item;
1.1232    raeburn  10816:                 }
                   10817:             }
                   10818:         }
1.693     albertel 10819: 
1.1301    raeburn  10820: 	my ($section, $group, @groups, @recurseup, $recursed);
                   10821: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  10822:         if (($courseid eq '') && ($cid)) {
                   10823:             $courseid = $cid;
                   10824:         }
                   10825: 	if (($symbparm && $courseid) && 
                   10826: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      10827: 
1.218     albertel 10828: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10829: 
1.60      www      10830: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10831: 	    my $symbp=$symbparm;
1.1301    raeburn  10832: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10833: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  10834:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 10835: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 10836: 	    if (($env{'user.name'} eq $uname) &&
                   10837: 		($env{'user.domain'} eq $udom)) {
                   10838: 		$section=$env{'request.course.sec'};
1.733     raeburn  10839:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10840:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10841: 	    } else {
1.539     albertel 10842: 		if (! defined($usection)) {
1.551     albertel 10843: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10844: 		} else {
                   10845: 		    $section = $usection;
                   10846: 		}
1.733     raeburn  10847:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10848: 	    }
                   10849: 
                   10850: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10851: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  10852:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 10853: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10854: 
1.593     albertel 10855: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10856: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  10857:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 10858: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10859: 
1.60      www      10860: # ----------------------------------------------------------- first, check user
1.624     albertel 10861: 
1.1301    raeburn  10862: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   10863:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 10864: 				       ([$courselevelr,'resource'],
                   10865: 					[$courselevelm,'map'     ],
1.1301    raeburn  10866:                                         [$courseleveli,'map'     ],
1.927     albertel 10867: 					[$courselevel, 'course'  ]));
1.931     albertel 10868: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10869: 
1.594     albertel 10870: # ------------------------------------------------ second, check some of course
1.684     raeburn  10871:             my $coursereply;
1.691     raeburn  10872:             if (@groups > 0) {
                   10873:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  10874:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   10875:                                        $mapp,\$recursed,\@recurseup);
                   10876:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  10877:             }
1.96      www      10878: 
1.684     raeburn  10879: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10880: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  10881: 				  'course',$mapp,\$recursed,\@recurseup,
                   10882:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 10883: 				  ([$seclevelr,   'resource'],
                   10884: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  10885:                                    [$secleveli,   'map'     ],
1.927     albertel 10886: 				   [$seclevel,    'course'  ],
                   10887: 				   [$courselevelr,'resource']));
                   10888: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10889: 
1.60      www      10890: # ------------------------------------------------------ third, check map parms
1.218     albertel 10891: 	    my %parmhash=();
                   10892: 	    my $thisparm='';
                   10893: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10894: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10895: 		    &GDBM_READER(),0640)) {
1.218     albertel 10896: 		$thisparm=$parmhash{$symbparm};
                   10897: 		untie(%parmhash);
                   10898: 	    }
1.927     albertel 10899: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10900: 	}
1.594     albertel 10901: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  10902:  
                   10903:         my $what = $spacequalifierrest;
                   10904: 	$what=~s/\./\_/;
1.282     albertel 10905: 	my $filename;
                   10906: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10907: 	if ($symbparm) {
1.409     www      10908: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10909: 	} else {
1.620     albertel 10910: 	    $filename=$env{'request.filename'};
1.282     albertel 10911: 	}
1.1301    raeburn  10912: 	my $metadata=&metadata($filename,$what);
1.927     albertel 10913: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1301    raeburn  10914: 	$metadata=&metadata($filename,'parameter_'.$what);
1.927     albertel 10915: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10916: 
1.1301    raeburn  10917: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 10918: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10919: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10920: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10921: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  10922: 				     'course',$mapp,\$recursed,\@recurseup,
                   10923:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 10924: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  10925:                                       [$courseleveli,'map'   ],
1.927     albertel 10926: 				      [$courselevel, 'course']));
                   10927: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10928: 	}
1.145     www      10929: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10930: 	unless ($space eq '0') {
1.336     albertel 10931: 	    my @parts=split(/_/,$space);
                   10932: 	    my $id=pop(@parts);
                   10933: 	    my $part=join('_',@parts);
                   10934: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10935: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10936: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10937: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10938: 	}
1.395     albertel 10939: 	if ($recurse) { return undef; }
                   10940: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10941: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10942: # ---------------------------------------------------- Any other user namespace
                   10943:     } elsif ($realm eq 'environment') {
                   10944: # ----------------------------------------------------------------- environment
1.620     albertel 10945: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10946: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10947: 	} else {
1.770     albertel 10948: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10949: 		return '';
                   10950: 	    }
1.219     albertel 10951: 	    my %returnhash=&userenvironment($udom,$uname,
                   10952: 					    $spacequalifierrest);
                   10953: 	    return $returnhash{$spacequalifierrest};
                   10954: 	}
1.28      www      10955:     } elsif ($realm eq 'system') {
1.48      www      10956: # ----------------------------------------------------------------- system.time
                   10957: 	if ($space eq 'time') {
                   10958: 	    return time;
                   10959:         }
1.696     albertel 10960:     } elsif ($realm eq 'server') {
                   10961: # ----------------------------------------------------------------- system.time
                   10962: 	if ($space eq 'name') {
                   10963: 	    return $ENV{'SERVER_NAME'};
                   10964:         }
1.28      www      10965:     }
1.48      www      10966:     return '';
1.61      www      10967: }
                   10968: 
1.927     albertel 10969: sub get_reply {
                   10970:     my ($reply_value) = @_;
1.940     raeburn  10971:     if (ref($reply_value) eq 'ARRAY') {
                   10972:         if (wantarray) {
                   10973: 	    return @$reply_value;
                   10974:         }
                   10975:         return $reply_value->[0];
                   10976:     } else {
                   10977:         return $reply_value;
1.927     albertel 10978:     }
                   10979: }
                   10980: 
1.691     raeburn  10981: sub check_group_parms {
1.1301    raeburn  10982:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   10983:         $recursed,$recurseupref) = @_;
                   10984:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   10985:                   [$what,'course']);
                   10986:     my $coursereply;
1.691     raeburn  10987:     foreach my $group (@{$groups}) {
1.1301    raeburn  10988:         my @groupitems = ();
1.691     raeburn  10989:         foreach my $level (@levels) {
1.927     albertel 10990:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10991:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10992:         }
1.1301    raeburn  10993:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10994:                                    $env{'course.'.$courseid.'.domain'},
                   10995:                                    'course',$mapp,$recursed,$recurseupref,
                   10996:                                    $courseid,'.['.$group.'].',$what,
                   10997:                                    @groupitems);
                   10998:         last if (defined($coursereply));
1.691     raeburn  10999:     }
                   11000:     return $coursereply;
                   11001: }
                   11002: 
1.1301    raeburn  11003: sub get_map_hierarchy {
1.1302    raeburn  11004:     my ($mapname,$courseid) = @_;
                   11005:     my @recurseup = ();
1.1301    raeburn  11006:     if ($mapname) {
1.1302    raeburn  11007:         if (($cachedmapkey eq $courseid) &&
                   11008:             (abs($cachedmaptime-time)<5)) {
                   11009:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   11010:                 return @{$cachedmaps{$mapname}};
                   11011:             }
                   11012:         }
1.1301    raeburn  11013:         my $navmap = Apache::lonnavmaps::navmap->new();
                   11014:         if (ref($navmap)) {
                   11015:             @recurseup = $navmap->recurseup_maps($mapname);
                   11016:             undef($navmap);
1.1302    raeburn  11017:             $cachedmaps{$mapname} = \@recurseup;
                   11018:             $cachedmaptime=time;
                   11019:             $cachedmapkey=$courseid;
1.1301    raeburn  11020:         }
                   11021:     }
                   11022:     return @recurseup;
                   11023: }
                   11024: 
1.1302    raeburn  11025: }
                   11026: 
1.691     raeburn  11027: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11028:     my ($courseid,@groups) = @_;
                   11029:     @groups = sort(@groups);
1.691     raeburn  11030:     return @groups;
                   11031: }
                   11032: 
1.395     albertel 11033: sub packages_tab_default {
                   11034:     my ($uri,$varname)=@_;
                   11035:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11036: 
                   11037:     my (@extension,@specifics,$do_default);
                   11038:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11039: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11040: 	if ($pack_type eq 'default') {
                   11041: 	    $do_default=1;
                   11042: 	} elsif ($pack_type eq 'extension') {
                   11043: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11044: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11045: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11046: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11047: 	}
                   11048:     }
                   11049:     # first look for a package that matches the requested part id
                   11050:     foreach my $package (@specifics) {
                   11051: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11052: 	next if ($pack_part ne $part);
                   11053: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11054: 	    return $packagetab{"$pack_type&$name&default"};
                   11055: 	}
                   11056:     }
                   11057:     # look for any possible matching non extension_ package
                   11058:     foreach my $package (@specifics) {
                   11059: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11060: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11061: 	    return $packagetab{"$pack_type&$name&default"};
                   11062: 	}
1.585     albertel 11063: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11064: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11065: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11066: 	}
                   11067:     }
1.738     albertel 11068:     # look for any posible extension_ match
                   11069:     foreach my $package (@extension) {
                   11070: 	my ($package,$pack_type)=@{$package};
                   11071: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11072: 	    return $packagetab{"$pack_type&$name&default"};
                   11073: 	}
                   11074: 	if (defined($packagetab{$package."&$name&default"})) {
                   11075: 	    return $packagetab{$package."&$name&default"};
                   11076: 	}
                   11077:     }
                   11078:     # look for a global default setting
                   11079:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11080: 	return $packagetab{"default&$name&default"};
                   11081:     }
1.395     albertel 11082:     return undef;
                   11083: }
                   11084: 
1.334     albertel 11085: sub add_prefix_and_part {
                   11086:     my ($prefix,$part)=@_;
                   11087:     my $keyroot;
                   11088:     if (defined($prefix) && $prefix !~ /^__/) {
                   11089: 	# prefix that has a part already
                   11090: 	$keyroot=$prefix;
                   11091:     } elsif (defined($prefix)) {
                   11092: 	# prefix that is missing a part
                   11093: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11094:     } else {
                   11095: 	# no prefix at all
                   11096: 	if (defined($part)) { $keyroot='_'.$part; }
                   11097:     }
                   11098:     return $keyroot;
                   11099: }
                   11100: 
1.71      www      11101: # ---------------------------------------------------------------- Get metadata
                   11102: 
1.599     albertel 11103: my %metaentry;
1.1070    www      11104: my %importedpartids;
1.71      www      11105: sub metadata {
1.176     www      11106:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11107:     $uri=&declutter($uri);
1.288     albertel 11108:     # if it is a non metadata possible uri return quickly
1.529     albertel 11109:     if (($uri eq '') || 
                   11110: 	(($uri =~ m|^/*adm/|) && 
1.1298    raeburn  11111: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|exttools?)$})) ||
1.1108    raeburn  11112:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11113: 	return undef;
                   11114:     }
1.1261    raeburn  11115:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11116: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11117: 	return undef;
1.288     albertel 11118:     }
1.73      www      11119:     my $filename=$uri;
                   11120:     $uri=~s/\.meta$//;
1.172     www      11121: #
                   11122: # Is the metadata already cached?
1.177     www      11123: # Look at timestamp of caching
1.172     www      11124: # Everything is cached by the main uri, libraries are never directly cached
                   11125: #
1.428     albertel 11126:     if (!defined($liburi)) {
1.599     albertel 11127: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11128: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11129:     }
                   11130:     {
1.1069    www      11131: # Imported parts would go here
1.1070    www      11132:         my %importedids=();
                   11133:         my @origfileimportpartids=();
1.1069    www      11134:         my $importedparts=0;
1.172     www      11135: #
                   11136: # Is this a recursive call for a library?
                   11137: #
1.599     albertel 11138: #	if (! exists($metacache{$uri})) {
                   11139: #	    $metacache{$uri}={};
                   11140: #	}
1.924     albertel 11141: 	my $cachetime = 60*60;
1.171     www      11142:         if ($liburi) {
                   11143: 	    $liburi=&declutter($liburi);
                   11144:             $filename=$liburi;
1.401     bowersj2 11145:         } else {
1.599     albertel 11146: 	    &devalidate_cache_new('meta',$uri);
                   11147: 	    undef(%metaentry);
1.401     bowersj2 11148: 	}
1.140     www      11149:         my %metathesekeys=();
1.73      www      11150:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11151: 	my $metastring;
1.1140    www      11152: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11153: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11154: 	    $metastring = 
1.929     albertel 11155: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11156: 					  ('grade_target' => 'meta'));
                   11157: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11158: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11159:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11160: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11161: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11162: 	    $metastring=&getfile($file);
1.489     albertel 11163: 	}
1.208     albertel 11164:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11165:         my $token;
1.140     www      11166:         undef %metathesekeys;
1.71      www      11167:         while ($token=$parser->get_token) {
1.339     albertel 11168: 	    if ($token->[0] eq 'S') {
                   11169: 		if (defined($token->[2]->{'package'})) {
1.172     www      11170: #
                   11171: # This is a package - get package info
                   11172: #
1.339     albertel 11173: 		    my $package=$token->[2]->{'package'};
                   11174: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11175: 		    if (defined($token->[2]->{'id'})) { 
                   11176: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11177: 		    }
1.599     albertel 11178: 		    if ($metaentry{':packages'}) {
                   11179: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11180: 		    } else {
1.599     albertel 11181: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11182: 		    }
1.736     albertel 11183: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11184: 			my $part=$keyroot;
                   11185: 			$part=~s/^\_//;
1.736     albertel 11186: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11187: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11188: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11189: 			    # ignore package.tab specified default values
                   11190:                             # here &package_tab_default() will fetch those
                   11191: 			    if ($subp eq 'default') { next; }
1.736     albertel 11192: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11193: 			    my $unikey;
                   11194: 			    if ($pack =~ /_0$/) {
                   11195: 				$unikey='parameter_0_'.$name;
                   11196: 				$part=0;
                   11197: 			    } else {
                   11198: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11199: 			    }
1.339     albertel 11200: 			    if ($subp eq 'display') {
                   11201: 				$value.=' [Part: '.$part.']';
                   11202: 			    }
1.599     albertel 11203: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11204: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11205: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11206: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11207: 			    }
1.599     albertel 11208: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11209: 				$metaentry{':'.$unikey}=
                   11210: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11211: 			    }
1.339     albertel 11212: 			}
                   11213: 		    }
                   11214: 		} else {
1.172     www      11215: #
                   11216: # This is not a package - some other kind of start tag
1.339     albertel 11217: #
                   11218: 		    my $entry=$token->[1];
1.1068    www      11219: 		    my $unikey='';
1.175     www      11220: 
1.339     albertel 11221: 		    if ($entry eq 'import') {
1.175     www      11222: #
                   11223: # Importing a library here
1.339     albertel 11224: #
1.1067    www      11225:                         my $location=$parser->get_text('/import');
                   11226:                         my $dir=$filename;
                   11227:                         $dir=~s|[^/]*$||;
                   11228:                         $location=&filelocation($dir,$location);
1.1069    www      11229:                        
1.1068    www      11230:                         my $importmode=$token->[2]->{'importmode'};
                   11231:                         if ($importmode eq 'problem') {
1.1069    www      11232: # Import as problem/response
1.1068    www      11233:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11234:                         } elsif ($importmode eq 'part') {
                   11235: # Import as part(s)
1.1069    www      11236:                            $importedparts=1;
                   11237: # We need to get the original file and the imported file to get the part order correct
                   11238: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   11239: # Load and inspect original file
1.1070    www      11240:                            if ($#origfileimportpartids<0) {
                   11241:                               undef(%importedpartids);
                   11242:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11243:                               my $origfile=&getfile($origfilelocation);
                   11244:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11245:                            }
                   11246: 
1.1069    www      11247: # Load and inspect imported file
                   11248:                            my $impfile=&getfile($location);
                   11249:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11250:                            if ($#impfilepartids>=0) {
                   11251: # This problem had parts
1.1070    www      11252:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11253:                            } else {
                   11254: # Importing by turning a single problem into a problem part
                   11255: # It gets the import-tags ID as part-ID
                   11256:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11257:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11258:                            }
1.1068    www      11259:                         } else {
                   11260: # Normal import
                   11261:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11262:                            if (defined($token->[2]->{'id'})) {
                   11263:                               $unikey.='_'.$token->[2]->{'id'};
                   11264:                            }
1.1067    www      11265:                         }
                   11266: 
1.339     albertel 11267: 			if ($depthcount<20) {
1.736     albertel 11268: 			    my $metadata = 
                   11269: 				&metadata($uri,'keys', $location,$unikey,
                   11270: 					  $depthcount+1);
                   11271: 			    foreach my $meta (split(',',$metadata)) {
                   11272: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11273: 				$metathesekeys{$meta}=1;
1.339     albertel 11274: 			    }
1.1068    www      11275: 			
                   11276:                         }
1.1067    www      11277: 		    } else {
                   11278: #
                   11279: # Not importing, some other kind of non-package, non-library start tag
                   11280: # 
                   11281:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11282:                         if (defined($token->[2]->{'id'})) {
                   11283:                             $unikey.='_'.$token->[2]->{'id'};
                   11284:                         }
1.339     albertel 11285: 			if (defined($token->[2]->{'name'})) { 
                   11286: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11287: 			}
                   11288: 			$metathesekeys{$unikey}=1;
1.736     albertel 11289: 			foreach my $param (@{$token->[3]}) {
                   11290: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11291: 				$token->[2]->{$param};
1.339     albertel 11292: 			}
                   11293: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11294: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11295: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11296: 		 # only ws inside the tag, and not in default, so use default
                   11297: 		 # as value
1.599     albertel 11298: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11299: 			} elsif ( $internaltext =~ /\S/ ) {
                   11300: 		  # something interesting inside the tag
                   11301: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11302: 			} else {
1.908     albertel 11303: 		  # no interesting values, don't set a default
1.339     albertel 11304: 			}
1.172     www      11305: # end of not-a-package not-a-library import
1.339     albertel 11306: 		    }
1.172     www      11307: # end of not-a-package start tag
1.339     albertel 11308: 		}
1.172     www      11309: # the next is the end of "start tag"
1.339     albertel 11310: 	    }
                   11311: 	}
1.483     albertel 11312: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11313: 	$extension = lc($extension);
                   11314: 	if ($extension eq 'htm') { $extension='html'; }
                   11315: 
1.737     albertel 11316: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11317: 	    #no specific packages #how's our extension
                   11318: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11319: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11320: 					 \%metathesekeys);
                   11321: 	}
1.883     albertel 11322: 
                   11323: 	if (!exists($metaentry{':packages'})
                   11324: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11325: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11326: 		#no specific packages well let's get default then
                   11327: 		if ($key!~/^default&/) { next; }
1.488     albertel 11328: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11329: 					     \%metathesekeys);
                   11330: 	    }
                   11331: 	}
1.338     www      11332: # are there custom rights to evaluate
1.599     albertel 11333: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11334: 
1.338     www      11335:     #
                   11336:     # Importing a rights file here
1.339     albertel 11337:     #
                   11338: 	    unless ($depthcount) {
1.599     albertel 11339: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11340: 		my $dir=$filename;
                   11341: 		$dir=~s|[^/]*$||;
                   11342: 		$location=&filelocation($dir,$location);
1.736     albertel 11343: 		my $rights_metadata =
                   11344: 		    &metadata($uri,'keys',$location,'_rights',
                   11345: 			      $depthcount+1);
                   11346: 		foreach my $rights (split(',',$rights_metadata)) {
                   11347: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11348: 		    $metathesekeys{$rights}=1;
1.339     albertel 11349: 		}
                   11350: 	    }
                   11351: 	}
1.737     albertel 11352: 	# uniqifiy package listing
                   11353: 	my %seen;
                   11354: 	my @uniq_packages =
                   11355: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11356: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11357: 
1.1070    www      11358:         if ($importedparts) {
                   11359: # We had imported parts and need to rebuild partorder
                   11360:            $metaentry{':partorder'}='';
                   11361:            $metathesekeys{'partorder'}=1;
                   11362:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   11363:                if ($origfileimportpartids[$index] eq 'part') {
                   11364: # original part, part of the problem
                   11365:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   11366:                } else {
                   11367: # we have imported parts at this position
                   11368:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   11369:                }
                   11370:            }
                   11371:            $metaentry{':partorder'}=~s/^\,//;
                   11372:         }
                   11373: 
1.737     albertel 11374: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11375: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  11376: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 11377: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      11378: # this is the end of "was not already recently cached
1.71      www      11379:     }
1.599     albertel 11380:     return $metaentry{':'.$what};
1.261     albertel 11381: }
                   11382: 
1.488     albertel 11383: sub metadata_create_package_def {
1.483     albertel 11384:     my ($uri,$key,$package,$metathesekeys)=@_;
                   11385:     my ($pack,$name,$subp)=split(/\&/,$key);
                   11386:     if ($subp eq 'default') { next; }
                   11387:     
1.599     albertel 11388:     if (defined($metaentry{':packages'})) {
                   11389: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 11390:     } else {
1.599     albertel 11391: 	$metaentry{':packages'}=$package;
1.483     albertel 11392:     }
                   11393:     my $value=$packagetab{$key};
                   11394:     my $unikey;
                   11395:     $unikey='parameter_0_'.$name;
1.599     albertel 11396:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 11397:     $$metathesekeys{$unikey}=1;
1.599     albertel 11398:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11399: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 11400:     }
1.599     albertel 11401:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   11402: 	$metaentry{':'.$unikey}=
                   11403: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 11404:     }
                   11405: }
                   11406: 
1.261     albertel 11407: sub metadata_generate_part0 {
                   11408:     my ($metadata,$metacache,$uri) = @_;
                   11409:     my %allnames;
1.737     albertel 11410:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 11411: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 11412: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   11413: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 11414: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 11415: 	    $allnames{$name}=$part;
                   11416: 	  }
                   11417: 	}
                   11418:     }
                   11419:     foreach my $name (keys(%allnames)) {
                   11420:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 11421:       my $key=":parameter_0_$name";
1.261     albertel 11422:       $$metacache{"$key.part"}='0';
                   11423:       $$metacache{"$key.name"}=$name;
1.428     albertel 11424:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 11425: 					   $allnames{$name}.'_'.$name.
                   11426: 					   '.type'};
1.428     albertel 11427:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 11428: 			     '.display'};
1.644     www      11429:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11430:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11431:       $$metacache{"$key.display"}=$olddis;
                   11432:     }
1.71      www      11433: }
                   11434: 
1.764     albertel 11435: # ------------------------------------------------------ Devalidate title cache
                   11436: 
                   11437: sub devalidate_title_cache {
                   11438:     my ($url)=@_;
                   11439:     if (!$env{'request.course.id'}) { return; }
                   11440:     my $symb=&symbread($url);
                   11441:     if (!$symb) { return; }
                   11442:     my $key=$env{'request.course.id'}."\0".$symb;
                   11443:     &devalidate_cache_new('title',$key);
                   11444: }
                   11445: 
1.1014    droeschl 11446: # ------------------------------------------------- Get the title of a course
                   11447: 
                   11448: sub current_course_title {
                   11449:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11450: }
1.301     www      11451: # ------------------------------------------------- Get the title of a resource
                   11452: 
                   11453: sub gettitle {
                   11454:     my $urlsymb=shift;
                   11455:     my $symb=&symbread($urlsymb);
1.534     albertel 11456:     if ($symb) {
1.620     albertel 11457: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11458: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11459: 	if (defined($cached)) { 
                   11460: 	    return $result;
                   11461: 	}
1.534     albertel 11462: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11463: 	my $title='';
1.907     albertel 11464: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11465: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11466: 	} else {
                   11467: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11468: 		    &GDBM_READER(),0640)) {
                   11469: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11470: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11471: 		untie(%bighash);
                   11472: 	    }
1.534     albertel 11473: 	}
                   11474: 	$title=~s/\&colon\;/\:/gs;
                   11475: 	if ($title) {
1.1159    www      11476: # Remember both $symb and $title for dynamic metadata
                   11477:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11478:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11479: # Cache this title and then return it
1.599     albertel 11480: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11481: 	}
                   11482: 	$urlsymb=$url;
                   11483:     }
                   11484:     my $title=&metadata($urlsymb,'title');
                   11485:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11486:     return $title;
1.301     www      11487: }
1.613     albertel 11488: 
1.614     albertel 11489: sub get_slot {
                   11490:     my ($which,$cnum,$cdom)=@_;
                   11491:     if (!$cnum || !$cdom) {
1.790     albertel 11492: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11493: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11494: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11495:     }
1.703     albertel 11496:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11497:     my %slotinfo;
                   11498:     if (exists($remembered{$key})) {
                   11499: 	$slotinfo{$which} = $remembered{$key};
                   11500:     } else {
                   11501: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11502: 	&Apache::lonhomework::showhash(%slotinfo);
                   11503: 	my ($tmp)=keys(%slotinfo);
                   11504: 	if ($tmp=~/^error:/) { return (); }
                   11505: 	$remembered{$key} = $slotinfo{$which};
                   11506:     }
1.616     albertel 11507:     if (ref($slotinfo{$which}) eq 'HASH') {
                   11508: 	return %{$slotinfo{$which}};
                   11509:     }
                   11510:     return $slotinfo{$which};
1.614     albertel 11511: }
1.1150    raeburn  11512: 
                   11513: sub get_reservable_slots {
                   11514:     my ($cnum,$cdom,$uname,$udom) = @_;
                   11515:     my $now = time;
                   11516:     my $reservable_info;
                   11517:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   11518:     if (exists($remembered{$key})) {
                   11519:         $reservable_info = $remembered{$key};
                   11520:     } else {
                   11521:         my %resv;
                   11522:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   11523:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   11524:         $reservable_info = \%resv;
                   11525:         $remembered{$key} = $reservable_info;
                   11526:     }
                   11527:     return $reservable_info;
                   11528: }
                   11529: 
                   11530: sub get_course_slots {
                   11531:     my ($cnum,$cdom) = @_;
                   11532:     my $hashid=$cnum.':'.$cdom;
                   11533:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   11534:     if (defined($cached)) {
                   11535:         if (ref($result) eq 'HASH') {
                   11536:             return %{$result};
                   11537:         }
                   11538:     } else {
                   11539:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   11540:         my ($tmp) = keys(%slots);
                   11541:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  11542:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  11543:             return %slots;
                   11544:         }
                   11545:     }
                   11546:     return;
                   11547: }
                   11548: 
                   11549: sub devalidate_slots_cache {
                   11550:     my ($cnum,$cdom)=@_;
                   11551:     my $hashid=$cnum.':'.$cdom;
                   11552:     &devalidate_cache_new('allslots',$hashid);
                   11553: }
                   11554: 
1.1181    raeburn  11555: sub get_coursechange {
                   11556:     my ($cdom,$cnum) = @_;
                   11557:     if ($cdom eq '' || $cnum eq '') {
                   11558:         return unless ($env{'request.course.id'});
                   11559:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11560:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11561:     }
                   11562:     my $hashid=$cdom.'_'.$cnum;
                   11563:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   11564:     if ((defined($cached)) && ($change ne '')) {
                   11565:         return $change;
                   11566:     } else {
                   11567:         my %crshash;
                   11568:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   11569:         if ($crshash{'internal.contentchange'} eq '') {
                   11570:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   11571:             if ($change eq '') {
                   11572:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   11573:                 $change = $crshash{'internal.created'};
                   11574:             }
                   11575:         } else {
                   11576:             $change = $crshash{'internal.contentchange'};
                   11577:         }
                   11578:         my $cachetime = 600;
                   11579:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   11580:     }
                   11581:     return $change;
                   11582: }
                   11583: 
                   11584: sub devalidate_coursechange_cache {
                   11585:     my ($cnum,$cdom)=@_;
                   11586:     my $hashid=$cnum.':'.$cdom;
                   11587:     &devalidate_cache_new('crschange',$hashid);
                   11588: }
                   11589: 
1.31      www      11590: # ------------------------------------------------- Update symbolic store links
                   11591: 
                   11592: sub symblist {
                   11593:     my ($mapname,%newhash)=@_;
1.438     www      11594:     $mapname=&deversion(&declutter($mapname));
1.31      www      11595:     my %hash;
1.620     albertel 11596:     if (($env{'request.course.fn'}) && (%newhash)) {
                   11597:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11598:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  11599: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 11600: 		next if ($url eq 'last_known'
                   11601: 			 && $env{'form.no_update_last_known'});
                   11602: 		$hash{declutter($url)}=&encode_symb($mapname,
                   11603: 						    $newhash{$url}->[1],
                   11604: 						    $newhash{$url}->[0]);
1.191     harris41 11605:             }
1.31      www      11606:             if (untie(%hash)) {
                   11607: 		return 'ok';
                   11608:             }
                   11609:         }
                   11610:     }
                   11611:     return 'error';
1.212     www      11612: }
                   11613: 
                   11614: # --------------------------------------------------------------- Verify a symb
                   11615: 
                   11616: sub symbverify {
1.1190    raeburn  11617:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      11618:     my $thisfn=$thisurl;
1.439     www      11619:     $thisfn=&declutter($thisfn);
1.215     www      11620: # direct jump to resource in page or to a sequence - will construct own symbs
                   11621:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   11622: # check URL part
1.409     www      11623:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      11624: 
1.431     www      11625:     unless ($url eq $thisfn) { return 0; }
1.213     www      11626: 
1.216     www      11627:     $symb=&symbclean($symb);
1.510     www      11628:     $thisurl=&deversion($thisurl);
1.439     www      11629:     $thisfn=&deversion($thisfn);
1.213     www      11630: 
                   11631:     my %bighash;
                   11632:     my $okay=0;
1.431     www      11633: 
1.620     albertel 11634:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11635:                             &GDBM_READER(),0640)) {
1.1204    raeburn  11636:         my $noclutter;
1.1032    raeburn  11637:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   11638:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  11639:             if ($map =~ m{^uploaded/.+\.page$}) {
                   11640:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   11641:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   11642:                 $noclutter = 1;
                   11643:             }
                   11644:         }
                   11645:         my $ids;
                   11646:         if ($noclutter) {
                   11647:             $ids=$bighash{'ids_'.$thisurl};
                   11648:         } else {
                   11649:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  11650:         }
1.1102    raeburn  11651:         unless ($ids) {
                   11652:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   11653:             $ids=$bighash{$idkey};
1.216     www      11654:         }
                   11655:         if ($ids) {
                   11656: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  11657:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  11658:                 $symb =~ s/\?.+$//;
1.1202    raeburn  11659:             }
1.800     albertel 11660: 	    foreach my $id (split(/\,/,$ids)) {
                   11661: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      11662:                if (
                   11663:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  11664:    eq $symb) {
                   11665:                    if (ref($encstate)) {
                   11666:                        $$encstate = $bighash{'encrypted_'.$id};
                   11667:                    }
1.620     albertel 11668: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  11669: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   11670:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  11671: 		       $okay=1;
1.1202    raeburn  11672:                        last;
1.582     albertel 11673: 		   }
                   11674: 	       }
1.216     www      11675: 	   }
                   11676:         }
1.213     www      11677: 	untie(%bighash);
                   11678:     }
                   11679:     return $okay;
1.31      www      11680: }
                   11681: 
1.210     www      11682: # --------------------------------------------------------------- Clean-up symb
                   11683: 
                   11684: sub symbclean {
                   11685:     my $symb=shift;
1.568     albertel 11686:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11687: # remove version from map
                   11688:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11689: 
1.210     www      11690: # remove version from URL
                   11691:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      11692: 
1.507     www      11693: # remove wrapper
                   11694: 
1.510     www      11695:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 11696:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      11697:     return $symb;
1.409     www      11698: }
                   11699: 
                   11700: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 11701: 
                   11702: sub encode_symb {
                   11703:     my ($map,$resid,$url)=@_;
                   11704:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   11705: }
1.409     www      11706: 
                   11707: sub decode_symb {
1.568     albertel 11708:     my $symb=shift;
                   11709:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   11710:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      11711:     return (&fixversion($map),$resid,&fixversion($url));
                   11712: }
                   11713: 
                   11714: sub fixversion {
                   11715:     my $fn=shift;
1.609     banghart 11716:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      11717:     my %bighash;
                   11718:     my $uri=&clutter($fn);
1.620     albertel 11719:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      11720: # is this cached?
1.599     albertel 11721:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      11722:     if (defined($cached)) { return $result; }
                   11723: # unfortunately not cached, or expired
1.620     albertel 11724:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      11725: 	    &GDBM_READER(),0640)) {
                   11726:  	if ($bighash{'version_'.$uri}) {
                   11727:  	    my $version=$bighash{'version_'.$uri};
1.444     www      11728:  	    unless (($version eq 'mostrecent') || 
                   11729: 		    ($version==&getversion($uri))) {
1.440     www      11730:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   11731:  	    }
                   11732:  	}
                   11733:  	untie %bighash;
1.413     www      11734:     }
1.599     albertel 11735:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      11736: }
                   11737: 
                   11738: sub deversion {
                   11739:     my $url=shift;
                   11740:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   11741:     return $url;
1.210     www      11742: }
                   11743: 
1.31      www      11744: # ------------------------------------------------------ Return symb list entry
                   11745: 
                   11746: sub symbread {
1.1282    raeburn  11747:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  11748:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  11749:     if (defined($env{$cache_str})) {
                   11750:         if ($ignorecachednull) {
                   11751:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   11752:         } else {
                   11753:             return $env{$cache_str};
                   11754:         }
                   11755:     }
1.242     www      11756: # no filename provided? try from environment
1.1265    raeburn  11757:     unless ($thisfn) {
1.620     albertel 11758:         if ($env{'request.symb'}) {
                   11759: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 11760: 	}
1.620     albertel 11761: 	$thisfn=$env{'request.filename'};
1.44      www      11762:     }
1.569     albertel 11763:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      11764: # is that filename actually a symb? Verify, clean, and return
                   11765:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 11766: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 11767: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 11768: 	}
1.242     www      11769:     }
1.44      www      11770:     $thisfn=declutter($thisfn);
1.31      www      11771:     my %hash;
1.37      www      11772:     my %bighash;
                   11773:     my $syval='';
1.620     albertel 11774:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  11775:         my $targetfn = $thisfn;
1.609     banghart 11776:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  11777:             $targetfn = 'adm/wrapper/'.$thisfn;
                   11778:         }
1.687     albertel 11779: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   11780: 	    $targetfn=$1;
                   11781: 	}
1.620     albertel 11782:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11783:                       &GDBM_READER(),0640)) {
1.481     raeburn  11784: 	    $syval=$hash{$targetfn};
1.37      www      11785:             untie(%hash);
                   11786:         }
                   11787: # ---------------------------------------------------------- There was an entry
                   11788:         if ($syval) {
1.601     albertel 11789: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 11790: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  11791: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11792: 		    #return $env{$cache_str}='';
1.601     albertel 11793: 		#}    
                   11794: 		#$syval.=$1;
                   11795: 	    #}
1.37      www      11796:         } else {
                   11797: # ------------------------------------------------------- Was not in symb table
1.620     albertel 11798:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11799:                             &GDBM_READER(),0640)) {
1.37      www      11800: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      11801:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      11802:               unless ($ids) { 
                   11803:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      11804:               }
                   11805:               unless ($ids) {
                   11806: # alias?
                   11807: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      11808:               }
1.37      www      11809:               if ($ids) {
                   11810: # ------------------------------------------------------------------- Has ID(s)
                   11811:                  my @possibilities=split(/\,/,$ids);
1.39      www      11812:                  if ($#possibilities==0) {
                   11813: # ----------------------------------------------- There is only one possibility
1.37      www      11814: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 11815: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11816: 						    $resid,$thisfn);
1.1282    raeburn  11817:                      if (ref($possibles) eq 'HASH') {
                   11818:                          $possibles->{$syval} = 1;    
                   11819:                      }
                   11820:                      if ($checkforblock) {
                   11821:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   11822:                          if (@blockers) {
                   11823:                              $syval = '';
                   11824:                              return;
                   11825:                          }
                   11826:                      }
                   11827:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      11828: # ------------------------------------------ There is more than one possibility
                   11829:                      my $realpossible=0;
1.800     albertel 11830:                      foreach my $id (@possibilities) {
                   11831: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  11832:                          my $canaccess;
                   11833:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   11834:                              $canaccess = 1;
                   11835:                          } else { 
                   11836:                              $canaccess = &allowed('bre',$file);
                   11837:                          }
                   11838:                          if ($canaccess) {
                   11839:          		     my ($mapid,$resid)=split(/\./,$id);
                   11840:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11841:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11842: 						             $resid,$thisfn);
                   11843:                                  if (ref($possibles) eq 'HASH') {
                   11844:                                      $possibles->{$syval} = 1;
                   11845:                                  }
                   11846:                                  if ($checkforblock) {
                   11847:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   11848:                                      unless (@blockers > 0) {
                   11849:                                          $syval = $poss_syval;
                   11850:                                          $realpossible++;
                   11851:                                      }
                   11852:                                  } else {
                   11853:                                      $syval = $poss_syval;
                   11854:                                      $realpossible++;
                   11855:                                  }
                   11856:                              }
1.39      www      11857: 			 }
1.191     harris41 11858:                      }
1.39      www      11859: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11860:                  } else {
                   11861:                      $syval='';
1.37      www      11862:                  }
                   11863: 	      }
1.1282    raeburn  11864:               untie(%bighash);
1.481     raeburn  11865:            }
1.31      www      11866:         }
1.62      www      11867:         if ($syval) {
1.620     albertel 11868: 	    return $env{$cache_str}=$syval;
1.62      www      11869:         }
1.31      www      11870:     }
1.949     raeburn  11871:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11872:     return $env{$cache_str}='';
1.31      www      11873: }
                   11874: 
                   11875: # ---------------------------------------------------------- Return random seed
                   11876: 
1.32      www      11877: sub numval {
                   11878:     my $txt=shift;
                   11879:     $txt=~tr/A-J/0-9/;
                   11880:     $txt=~tr/a-j/0-9/;
                   11881:     $txt=~tr/K-T/0-9/;
                   11882:     $txt=~tr/k-t/0-9/;
                   11883:     $txt=~tr/U-Z/0-5/;
                   11884:     $txt=~tr/u-z/0-5/;
                   11885:     $txt=~s/\D//g;
1.564     albertel 11886:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      11887:     return int($txt);
1.368     albertel 11888: }
                   11889: 
1.484     albertel 11890: sub numval2 {
                   11891:     my $txt=shift;
                   11892:     $txt=~tr/A-J/0-9/;
                   11893:     $txt=~tr/a-j/0-9/;
                   11894:     $txt=~tr/K-T/0-9/;
                   11895:     $txt=~tr/k-t/0-9/;
                   11896:     $txt=~tr/U-Z/0-5/;
                   11897:     $txt=~tr/u-z/0-5/;
                   11898:     $txt=~s/\D//g;
                   11899:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11900:     my $total;
                   11901:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 11902:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 11903:     return int($total);
                   11904: }
                   11905: 
1.575     albertel 11906: sub numval3 {
                   11907:     use integer;
                   11908:     my $txt=shift;
                   11909:     $txt=~tr/A-J/0-9/;
                   11910:     $txt=~tr/a-j/0-9/;
                   11911:     $txt=~tr/K-T/0-9/;
                   11912:     $txt=~tr/k-t/0-9/;
                   11913:     $txt=~tr/U-Z/0-5/;
                   11914:     $txt=~tr/u-z/0-5/;
                   11915:     $txt=~s/\D//g;
                   11916:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11917:     my $total;
                   11918:     foreach my $val (@txts) { $total+=$val; }
                   11919:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11920:     return $total;
                   11921: }
                   11922: 
1.675     albertel 11923: sub digest {
                   11924:     my ($data)=@_;
                   11925:     my $digest=&Digest::MD5::md5($data);
                   11926:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11927:     my ($e,$f);
                   11928:     {
                   11929:         use integer;
                   11930:         $e=($a+$b);
                   11931:         $f=($c+$d);
                   11932:         if ($_64bit) {
                   11933:             $e=(($e<<32)>>32);
                   11934:             $f=(($f<<32)>>32);
                   11935:         }
                   11936:     }
                   11937:     if (wantarray) {
                   11938: 	return ($e,$f);
                   11939:     } else {
                   11940: 	my $g;
                   11941: 	{
                   11942: 	    use integer;
                   11943: 	    $g=($e+$f);
                   11944: 	    if ($_64bit) {
                   11945: 		$g=(($g<<32)>>32);
                   11946: 	    }
                   11947: 	}
                   11948: 	return $g;
                   11949:     }
                   11950: }
                   11951: 
1.368     albertel 11952: sub latest_rnd_algorithm_id {
1.675     albertel 11953:     return '64bit5';
1.366     albertel 11954: }
1.32      www      11955: 
1.503     albertel 11956: sub get_rand_alg {
                   11957:     my ($courseid)=@_;
1.790     albertel 11958:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 11959:     if ($courseid) {
1.620     albertel 11960: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 11961:     }
                   11962:     return &latest_rnd_algorithm_id();
                   11963: }
                   11964: 
1.562     albertel 11965: sub validCODE {
                   11966:     my ($CODE)=@_;
                   11967:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   11968:     return 0;
                   11969: }
                   11970: 
1.491     albertel 11971: sub getCODE {
1.620     albertel 11972:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 11973:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   11974: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   11975: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 11976: 	return $Apache::lonhomework::history{'resource.CODE'};
                   11977:     }
                   11978:     return undef;
                   11979: }
1.1133    foxr     11980: #
                   11981: #  Determines the random seed for a specific context:
                   11982: #
                   11983: # parameters:
                   11984: #   symb      - in course context the symb for the seed.
                   11985: #   course_id - The course id of the form domain_coursenum.
                   11986: #   domain    - Domain for the user.
                   11987: #   course    - Course for the user.
                   11988: #   cenv      - environment of the course.
                   11989: #
                   11990: # NOTE:
                   11991: #   All parameters are picked out of the environment if missing
                   11992: #   or not defined.
                   11993: #   If a symb cannot be determined the current time is used instead.
                   11994: #
                   11995: #  For a given well defined symb, courside, domain, username,
                   11996: #  and course environment, the seed is reproducible.
                   11997: #
1.31      www      11998: sub rndseed {
1.1133    foxr     11999:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12000:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12001:     if (!defined($symb)) {
1.366     albertel 12002: 	unless ($symb=$wsymb) { return time; }
                   12003:     }
1.1146    foxr     12004:     if (!defined $courseid) { 
                   12005: 	$courseid=$wcourseid; 
                   12006:     }
                   12007:     if (!defined $domain) { $domain=$wdomain; }
                   12008:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12009: 
                   12010:     my $which;
                   12011:     if (defined($cenv->{'rndseed'})) {
                   12012: 	$which = $cenv->{'rndseed'};
                   12013:     } else {
                   12014: 	$which =&get_rand_alg($courseid);
                   12015:     }
1.491     albertel 12016:     if (defined(&getCODE())) {
1.1133    foxr     12017: 
1.675     albertel 12018: 	if ($which eq '64bit5') {
                   12019: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12020: 	} elsif ($which eq '64bit4') {
1.575     albertel 12021: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12022: 	} else {
                   12023: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12024: 	}
1.675     albertel 12025:     } elsif ($which eq '64bit5') {
                   12026: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12027:     } elsif ($which eq '64bit4') {
                   12028: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12029:     } elsif ($which eq '64bit3') {
                   12030: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12031:     } elsif ($which eq '64bit2') {
                   12032: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12033:     } elsif ($which eq '64bit') {
                   12034: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12035:     }
                   12036:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12037: }
                   12038: 
                   12039: sub rndseed_32bit {
                   12040:     my ($symb,$courseid,$domain,$username)=@_;
                   12041:     {
                   12042: 	use integer;
                   12043: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12044: 	my $symbseed=numval($symb) << 22;
                   12045: 	my $namechck=unpack("%32C*",$username) << 17;
                   12046: 	my $nameseed=numval($username) << 12;
                   12047: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12048: 	my $courseseed=unpack("%32C*",$courseid);
                   12049: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12050: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12051: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12052: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12053: 	return $num;
                   12054:     }
                   12055: }
                   12056: 
                   12057: sub rndseed_64bit {
                   12058:     my ($symb,$courseid,$domain,$username)=@_;
                   12059:     {
                   12060: 	use integer;
                   12061: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12062: 	my $symbseed=numval($symb) << 10;
                   12063: 	my $namechck=unpack("%32S*",$username);
                   12064: 	
                   12065: 	my $nameseed=numval($username) << 21;
                   12066: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12067: 	my $courseseed=unpack("%32S*",$courseid);
                   12068: 	
                   12069: 	my $num1=$symbchck+$symbseed+$namechck;
                   12070: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12071: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12072: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12073: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12074: 	return "$num1,$num2";
1.155     albertel 12075:     }
1.366     albertel 12076: }
                   12077: 
1.443     albertel 12078: sub rndseed_64bit2 {
                   12079:     my ($symb,$courseid,$domain,$username)=@_;
                   12080:     {
                   12081: 	use integer;
                   12082: 	# strings need to be an even # of cahracters long, it it is odd the
                   12083:         # last characters gets thrown away
                   12084: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12085: 	my $symbseed=numval($symb) << 10;
                   12086: 	my $namechck=unpack("%32S*",$username.' ');
                   12087: 	
                   12088: 	my $nameseed=numval($username) << 21;
1.501     albertel 12089: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12090: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12091: 	
                   12092: 	my $num1=$symbchck+$symbseed+$namechck;
                   12093: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12094: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12095: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12096: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12097: 	return "$num1,$num2";
                   12098:     }
                   12099: }
                   12100: 
                   12101: sub rndseed_64bit3 {
                   12102:     my ($symb,$courseid,$domain,$username)=@_;
                   12103:     {
                   12104: 	use integer;
                   12105: 	# strings need to be an even # of cahracters long, it it is odd the
                   12106:         # last characters gets thrown away
                   12107: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12108: 	my $symbseed=numval2($symb) << 10;
                   12109: 	my $namechck=unpack("%32S*",$username.' ');
                   12110: 	
                   12111: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12112: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12113: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12114: 	
                   12115: 	my $num1=$symbchck+$symbseed+$namechck;
                   12116: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12117: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12118: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12119: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12120: 	
1.503     albertel 12121: 	return "$num1:$num2";
1.443     albertel 12122:     }
                   12123: }
                   12124: 
1.575     albertel 12125: sub rndseed_64bit4 {
                   12126:     my ($symb,$courseid,$domain,$username)=@_;
                   12127:     {
                   12128: 	use integer;
                   12129: 	# strings need to be an even # of cahracters long, it it is odd the
                   12130:         # last characters gets thrown away
                   12131: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12132: 	my $symbseed=numval3($symb) << 10;
                   12133: 	my $namechck=unpack("%32S*",$username.' ');
                   12134: 	
                   12135: 	my $nameseed=numval3($username) << 21;
                   12136: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12137: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12138: 	
                   12139: 	my $num1=$symbchck+$symbseed+$namechck;
                   12140: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12141: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12142: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12143: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12144: 	
1.575     albertel 12145: 	return "$num1:$num2";
                   12146:     }
                   12147: }
                   12148: 
1.675     albertel 12149: sub rndseed_64bit5 {
                   12150:     my ($symb,$courseid,$domain,$username)=@_;
                   12151:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12152:     return "$num1:$num2";
                   12153: }
                   12154: 
1.366     albertel 12155: sub rndseed_CODE_64bit {
                   12156:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12157:     {
1.366     albertel 12158: 	use integer;
1.443     albertel 12159: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12160: 	my $symbseed=numval2($symb);
1.491     albertel 12161: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12162: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12163: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12164: 	my $num1=$symbseed+$CODEchck;
                   12165: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12166: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12167: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12168: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12169: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12170: 	return "$num1:$num2";
1.366     albertel 12171:     }
                   12172: }
                   12173: 
1.575     albertel 12174: sub rndseed_CODE_64bit4 {
                   12175:     my ($symb,$courseid,$domain,$username)=@_;
                   12176:     {
                   12177: 	use integer;
                   12178: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12179: 	my $symbseed=numval3($symb);
                   12180: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12181: 	my $CODEseed=numval3(&getCODE());
                   12182: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12183: 	my $num1=$symbseed+$CODEchck;
                   12184: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12185: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12186: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12187: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12188: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12189: 	return "$num1:$num2";
                   12190:     }
                   12191: }
                   12192: 
1.675     albertel 12193: sub rndseed_CODE_64bit5 {
                   12194:     my ($symb,$courseid,$domain,$username)=@_;
                   12195:     my $code = &getCODE();
                   12196:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12197:     return "$num1:$num2";
                   12198: }
                   12199: 
1.366     albertel 12200: sub setup_random_from_rndseed {
                   12201:     my ($rndseed)=@_;
1.503     albertel 12202:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  12203:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12204:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12205:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12206:         } else {
                   12207:             &Math::Random::random_set_seed($num1,$num2);
                   12208:         }
1.366     albertel 12209:     } else {
                   12210: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12211:     }
1.36      albertel 12212: }
                   12213: 
1.474     albertel 12214: sub latest_receipt_algorithm_id {
1.835     albertel 12215:     return 'receipt3';
1.474     albertel 12216: }
                   12217: 
1.480     www      12218: sub recunique {
                   12219:     my $fucourseid=shift;
                   12220:     my $unique;
1.835     albertel 12221:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12222: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12223: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12224:     } else {
                   12225: 	$unique=$perlvar{'lonReceipt'};
                   12226:     }
                   12227:     return unpack("%32C*",$unique);
                   12228: }
                   12229: 
                   12230: sub recprefix {
                   12231:     my $fucourseid=shift;
                   12232:     my $prefix;
1.835     albertel 12233:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12234: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12235: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12236:     } else {
                   12237: 	$prefix=$perlvar{'lonHostID'};
                   12238:     }
                   12239:     return unpack("%32C*",$prefix);
                   12240: }
                   12241: 
1.76      www      12242: sub ireceipt {
1.474     albertel 12243:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12244: 
                   12245:     my $return =&recprefix($fucourseid).'-';
                   12246: 
                   12247:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12248: 	$env{'request.state'} eq 'construct') {
                   12249: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12250: 	return $return;
                   12251:     }
                   12252: 
1.76      www      12253:     my $cuname=unpack("%32C*",$funame);
                   12254:     my $cudom=unpack("%32C*",$fudom);
                   12255:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12256:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12257:     my $cunique=&recunique($fucourseid);
1.474     albertel 12258:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12259:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12260: 
1.790     albertel 12261: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12262: 			       
                   12263: 	$return.= ($cunique%$cuname+
                   12264: 		   $cunique%$cudom+
                   12265: 		   $cusymb%$cuname+
                   12266: 		   $cusymb%$cudom+
                   12267: 		   $cucourseid%$cuname+
                   12268: 		   $cucourseid%$cudom+
                   12269: 		   $cpart%$cuname+
                   12270: 		   $cpart%$cudom);
                   12271:     } else {
                   12272: 	$return.= ($cunique%$cuname+
                   12273: 		   $cunique%$cudom+
                   12274: 		   $cusymb%$cuname+
                   12275: 		   $cusymb%$cudom+
                   12276: 		   $cucourseid%$cuname+
                   12277: 		   $cucourseid%$cudom);
                   12278:     }
                   12279:     return $return;
1.76      www      12280: }
                   12281: 
                   12282: sub receipt {
1.474     albertel 12283:     my ($part)=@_;
1.790     albertel 12284:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12285:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12286: }
1.260     ng       12287: 
1.790     albertel 12288: sub whichuser {
                   12289:     my ($passedsymb)=@_;
                   12290:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12291:     if (defined($env{'form.grade_symb'})) {
                   12292: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12293: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12294: 	if (!$allowed &&
                   12295: 	    exists($env{'request.course.sec'}) &&
                   12296: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12297: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12298: 			      '/'.$env{'request.course.sec'});
                   12299: 	}
                   12300: 	if ($allowed) {
                   12301: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12302: 	    $courseid=$tmp_courseid;
                   12303: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12304: 	    ($name)=&get_env_multiple('form.grade_username');
                   12305: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12306: 	}
                   12307:     }
                   12308:     if (!$passedsymb) {
                   12309: 	$symb=&symbread();
                   12310:     } else {
                   12311: 	$symb=$passedsymb;
                   12312:     }
                   12313:     $courseid=$env{'request.course.id'};
                   12314:     $domain=$env{'user.domain'};
                   12315:     $name=$env{'user.name'};
                   12316:     if ($name eq 'public' && $domain eq 'public') {
                   12317: 	if (!defined($env{'form.username'})) {
                   12318: 	    $env{'form.username'}.=time.rand(10000000);
                   12319: 	}
                   12320: 	$name.=$env{'form.username'};
                   12321:     }
                   12322:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12323: 
                   12324: }
                   12325: 
1.36      albertel 12326: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12327: # returns either the contents of the file or 
                   12328: # -1 if the file doesn't exist
1.481     raeburn  12329: #
                   12330: # if the target is a file that was uploaded via DOCS, 
                   12331: # a check will be made to see if a current copy exists on the local server,
                   12332: # if it does this will be served, otherwise a copy will be retrieved from
                   12333: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12334: # the local server.   
1.472     albertel 12335: 
1.36      albertel 12336: sub getfile {
1.538     albertel 12337:     my ($file) = @_;
1.609     banghart 12338:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12339:     &repcopy($file);
                   12340:     return &readfile($file);
                   12341: }
                   12342: 
                   12343: sub repcopy_userfile {
                   12344:     my ($file)=@_;
1.1142    raeburn  12345:     my $londocroot = $perlvar{'lonDocRoot'};
                   12346:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12347:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12348:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12349: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12350:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12351:     if (-e "$file") {
1.828     www      12352: # we already have a local copy, check it out
1.538     albertel 12353: 	my @fileinfo = stat($file);
1.828     www      12354: 	my $rtncode;
                   12355: 	my $info;
1.538     albertel 12356: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12357: 	if ($lwpresp ne 'ok') {
1.828     www      12358: # there is no such file anymore, even though we had a local copy
1.482     albertel 12359: 	    if ($rtncode eq '404') {
1.538     albertel 12360: 		unlink($file);
1.482     albertel 12361: 	    }
                   12362: 	    return -1;
                   12363: 	}
                   12364: 	if ($info < $fileinfo[9]) {
1.828     www      12365: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12366: 	    return 'ok';
1.828     www      12367: 	} else {
                   12368: # the file is outdated, get rid of it
                   12369: 	    unlink($file);
1.482     albertel 12370: 	}
1.828     www      12371:     }
                   12372: # one way or the other, at this point, we don't have the file
                   12373: # construct the correct path for the file
                   12374:     my @parts = ($cdom,$cnum); 
                   12375:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12376: 	push @parts, split(/\//,$1);
                   12377:     }
                   12378:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   12379:     foreach my $part (@parts) {
                   12380: 	$path .= '/'.$part;
                   12381: 	if (!-e $path) {
                   12382: 	    mkdir($path,0770);
1.482     albertel 12383: 	}
                   12384:     }
1.828     www      12385: # now the path exists for sure
                   12386: # get a user agent
                   12387:     my $ua=new LWP::UserAgent;
                   12388:     my $transferfile=$file.'.in.transfer';
                   12389: # FIXME: this should flock
                   12390:     if (-e $transferfile) { return 'ok'; }
                   12391:     my $request;
                   12392:     $uri=~s/^\///;
1.980     raeburn  12393:     my $homeserver = &homeserver($cnum,$cdom);
                   12394:     my $protocol = $protocol{$homeserver};
                   12395:     $protocol = 'http' if ($protocol ne 'https');
                   12396:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      12397:     my $response=$ua->request($request,$transferfile);
                   12398: # did it work?
                   12399:     if ($response->is_error()) {
                   12400: 	unlink($transferfile);
                   12401: 	&logthis("Userfile repcopy failed for $uri");
                   12402: 	return -1;
                   12403:     }
                   12404: # worked, rename the transfer file
                   12405:     rename($transferfile,$file);
1.607     raeburn  12406:     return 'ok';
1.481     raeburn  12407: }
                   12408: 
1.517     albertel 12409: sub tokenwrapper {
                   12410:     my $uri=shift;
1.980     raeburn  12411:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 12412:     $uri=~s|^/||;
1.620     albertel 12413:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 12414:     my $token=$1;
1.552     albertel 12415:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   12416:     if ($udom && $uname && $file) {
                   12417: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  12418:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  12419:         my $homeserver = &homeserver($uname,$udom);
                   12420:         my $protocol = $protocol{$homeserver};
                   12421:         $protocol = 'http' if ($protocol ne 'https');
                   12422:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 12423:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   12424:                                '&tokenissued='.$perlvar{'lonHostID'};
                   12425:     } else {
                   12426:         return '/adm/notfound.html';
                   12427:     }
                   12428: }
                   12429: 
1.828     www      12430: # call with reqtype HEAD: get last modification time
                   12431: # call with reqtype GET: get the file contents
                   12432: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12433: #
1.481     raeburn  12434: sub getuploaded {
                   12435:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12436:     $uri=~s/^\///;
1.980     raeburn  12437:     my $homeserver = &homeserver($cnum,$cdom);
                   12438:     my $protocol = $protocol{$homeserver};
                   12439:     $protocol = 'http' if ($protocol ne 'https');
                   12440:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12441:     my $ua=new LWP::UserAgent;
                   12442:     my $request=new HTTP::Request($reqtype,$uri);
                   12443:     my $response=$ua->request($request);
                   12444:     $$rtncode = $response->code;
1.482     albertel 12445:     if (! $response->is_success()) {
                   12446: 	return 'failed';
                   12447:     }      
                   12448:     if ($reqtype eq 'HEAD') {
1.486     www      12449: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12450:     } elsif ($reqtype eq 'GET') {
                   12451: 	$$info = $response->content;
1.472     albertel 12452:     }
1.482     albertel 12453:     return 'ok';
1.36      albertel 12454: }
                   12455: 
1.481     raeburn  12456: sub readfile {
                   12457:     my $file = shift;
                   12458:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12459:     my $fh;
                   12460:     open($fh,"<$file");
                   12461:     my $a='';
1.800     albertel 12462:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12463:     return $a;
                   12464: }
                   12465: 
1.36      albertel 12466: sub filelocation {
1.590     banghart 12467:     my ($dir,$file) = @_;
                   12468:     my $location;
                   12469:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12470: 
                   12471:     if ($file =~ m-^/adm/-) {
                   12472: 	$file=~s-^/adm/wrapper/-/-;
                   12473: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12474:     }
1.882     albertel 12475: 
1.1139    www      12476:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12477:         $location = $file;
1.609     banghart 12478:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12479:         my ($udom,$uname,$filename)=
1.811     albertel 12480:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12481:         my $home=&homeserver($uname,$udom);
                   12482:         my $is_me=0;
                   12483:         my @ids=&current_machine_ids();
                   12484:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12485:         if ($is_me) {
1.1117    foxr     12486:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12487:         } else {
                   12488:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12489:   	      $udom.'/'.$uname.'/'.$filename;
                   12490:         }
1.882     albertel 12491:     } elsif ($file =~ m-^/adm/-) {
                   12492: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12493:     } else {
                   12494:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12495:         $file=~s:^/(res|priv)/:/:;
                   12496:         my $space=$1;
1.590     banghart 12497:         if ( !( $file =~ m:^/:) ) {
                   12498:             $location = $dir. '/'.$file;
                   12499:         } else {
1.1142    raeburn  12500:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12501:         }
1.59      albertel 12502:     }
1.590     banghart 12503:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12504:     while ($location=~m{/\.\./}) {
                   12505: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12506: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   12507: 	} else {
                   12508: 	    $location=~ s{/\.\./}{/}g;
                   12509: 	}
                   12510:     } #remove dir/..
1.590     banghart 12511:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   12512:     return $location;
1.46      www      12513: }
1.36      albertel 12514: 
1.46      www      12515: sub hreflocation {
                   12516:     my ($dir,$file)=@_;
1.980     raeburn  12517:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 12518: 	$file=filelocation($dir,$file);
1.700     albertel 12519:     } elsif ($file=~m-^/adm/-) {
                   12520: 	$file=~s-^/adm/wrapper/-/-;
                   12521: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 12522:     }
                   12523:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   12524: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   12525:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  12526: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   12527: 	        {/uploaded/$1/$2/}x;
1.46      www      12528:     }
1.913     albertel 12529:     if ($file=~ m{^/userfiles/}) {
                   12530: 	$file =~ s{^/userfiles/}{/uploaded/};
                   12531:     }
1.462     albertel 12532:     return $file;
1.465     albertel 12533: }
                   12534: 
1.1139    www      12535: 
                   12536: 
                   12537: 
                   12538: 
1.465     albertel 12539: sub current_machine_domains {
1.853     albertel 12540:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   12541: }
                   12542: 
                   12543: sub machine_domains {
                   12544:     my ($hostname) = @_;
1.465     albertel 12545:     my @domains;
1.838     albertel 12546:     my %hostname = &all_hostnames();
1.465     albertel 12547:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  12548: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 12549: 	if ($hostname eq $name) {
1.844     albertel 12550: 	    push(@domains,&host_domain($id));
1.465     albertel 12551: 	}
                   12552:     }
                   12553:     return @domains;
                   12554: }
                   12555: 
                   12556: sub current_machine_ids {
1.853     albertel 12557:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   12558: }
                   12559: 
                   12560: sub machine_ids {
                   12561:     my ($hostname) = @_;
                   12562:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 12563:     my @ids;
1.888     albertel 12564:     my %name_to_host = &all_names();
1.889     albertel 12565:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   12566: 	return @{ $name_to_host{$hostname} };
                   12567:     }
                   12568:     return;
1.31      www      12569: }
                   12570: 
1.824     raeburn  12571: sub additional_machine_domains {
                   12572:     my @domains;
                   12573:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   12574:     while( my $line = <$fh>) {
                   12575:         $line =~ s/\s//g;
                   12576:         push(@domains,$line);
                   12577:     }
                   12578:     return @domains;
                   12579: }
                   12580: 
                   12581: sub default_login_domain {
                   12582:     my $domain = $perlvar{'lonDefDomain'};
                   12583:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   12584:     foreach my $posdom (&current_machine_domains(),
                   12585:                         &additional_machine_domains()) {
                   12586:         if (lc($posdom) eq lc($testdomain)) {
                   12587:             $domain=$posdom;
                   12588:             last;
                   12589:         }
                   12590:     }
                   12591:     return $domain;
                   12592: }
                   12593: 
1.31      www      12594: # ------------------------------------------------------------- Declutters URLs
                   12595: 
                   12596: sub declutter {
                   12597:     my $thisfn=shift;
1.569     albertel 12598:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  12599:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   12600:         $thisfn=~s{^/home/httpd/html}{};
                   12601:     }
1.31      www      12602:     $thisfn=~s/^\///;
1.697     albertel 12603:     $thisfn=~s|^adm/wrapper/||;
                   12604:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12605:     $thisfn=~s/^res\///;
1.1172    bisitz   12606:     $thisfn=~s/^priv\///;
1.1032    raeburn  12607:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12608:         $thisfn=~s/\?.+$//;
                   12609:     }
1.268     www      12610:     return $thisfn;
                   12611: }
                   12612: 
                   12613: # ------------------------------------------------------------- Clutter up URLs
                   12614: 
                   12615: sub clutter {
                   12616:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12617:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 12618: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      12619:        $thisfn='/res'.$thisfn; 
                   12620:     }
1.1031    raeburn  12621:     if ($thisfn !~m|^/adm|) {
                   12622: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 12623: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 12624: 	} else {
                   12625: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   12626: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 12627: 	    if ($embstyle eq 'ssi'
                   12628: 		|| ($embstyle eq 'hdn')
                   12629: 		|| ($embstyle eq 'rat')
                   12630: 		|| ($embstyle eq 'prv')
                   12631: 		|| ($embstyle eq 'ign')) {
                   12632: 		#do nothing with these
                   12633: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 12634: 		|| ($embstyle eq 'emb')
                   12635: 		|| ($embstyle eq 'wrp')) {
                   12636: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 12637: 	    } elsif ($embstyle eq 'unk'
                   12638: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 12639: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 12640: 	    } else {
1.718     www      12641: #		&logthis("Got a blank emb style");
1.695     albertel 12642: 	    }
1.694     albertel 12643: 	}
1.1298    raeburn  12644:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/exttools?$}) {
                   12645:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 12646:     }
1.31      www      12647:     return $thisfn;
1.12      www      12648: }
                   12649: 
1.787     albertel 12650: sub clutter_with_no_wrapper {
                   12651:     my $uri = &clutter(shift);
                   12652:     if ($uri =~ m-^/adm/-) {
                   12653: 	$uri =~ s-^/adm/wrapper/-/-;
                   12654: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   12655:     }
                   12656:     return $uri;
                   12657: }
                   12658: 
1.557     albertel 12659: sub freeze_escape {
                   12660:     my ($value)=@_;
                   12661:     if (ref($value)) {
                   12662: 	$value=&nfreeze($value);
                   12663: 	return '__FROZEN__'.&escape($value);
                   12664:     }
                   12665:     return &escape($value);
                   12666: }
                   12667: 
1.11      www      12668: 
1.557     albertel 12669: sub thaw_unescape {
                   12670:     my ($value)=@_;
                   12671:     if ($value =~ /^__FROZEN__/) {
                   12672: 	substr($value,0,10,undef);
                   12673: 	$value=&unescape($value);
                   12674: 	return &thaw($value);
                   12675:     }
                   12676:     return &unescape($value);
                   12677: }
                   12678: 
1.436     albertel 12679: sub correct_line_ends {
                   12680:     my ($result)=@_;
                   12681:     $$result =~s/\r\n/\n/mg;
                   12682:     $$result =~s/\r/\n/mg;
1.415     albertel 12683: }
1.1       albertel 12684: # ================================================================ Main Program
                   12685: 
1.184     www      12686: sub goodbye {
1.204     albertel 12687:    &logthis("Starting Shut down");
1.443     albertel 12688: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 12689:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 12690: #converted
1.599     albertel 12691: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 12692:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   12693: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   12694: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 12695: #1.1 only
1.870     albertel 12696: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   12697: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   12698: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   12699: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   12700:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 12701:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   12702:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      12703:    &flushcourselogs();
                   12704:    &logthis("Shutting down");
                   12705: }
                   12706: 
1.852     albertel 12707: sub get_dns {
1.1210    raeburn  12708:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 12709:     if (!$ignore_cache) {
                   12710: 	my ($content,$cached)=
                   12711: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   12712: 	if ($cached) {
1.1210    raeburn  12713: 	    &$func($content,$hashref);
1.869     albertel 12714: 	    return;
                   12715: 	}
                   12716:     }
                   12717: 
                   12718:     my %alldns;
1.852     albertel 12719:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12720:     foreach my $dns (<$config>) {
                   12721: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  12722:         my $line = $1;
                   12723:         my ($host,$protocol) = split(/:/,$line);
                   12724:         if ($protocol ne 'https') {
                   12725:             $protocol = 'http';
                   12726:         }
                   12727: 	$alldns{$host} = $protocol;
1.869     albertel 12728:     }
                   12729:     while (%alldns) {
1.1263    raeburn  12730: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 12731: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  12732:         $ua->timeout(30);
1.979     raeburn  12733: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 12734: 	my $response=$ua->request($request);
1.979     raeburn  12735:         delete($alldns{$dns});
1.852     albertel 12736: 	next if ($response->is_error());
                   12737: 	my @content = split("\n",$response->content);
1.1210    raeburn  12738: 	unless ($nocache) {
1.1219    raeburn  12739: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210    raeburn  12740: 	}
                   12741: 	&$func(\@content,$hashref);
1.869     albertel 12742: 	return;
1.852     albertel 12743:     }
                   12744:     close($config);
1.871     albertel 12745:     my $which = (split('/',$url))[3];
                   12746:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   12747:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 12748:     my @content = <$config>;
1.1210    raeburn  12749:     &$func(\@content,$hashref);
                   12750:     return;
                   12751: }
                   12752: 
                   12753: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  12754: sub parse_dns_checksums_tab {
1.1210    raeburn  12755:     my ($lines,$hashref) = @_;
1.1264    raeburn  12756:     my $lonhost = $perlvar{'lonHostID'};
                   12757:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  12758:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  12759:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   12760:     my $webconfdir = '/etc/httpd/conf';
                   12761:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   12762:         $webconfdir = '/etc/apache2';
                   12763:     } elsif ($distro =~ /^sles(\d+)$/) {
                   12764:         if ($1 >= 10) {
                   12765:             $webconfdir = '/etc/apache2';
                   12766:         }
                   12767:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   12768:         if ($1 >= 10.0) {
                   12769:             $webconfdir = '/etc/apache2';
                   12770:         }
                   12771:     }
1.1210    raeburn  12772:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12773:     my (%chksum,%revnum);
                   12774:     if (ref($lines) eq 'ARRAY') {
                   12775:         chomp(@{$lines});
1.1238    raeburn  12776:         my $version = shift(@{$lines});
                   12777:         if ($version eq $release) {  
1.1210    raeburn  12778:             foreach my $line (@{$lines}) {
1.1238    raeburn  12779:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  12780:                 if ($file =~ m{^/etc/httpd/conf}) {
                   12781:                     if ($webconfdir eq '/etc/apache2') {
                   12782:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   12783:                     }
                   12784:                 }
1.1238    raeburn  12785:                 $chksum{$file} = $shasum;
                   12786:                 $revnum{$file} = $version;
1.1210    raeburn  12787:             }
                   12788:             if (ref($hashref) eq 'HASH') {
                   12789:                 %{$hashref} = (
                   12790:                                 sums     => \%chksum,
                   12791:                                 versions => \%revnum,
                   12792:                               );
                   12793:             }
                   12794:         }
                   12795:     }
1.869     albertel 12796:     return;
1.852     albertel 12797: }
1.1210    raeburn  12798: 
                   12799: sub fetch_dns_checksums {
1.1238    raeburn  12800:     my %checksums;
                   12801:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  12802:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  12803:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12804:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  12805:              \%checksums);
1.1210    raeburn  12806:     return \%checksums;
                   12807: }
                   12808: 
1.327     albertel 12809: # ------------------------------------------------------------ Read domain file
                   12810: {
1.852     albertel 12811:     my $loaded;
1.846     albertel 12812:     my %domain;
                   12813: 
1.852     albertel 12814:     sub parse_domain_tab {
                   12815: 	my ($lines) = @_;
                   12816: 	foreach my $line (@$lines) {
                   12817: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      12818: 
1.846     albertel 12819: 	    chomp($line);
1.852     albertel 12820: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 12821: 	    my %this_domain;
                   12822: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   12823: 			       'lang_def', 'city', 'longi', 'lati',
                   12824: 			       'primary') {
                   12825: 		$this_domain{$field} = shift(@elements);
                   12826: 	    }
                   12827: 	    $domain{$name} = \%this_domain;
1.852     albertel 12828: 	}
                   12829:     }
1.864     albertel 12830: 
                   12831:     sub reset_domain_info {
                   12832: 	undef($loaded);
                   12833: 	undef(%domain);
                   12834:     }
                   12835: 
1.852     albertel 12836:     sub load_domain_tab {
1.1293    raeburn  12837: 	my ($ignore_cache,$nocache) = @_;
                   12838: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 12839: 	my $fh;
                   12840: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   12841: 	    my @lines = <$fh>;
                   12842: 	    &parse_domain_tab(\@lines);
1.448     albertel 12843: 	}
1.852     albertel 12844: 	close($fh);
                   12845: 	$loaded = 1;
1.327     albertel 12846:     }
1.846     albertel 12847: 
                   12848:     sub domain {
1.852     albertel 12849: 	&load_domain_tab() if (!$loaded);
                   12850: 
1.846     albertel 12851: 	my ($name,$what) = @_;
                   12852: 	return if ( !exists($domain{$name}) );
                   12853: 
                   12854: 	if (!$what) {
                   12855: 	    return $domain{$name}{'description'};
                   12856: 	}
                   12857: 	return $domain{$name}{$what};
                   12858:     }
1.974     raeburn  12859: 
                   12860:     sub domain_info {
                   12861:         &load_domain_tab() if (!$loaded);
                   12862:         return %domain;
                   12863:     }
                   12864: 
1.327     albertel 12865: }
                   12866: 
                   12867: 
1.1       albertel 12868: # ------------------------------------------------------------- Read hosts file
                   12869: {
1.838     albertel 12870:     my %hostname;
1.844     albertel 12871:     my %hostdom;
1.845     albertel 12872:     my %libserv;
1.852     albertel 12873:     my $loaded;
1.888     albertel 12874:     my %name_to_host;
1.1074    raeburn  12875:     my %internetdom;
1.1107    raeburn  12876:     my %LC_dns_serv;
1.852     albertel 12877: 
                   12878:     sub parse_hosts_tab {
                   12879: 	my ($file) = @_;
                   12880: 	foreach my $configline (@$file) {
                   12881: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  12882:             chomp($configline);
                   12883: 	    if ($configline =~ /^\^/) {
                   12884:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   12885:                     $LC_dns_serv{$1} = 1;
                   12886:                 }
                   12887:                 next;
                   12888:             }
1.1074    raeburn  12889: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 12890: 	    $name=~s/\s//g;
                   12891: 	    if ($id && $domain && $role && $name) {
                   12892: 		$hostname{$id}=$name;
1.888     albertel 12893: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 12894: 		$hostdom{$id}=$domain;
                   12895: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  12896:                 if (defined($protocol)) {
                   12897:                     if ($protocol eq 'https') {
                   12898:                         $protocol{$id} = $protocol;
                   12899:                     } else {
                   12900:                         $protocol{$id} = 'http'; 
                   12901:                     }
1.968     raeburn  12902:                 } else {
1.969     raeburn  12903:                     $protocol{$id} = 'http';
1.968     raeburn  12904:                 }
1.1074    raeburn  12905:                 if (defined($intdom)) {
                   12906:                     $internetdom{$id} = $intdom;
                   12907:                 }
1.852     albertel 12908: 	    }
                   12909: 	}
                   12910:     }
1.864     albertel 12911:     
                   12912:     sub reset_hosts_info {
1.897     albertel 12913: 	&purge_remembered();
1.864     albertel 12914: 	&reset_domain_info();
                   12915: 	&reset_hosts_ip_info();
1.892     albertel 12916: 	undef(%name_to_host);
1.864     albertel 12917: 	undef(%hostname);
                   12918: 	undef(%hostdom);
                   12919: 	undef(%libserv);
                   12920: 	undef($loaded);
                   12921:     }
1.1       albertel 12922: 
1.852     albertel 12923:     sub load_hosts_tab {
1.1293    raeburn  12924: 	my ($ignore_cache,$nocache) = @_;
                   12925: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852     albertel 12926: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12927: 	my @config = <$config>;
                   12928: 	&parse_hosts_tab(\@config);
                   12929: 	close($config);
                   12930: 	$loaded=1;
1.1       albertel 12931:     }
1.852     albertel 12932: 
1.838     albertel 12933:     sub hostname {
1.852     albertel 12934: 	&load_hosts_tab() if (!$loaded);
                   12935: 
1.838     albertel 12936: 	my ($lonid) = @_;
                   12937: 	return $hostname{$lonid};
                   12938:     }
1.845     albertel 12939: 
1.838     albertel 12940:     sub all_hostnames {
1.852     albertel 12941: 	&load_hosts_tab() if (!$loaded);
                   12942: 
1.838     albertel 12943: 	return %hostname;
                   12944:     }
1.845     albertel 12945: 
1.888     albertel 12946:     sub all_names {
1.1293    raeburn  12947:         my ($ignore_cache,$nocache) = @_;
                   12948: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 12949: 
                   12950: 	return %name_to_host;
                   12951:     }
                   12952: 
1.974     raeburn  12953:     sub all_host_domain {
                   12954:         &load_hosts_tab() if (!$loaded);
                   12955:         return %hostdom;
                   12956:     }
                   12957: 
1.845     albertel 12958:     sub is_library {
1.852     albertel 12959: 	&load_hosts_tab() if (!$loaded);
                   12960: 
1.845     albertel 12961: 	return exists($libserv{$_[0]});
                   12962:     }
                   12963: 
                   12964:     sub all_library {
1.852     albertel 12965: 	&load_hosts_tab() if (!$loaded);
                   12966: 
1.845     albertel 12967: 	return %libserv;
                   12968:     }
                   12969: 
1.1062    droeschl 12970:     sub unique_library {
                   12971: 	#2x reverse removes all hostnames that appear more than once
                   12972:         my %unique = reverse &all_library();
                   12973:         return reverse %unique;
                   12974:     }
                   12975: 
1.841     albertel 12976:     sub get_servers {
1.852     albertel 12977: 	&load_hosts_tab() if (!$loaded);
                   12978: 
1.841     albertel 12979: 	my ($domain,$type) = @_;
                   12980: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   12981: 	                                          : %hostname;
                   12982: 	my %result;
1.842     albertel 12983: 	if (ref($domain) eq 'ARRAY') {
                   12984: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 12985: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 12986: 		    $result{$host} = $hostname;
                   12987: 		}
                   12988: 	    }
                   12989: 	} else {
                   12990: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   12991: 		if ($hostdom{$host} eq $domain) {
                   12992: 		    $result{$host} = $hostname;
                   12993: 		}
1.841     albertel 12994: 	    }
                   12995: 	}
                   12996: 	return %result;
                   12997:     }
1.845     albertel 12998: 
1.1062    droeschl 12999:     sub get_unique_servers {
                   13000:         my %unique = reverse &get_servers(@_);
                   13001: 	return reverse %unique;
                   13002:     }
                   13003: 
1.844     albertel 13004:     sub host_domain {
1.852     albertel 13005: 	&load_hosts_tab() if (!$loaded);
                   13006: 
1.844     albertel 13007: 	my ($lonid) = @_;
                   13008: 	return $hostdom{$lonid};
                   13009:     }
                   13010: 
1.841     albertel 13011:     sub all_domains {
1.852     albertel 13012: 	&load_hosts_tab() if (!$loaded);
                   13013: 
1.841     albertel 13014: 	my %seen;
                   13015: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13016: 	return @uniq;
                   13017:     }
1.1074    raeburn  13018: 
                   13019:     sub internet_dom {
                   13020:         &load_hosts_tab() if (!$loaded);
                   13021: 
                   13022:         my ($lonid) = @_;
                   13023:         return $internetdom{$lonid};
                   13024:     }
1.1107    raeburn  13025: 
                   13026:     sub is_LC_dns {
                   13027:         &load_hosts_tab() if (!$loaded);
                   13028: 
                   13029:         my ($hostname) = @_;
                   13030:         return exists($LC_dns_serv{$hostname});
                   13031:     }
                   13032: 
1.1       albertel 13033: }
                   13034: 
1.847     albertel 13035: { 
                   13036:     my %iphost;
1.856     albertel 13037:     my %name_to_ip;
                   13038:     my %lonid_to_ip;
1.869     albertel 13039: 
1.847     albertel 13040:     sub get_hosts_from_ip {
                   13041: 	my ($ip) = @_;
                   13042: 	my %iphosts = &get_iphost();
                   13043: 	if (ref($iphosts{$ip})) {
                   13044: 	    return @{$iphosts{$ip}};
                   13045: 	}
                   13046: 	return;
1.839     albertel 13047:     }
1.864     albertel 13048:     
                   13049:     sub reset_hosts_ip_info {
                   13050: 	undef(%iphost);
                   13051: 	undef(%name_to_ip);
                   13052: 	undef(%lonid_to_ip);
                   13053:     }
1.856     albertel 13054: 
                   13055:     sub get_host_ip {
                   13056: 	my ($lonid) = @_;
                   13057: 	if (exists($lonid_to_ip{$lonid})) {
                   13058: 	    return $lonid_to_ip{$lonid};
                   13059: 	}
                   13060: 	my $name=&hostname($lonid);
                   13061:    	my $ip = gethostbyname($name);
                   13062: 	return if (!$ip || length($ip) ne 4);
                   13063: 	$ip=inet_ntoa($ip);
                   13064: 	$name_to_ip{$name}   = $ip;
                   13065: 	$lonid_to_ip{$lonid} = $ip;
                   13066: 	return $ip;
                   13067:     }
1.847     albertel 13068:     
                   13069:     sub get_iphost {
1.1293    raeburn  13070: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13071: 
1.869     albertel 13072: 	if (!$ignore_cache) {
                   13073: 	    if (%iphost) {
                   13074: 		return %iphost;
                   13075: 	    }
                   13076: 	    my ($ip_info,$cached)=
                   13077: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13078: 	    if ($cached) {
                   13079: 		%iphost      = %{$ip_info->[0]};
                   13080: 		%name_to_ip  = %{$ip_info->[1]};
                   13081: 		%lonid_to_ip = %{$ip_info->[2]};
                   13082: 		return %iphost;
                   13083: 	    }
                   13084: 	}
1.894     albertel 13085: 
                   13086: 	# get yesterday's info for fallback
                   13087: 	my %old_name_to_ip;
                   13088: 	my ($ip_info,$cached)=
                   13089: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13090: 	if ($cached) {
                   13091: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13092: 	}
                   13093: 
1.1293    raeburn  13094: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13095: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13096: 	    my $ip;
                   13097: 	    if (!exists($name_to_ip{$name})) {
                   13098: 		$ip = gethostbyname($name);
                   13099: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13100: 		    if (defined($old_name_to_ip{$name})) {
                   13101: 			$ip = $old_name_to_ip{$name};
                   13102: 			&logthis("Can't find $name defaulting to old $ip");
                   13103: 		    } else {
                   13104: 			&logthis("Name $name no IP found");
                   13105: 			next;
                   13106: 		    }
                   13107: 		} else {
                   13108: 		    $ip=inet_ntoa($ip);
1.847     albertel 13109: 		}
                   13110: 		$name_to_ip{$name} = $ip;
                   13111: 	    } else {
                   13112: 		$ip = $name_to_ip{$name};
1.653     albertel 13113: 	    }
1.888     albertel 13114: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13115: 		$lonid_to_ip{$id} = $ip;
                   13116: 	    }
                   13117: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13118: 	}
1.1293    raeburn  13119:         unless ($nocache) {
                   13120: 	    &do_cache_new('iphost','iphost',
                   13121: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13122: 		          48*60*60);
                   13123:         }
1.869     albertel 13124: 
1.847     albertel 13125: 	return %iphost;
1.598     albertel 13126:     }
                   13127: 
1.992     raeburn  13128:     #
                   13129:     #  Given a DNS returns the loncapa host name for that DNS 
                   13130:     # 
                   13131:     sub host_from_dns {
                   13132:         my ($dns) = @_;
                   13133:         my @hosts;
                   13134:         my $ip;
                   13135: 
1.993     raeburn  13136:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13137:             $ip = $name_to_ip{$dns};
                   13138:         }
                   13139:         if (!$ip) {
                   13140:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13141:             if (length($ip) == 4) { 
                   13142: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13143:             }
                   13144:         }
                   13145:         if ($ip) {
                   13146: 	    @hosts = get_hosts_from_ip($ip);
                   13147: 	    return $hosts[0];
                   13148:         }
                   13149:         return undef;
1.986     foxr     13150:     }
1.992     raeburn  13151: 
1.1074    raeburn  13152:     sub get_internet_names {
                   13153:         my ($lonid) = @_;
                   13154:         return if ($lonid eq '');
                   13155:         my ($idnref,$cached)=
                   13156:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13157:         if ($cached) {
                   13158:             return $idnref;
                   13159:         }
                   13160:         my $ip = &get_host_ip($lonid);
                   13161:         my @hosts = &get_hosts_from_ip($ip);
                   13162:         my %iphost = &get_iphost();
                   13163:         my (@idns,%seen);
                   13164:         foreach my $id (@hosts) {
                   13165:             my $dom = &host_domain($id);
                   13166:             my $prim_id = &domain($dom,'primary');
                   13167:             my $prim_ip = &get_host_ip($prim_id);
                   13168:             next if ($seen{$prim_ip});
                   13169:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13170:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13171:                     my $intdom = &internet_dom($id);
                   13172:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13173:                         push(@idns,$intdom);
                   13174:                     }
                   13175:                 }
                   13176:             }
                   13177:             $seen{$prim_ip} = 1;
                   13178:         }
1.1219    raeburn  13179:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13180:     }
                   13181: 
1.986     foxr     13182: }
                   13183: 
1.1079    raeburn  13184: sub all_loncaparevs {
1.1249    raeburn  13185:     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  13186: }
                   13187: 
1.1227    raeburn  13188: # ---------------------------------------------------------- Read loncaparev table
                   13189: {
                   13190:     sub load_loncaparevs { 
                   13191:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   13192:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   13193:                 while (my $configline=<$config>) {
                   13194:                     chomp($configline);
                   13195:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13196:                     $loncaparevs{$hostid}=$loncaparev;
                   13197:                 }
                   13198:                 close($config);
                   13199:             }
                   13200:         }
                   13201:     }
                   13202: }
                   13203: 
                   13204: # ---------------------------------------------------------- Read serverhostID table
                   13205: {
                   13206:     sub load_serverhomeIDs {
                   13207:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   13208:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   13209:                 while (my $configline=<$config>) {
                   13210:                     chomp($configline);
                   13211:                     my ($name,$id)=split(/:/,$configline);
                   13212:                     $serverhomeIDs{$name}=$id;
                   13213:                 }
                   13214:                 close($config);
                   13215:             }
                   13216:         }
                   13217:     }
                   13218: }
                   13219: 
                   13220: 
1.862     albertel 13221: BEGIN {
                   13222: 
                   13223: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13224:     unless ($readit) {
                   13225: {
                   13226:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13227:     %perlvar = (%perlvar,%{$configvars});
                   13228: }
                   13229: 
                   13230: 
1.1       albertel 13231: # ------------------------------------------------------ Read spare server file
                   13232: {
1.448     albertel 13233:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13234: 
                   13235:     while (my $configline=<$config>) {
                   13236:        chomp($configline);
1.284     matthew  13237:        if ($configline) {
1.784     albertel 13238: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13239: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13240: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13241:        }
                   13242:     }
1.448     albertel 13243:     close($config);
1.1       albertel 13244: }
1.11      www      13245: # ------------------------------------------------------------ Read permissions
                   13246: {
1.448     albertel 13247:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13248: 
                   13249:     while (my $configline=<$config>) {
1.448     albertel 13250: 	chomp($configline);
                   13251: 	if ($configline) {
                   13252: 	    my ($role,$perm)=split(/ /,$configline);
                   13253: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13254: 	}
1.11      www      13255:     }
1.448     albertel 13256:     close($config);
1.11      www      13257: }
                   13258: 
                   13259: # -------------------------------------------- Read plain texts for permissions
                   13260: {
1.448     albertel 13261:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13262: 
                   13263:     while (my $configline=<$config>) {
1.448     albertel 13264: 	chomp($configline);
                   13265: 	if ($configline) {
1.742     raeburn  13266: 	    my ($short,@plain)=split(/:/,$configline);
                   13267:             %{$prp{$short}} = ();
                   13268: 	    if (@plain > 0) {
                   13269:                 $prp{$short}{'std'} = $plain[0];
                   13270:                 for (my $i=1; $i<@plain; $i++) {
                   13271:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13272:                 }
                   13273:             }
1.448     albertel 13274: 	}
1.135     www      13275:     }
1.448     albertel 13276:     close($config);
1.135     www      13277: }
                   13278: 
                   13279: # ---------------------------------------------------------- Read package table
                   13280: {
1.448     albertel 13281:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13282: 
                   13283:     while (my $configline=<$config>) {
1.483     albertel 13284: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13285: 	chomp($configline);
                   13286: 	my ($short,$plain)=split(/:/,$configline);
                   13287: 	my ($pack,$name)=split(/\&/,$short);
                   13288: 	if ($plain ne '') {
                   13289: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13290: 	    $packagetab{$short}=$plain; 
                   13291: 	}
1.11      www      13292:     }
1.448     albertel 13293:     close($config);
1.329     matthew  13294: }
                   13295: 
1.1073    raeburn  13296: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  13297: 
                   13298: &load_loncaparevs();
1.1073    raeburn  13299: 
1.1074    raeburn  13300: # ---------------------------------------------------------- Read serverhostID table
                   13301: 
1.1227    raeburn  13302: &load_serverhomeIDs();
                   13303: 
                   13304: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13305: {
                   13306:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13307:     if (-e $file) {
                   13308:         my $parser = HTML::LCParser->new($file);
                   13309:         while (my $token = $parser->get_token()) {
                   13310:             if ($token->[0] eq 'S') {
                   13311:                 my $item = $token->[1];
                   13312:                 my $name = $token->[2]{'name'};
                   13313:                 my $value = $token->[2]{'value'};
1.1285    raeburn  13314:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  13315:                 my $namematch = $token->[2]{'namematch'};
                   13316:                 if ($item eq 'parameter') {
                   13317:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   13318:                         my $release = $parser->get_text();
                   13319:                         $release =~ s/(^\s*|\s*$ )//gx;
                   13320:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   13321:                     }
                   13322:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  13323:                     my $release = $parser->get_text();
                   13324:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  13325:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  13326:                 }
                   13327:             }
                   13328:         }
                   13329:     }
1.1073    raeburn  13330: }
                   13331: 
1.1138    raeburn  13332: # ---------------------------------------------------------- Read managers table
                   13333: {
                   13334:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   13335:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   13336:             while (my $configline=<$config>) {
                   13337:                 chomp($configline);
                   13338:                 next if ($configline =~ /^\#/);
                   13339:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13340:                     $managerstab{$configline} = 1;
                   13341:                 }
                   13342:             }
                   13343:             close($config);
                   13344:         }
                   13345:     }
                   13346: }
                   13347: 
1.329     matthew  13348: # ------------- set up temporary directory
                   13349: {
1.1117    foxr     13350:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  13351: 
1.11      www      13352: }
                   13353: 
1.794     albertel 13354: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   13355: 				'compress_threshold'=> 20_000,
                   13356:  			        });
1.185     www      13357: 
1.281     www      13358: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      13359: $dumpcount=0;
1.958     www      13360: $locknum=0;
1.22      www      13361: 
1.163     harris41 13362: &logtouch();
1.672     albertel 13363: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      13364: $readit=1;
1.564     albertel 13365:     {
                   13366: 	use integer;
                   13367: 	my $test=(2**32)+1;
1.568     albertel 13368: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 13369: 	&logthis(" Detected 64bit platform ($_64bit)");
                   13370:     }
1.195     www      13371: }
1.1       albertel 13372: }
1.179     www      13373: 
1.1       albertel 13374: 1;
1.191     harris41 13375: __END__
                   13376: 
1.243     albertel 13377: =pod
                   13378: 
1.191     harris41 13379: =head1 NAME
                   13380: 
1.243     albertel 13381: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 13382: 
                   13383: =head1 SYNOPSIS
                   13384: 
1.243     albertel 13385: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 13386: 
                   13387:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   13388: 
1.243     albertel 13389: Common parameters:
                   13390: 
                   13391: =over 4
                   13392: 
                   13393: =item *
                   13394: 
                   13395: $uname : an internal username (if $cname expecting a course Id specifically)
                   13396: 
                   13397: =item *
                   13398: 
                   13399: $udom : a domain (if $cdom expecting a course's domain specifically)
                   13400: 
                   13401: =item *
                   13402: 
                   13403: $symb : a resource instance identifier
                   13404: 
                   13405: =item *
                   13406: 
                   13407: $namespace : the name of a .db file that contains the data needed or
                   13408: being set.
                   13409: 
                   13410: =back
                   13411: 
1.394     bowersj2 13412: =head1 OVERVIEW
1.191     harris41 13413: 
1.394     bowersj2 13414: lonnet provides subroutines which interact with the
                   13415: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   13416: about classes, users, and resources.
1.243     albertel 13417: 
                   13418: For many of these objects you can also use this to store data about
                   13419: them or modify them in various ways.
1.191     harris41 13420: 
1.394     bowersj2 13421: =head2 Symbs
1.191     harris41 13422: 
1.394     bowersj2 13423: To identify a specific instance of a resource, LON-CAPA uses symbols
                   13424: or "symbs"X<symb>. These identifiers are built from the URL of the
                   13425: map, the resource number of the resource in the map, and the URL of
                   13426: the resource itself. The latter is somewhat redundant, but might help
                   13427: if maps change.
                   13428: 
                   13429: An example is
                   13430: 
                   13431:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   13432: 
                   13433: The respective map entry is
                   13434: 
                   13435:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   13436:   title="Problem 2">
                   13437:  </resource>
                   13438: 
                   13439: Symbs are used by the random number generator, as well as to store and
                   13440: restore data specific to a certain instance of for example a problem.
                   13441: 
                   13442: =head2 Storing And Retrieving Data
                   13443: 
                   13444: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   13445: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   13446: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   13447: is is the non-critical message twin of cstore. These functions are for
                   13448: handlers to store a perl hash to a user's permanent data space in an
                   13449: easy manner, and to retrieve it again on another call. It is expected
                   13450: that a handler would use this once at the beginning to retrieve data,
                   13451: and then again once at the end to send only the new data back.
                   13452: 
                   13453: The data is stored in the user's data directory on the user's
                   13454: homeserver under the ID of the course.
                   13455: 
                   13456: The hash that is returned by restore will have all of the previous
                   13457: value for all of the elements of the hash.
                   13458: 
                   13459: Example:
                   13460: 
                   13461:  #creating a hash
                   13462:  my %hash;
                   13463:  $hash{'foo'}='bar';
                   13464: 
                   13465:  #storing it
                   13466:  &Apache::lonnet::cstore(\%hash);
                   13467: 
                   13468:  #changing a value
                   13469:  $hash{'foo'}='notbar';
                   13470: 
                   13471:  #adding a new value
                   13472:  $hash{'bar'}='foo';
                   13473:  &Apache::lonnet::cstore(\%hash);
                   13474: 
                   13475:  #retrieving the hash
                   13476:  my %history=&Apache::lonnet::restore();
                   13477: 
                   13478:  #print the hash
                   13479:  foreach my $key (sort(keys(%history))) {
                   13480:    print("\%history{$key} = $history{$key}");
                   13481:  }
                   13482: 
                   13483: Will print out:
1.191     harris41 13484: 
1.394     bowersj2 13485:  %history{1:foo} = bar
                   13486:  %history{1:keys} = foo:timestamp
                   13487:  %history{1:timestamp} = 990455579
                   13488:  %history{2:bar} = foo
                   13489:  %history{2:foo} = notbar
                   13490:  %history{2:keys} = foo:bar:timestamp
                   13491:  %history{2:timestamp} = 990455580
                   13492:  %history{bar} = foo
                   13493:  %history{foo} = notbar
                   13494:  %history{timestamp} = 990455580
                   13495:  %history{version} = 2
                   13496: 
                   13497: Note that the special hash entries C<keys>, C<version> and
                   13498: C<timestamp> were added to the hash. C<version> will be equal to the
                   13499: total number of versions of the data that have been stored. The
                   13500: C<timestamp> attribute will be the UNIX time the hash was
                   13501: stored. C<keys> is available in every historical section to list which
                   13502: keys were added or changed at a specific historical revision of a
                   13503: hash.
                   13504: 
                   13505: B<Warning>: do not store the hash that restore returns directly. This
                   13506: will cause a mess since it will restore the historical keys as if the
                   13507: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 13508: 
1.394     bowersj2 13509: Calling convention:
1.191     harris41 13510: 
1.1225    raeburn  13511:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  13512:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 13513: 
1.394     bowersj2 13514: For more detailed information, see lonnet specific documentation.
1.191     harris41 13515: 
1.394     bowersj2 13516: =head1 RETURN MESSAGES
1.191     harris41 13517: 
1.394     bowersj2 13518: =over 4
1.191     harris41 13519: 
1.394     bowersj2 13520: =item * B<con_lost>: unable to contact remote host
1.191     harris41 13521: 
1.394     bowersj2 13522: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   13523: when the connection is brought back up
1.191     harris41 13524: 
1.394     bowersj2 13525: =item * B<con_failed>: unable to contact remote host and unable to save message
                   13526: for later delivery
1.191     harris41 13527: 
1.967     bisitz   13528: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 13529: 
1.394     bowersj2 13530: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 13531: that was requested
1.191     harris41 13532: 
1.243     albertel 13533: =back
1.191     harris41 13534: 
1.243     albertel 13535: =head1 PUBLIC SUBROUTINES
1.191     harris41 13536: 
1.243     albertel 13537: =head2 Session Environment Functions
1.191     harris41 13538: 
1.243     albertel 13539: =over 4
1.191     harris41 13540: 
1.394     bowersj2 13541: =item * 
                   13542: X<appenv()>
1.949     raeburn  13543: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 13544: the user envirnoment file, and will be restored for each access this
1.620     albertel 13545: user makes during this session, also modifies the %env for the current
1.949     raeburn  13546: process. Optional rolesarrayref - if defined contains a reference to an array
                   13547: of roles which are exempt from the restriction on modifying user.role entries 
                   13548: in the user's environment.db and in %env.    
1.191     harris41 13549: 
                   13550: =item *
1.394     bowersj2 13551: X<delenv()>
1.987     raeburn  13552: B<delenv($delthis,$regexp)>: removes all items from the session
                   13553: environment file that begin with $delthis. If the 
                   13554: optional second arg - $regexp - is true, $delthis is treated as a 
                   13555: regular expression, otherwise \Q$delthis\E is used. 
                   13556: The values are also deleted from the current processes %env.
1.191     harris41 13557: 
1.795     albertel 13558: =item * get_env_multiple($name) 
                   13559: 
                   13560: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   13561: values may be defined and end up as an array ref.
                   13562: 
                   13563: returns an array of values
                   13564: 
1.243     albertel 13565: =back
                   13566: 
                   13567: =head2 User Information
1.191     harris41 13568: 
1.243     albertel 13569: =over 4
1.191     harris41 13570: 
                   13571: =item *
1.394     bowersj2 13572: X<queryauthenticate()>
                   13573: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 13574: authentication scheme
                   13575: 
                   13576: =item *
1.394     bowersj2 13577: X<authenticate()>
1.1073    raeburn  13578: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 13579: authenticate user from domain's lib servers (first use the current
                   13580: one). C<$upass> should be the users password.
1.1073    raeburn  13581: $checkdefauth is optional (value is 1 if a check should be made to
                   13582:    authenticate user using default authentication method, and allow
                   13583:    account creation if username does not have account in the domain).
                   13584: $clientcancheckhost is optional (value is 1 if checking whether the
                   13585:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 13586: 
                   13587: =item *
1.394     bowersj2 13588: X<homeserver()>
                   13589: B<homeserver($uname,$udom)>: find the server which has
                   13590: the user's directory and files (there must be only one), this caches
                   13591: the answer, and also caches if there is a borken connection.
1.191     harris41 13592: 
                   13593: =item *
1.394     bowersj2 13594: X<idget()>
1.1300    raeburn  13595: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   13596: a list of student/employee IDs or clicker IDs
                   13597: (student/employee IDs are a unique resource in a domain, there must be 
                   13598: only 1 ID per username, and only 1 username per ID in a specific domain).
                   13599: clickerIDs are not necessarily unique, as students might share clickers.
                   13600: (returns hash: id=>name,id=>name)
1.191     harris41 13601: 
                   13602: =item *
1.394     bowersj2 13603: X<idrget()>
                   13604: B<idrget($udom,@unames)>: find the IDs behind a list of
                   13605: usernames (returns hash: name=>id,name=>id)
1.191     harris41 13606: 
                   13607: =item *
1.394     bowersj2 13608: X<idput()>
1.1300    raeburn  13609: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   13610: names and associated student/employee IDs or clicker IDs.
                   13611: 
                   13612: =item *
                   13613: X<iddel()>
                   13614: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   13615: student/employee ID or clicker ID username look-ups from domain.
                   13616: The homeserver ($uhome) and namespace ($namespace) are optional.
                   13617: If no $uhome is provided, it will be determined usig &homeserver()
                   13618: for each user.  If no $namespace is provided, the default is ids.
                   13619: 
                   13620: =item *
                   13621: X<updateclickers()>
                   13622: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   13623: clicker ID-to-username look-ups in clickers.db on library server.
                   13624: Permitted actions are add or del (i.e., add or delete). The 
                   13625: clickers.db contains clickerID as keys (escaped), and each corresponding
                   13626: value is an escaped comma-separated list of usernames (for whom the
                   13627: library server is the homeserver), who registered that particular ID.
                   13628: If $critical is true, the update will be sent via &critical, otherwise
                   13629: &reply() will be used.
1.191     harris41 13630: 
                   13631: =item *
1.394     bowersj2 13632: X<rolesinit()>
1.1169    droeschl 13633: B<rolesinit($udom,$username)>: get user privileges.
                   13634: returns user role, first access and timer interval hashes
1.243     albertel 13635: 
                   13636: =item *
1.1171    droeschl 13637: X<privileged()>
                   13638: B<privileged($username,$domain)>: returns a true if user has a
                   13639: privileged and active role (i.e. su or dc), false otherwise.
                   13640: 
                   13641: =item *
1.551     albertel 13642: X<getsection()>
                   13643: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 13644: course $cname, return section name/number or '' for "not in course"
                   13645: and '-1' for "no section"
                   13646: 
                   13647: =item *
1.394     bowersj2 13648: X<userenvironment()>
                   13649: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 13650: passed in @what from the requested user's environment, returns a hash
                   13651: 
1.858     raeburn  13652: =item * 
                   13653: X<userlog_query()>
1.859     albertel 13654: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   13655: activity.log file. %filters defines filters applied when parsing the
                   13656: log file. These can be start or end timestamps, or the type of action
                   13657: - log to look for Login or Logout events, check for Checkin or
                   13658: Checkout, role for role selection. The response is in the form
                   13659: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   13660: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  13661: 
1.243     albertel 13662: =back
                   13663: 
                   13664: =head2 User Roles
                   13665: 
                   13666: =over 4
                   13667: 
                   13668: =item *
                   13669: 
1.1284    raeburn  13670: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   13671: returns codes for allowed actions.
                   13672: 
                   13673: The first argument is required, all others are optional.
                   13674: 
                   13675: $priv is the privilege being checked.
                   13676: $uri contains additional information about what is being checked for access (e.g.,
                   13677: URL, course ID etc.). 
                   13678: $symb is the unique resource instance identifier in a course; if needed,
                   13679: but not provided, it will be retrieved via a call to &symbread(). 
                   13680: $role is the role for which a priv is being checked (only used if priv is evb). 
                   13681: $clientip is the user's IP address (only used when checking for access to portfolio 
                   13682: files).
                   13683: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   13684: prevents recursive calls to &allowed.
                   13685: 
1.243     albertel 13686:  F: full access
                   13687:  U,I,K: authentication modes (cxx only)
                   13688:  '': forbidden
                   13689:  1: user needs to choose course
                   13690:  2: browse allowed
1.766     albertel 13691:  A: passphrase authentication needed
1.1284    raeburn  13692:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 13693: 
                   13694: =item *
                   13695: 
1.1192    raeburn  13696: constructaccess($url,$setpriv) : check for access to construction space URL
                   13697: 
                   13698: See if the owner domain and name in the URL match those in the
                   13699: expected environment.  If so, return three element list
                   13700: ($ownername,$ownerdomain,$ownerhome).
                   13701: 
                   13702: Otherwise return the null string.
                   13703: 
                   13704: If second argument 'setpriv' is true, it assigns the privileges,
                   13705: and returns the same three element list, unless the owner has
                   13706: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   13707: in which case the null string is returned.
                   13708: 
                   13709: =item *
                   13710: 
1.243     albertel 13711: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   13712: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   13713: and course level
                   13714: 
                   13715: =item *
                   13716: 
1.988     raeburn  13717: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   13718: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  13719: $type is Course (default) or Community.
1.988     raeburn  13720: If $forcedefault evaluates to true, text returned will be default 
                   13721: text for $type. Otherwise, if this is a course, the text returned 
                   13722: will be a custom name for the role (if defined in the course's 
                   13723: environment).  If no custom name is defined the default is returned.
                   13724:    
1.832     raeburn  13725: =item *
                   13726: 
1.1219    raeburn  13727: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  13728: All arguments are optional. Returns a hash of a roles, either for
                   13729: co-author/assistant author roles for a user's Construction Space
1.906     albertel 13730: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  13731: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   13732: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   13733: For each key, value is set to colon-separated start and end times for
                   13734: the role.  If no username and domain are specified, will default to
1.934     raeburn  13735: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  13736: of role statuses (active, future or previous), roles 
                   13737: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   13738: to restrict the list of roles reported. If no array ref is 
                   13739: provided for types, will default to return only active roles.
1.834     albertel 13740: 
1.1195    raeburn  13741: =item *
                   13742: 
                   13743: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  13744: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   13745: 
                   13746: Additional optional arguments are: $type (if role checking is to be restricted 
                   13747: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  13748: available roles) or future (roles available in the future), and
                   13749: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  13750: have active Domain Coordinator role in course's domain or in additional
                   13751: domains (specified in 'Domains to check for privileged users' in course
                   13752: environment -- set via:  Course Settings -> Classlists and staff listing).
                   13753: 
                   13754: =item *
                   13755: 
                   13756: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   13757: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   13758: $possdomains and $possroles are optional array refs -- to domains to check and
                   13759: roles to check.  If $possdomains is not specified, a dump will be done of the
                   13760: users' roles.db to check for a dc or su role in any domain. This can be
                   13761: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   13762: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   13763: this then allows &privileged_by_domain() to be used, which caches the identity
                   13764: of privileged users, eliminating the need for repeated calls to &dump().
                   13765: 
                   13766: =item *
                   13767: 
                   13768: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   13769: where the outer hash keys are domains specified in the $possdomains array ref,
                   13770: next inner hash keys are privileged roles specified in the $roles array ref,
                   13771: and the innermost hash contains key = value pairs for username:domain = end:start
                   13772: for active or future "privileged" users with that role in that domain. To avoid
                   13773: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   13774: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  13775: 
1.243     albertel 13776: =back
                   13777: 
                   13778: =head2 User Modification
                   13779: 
                   13780: =over 4
                   13781: 
                   13782: =item *
                   13783: 
1.957     raeburn  13784: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 13785: user for the level given by URL.  Optional start and end dates (leave empty
                   13786: string or zero for "no date")
1.191     harris41 13787: 
                   13788: =item *
                   13789: 
1.243     albertel 13790: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   13791: change a users, password, possible return values are: ok,
                   13792: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   13793: refused
1.191     harris41 13794: 
                   13795: =item *
                   13796: 
1.243     albertel 13797: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 13798: 
                   13799: =item *
                   13800: 
1.1058    raeburn  13801: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   13802:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   13803: 
                   13804: will update user information (firstname,middlename,lastname,generation,
                   13805: permanentemail), and if forceid is true, student/employee ID also.
                   13806: A user's institutional affiliation(s) can also be updated.
                   13807: User information fields will not be overwritten with empty entries 
                   13808: unless the field is included in the $candelete array reference.
                   13809: This array is included when a single user is modified via "Manage Users",
                   13810: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 13811: 
                   13812: =item *
                   13813: 
1.286     matthew  13814: modifystudent
                   13815: 
1.957     raeburn  13816: modify a student's enrollment and identification information.
1.1235    raeburn  13817: The course id is resolved based on the current user's environment.  
                   13818: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  13819: associated with a course.
                   13820: 
1.297     matthew  13821: This call is essentially a wrapper for lonnet::modifyuser and
                   13822: lonnet::modify_student_enrollment
1.286     matthew  13823: 
                   13824: Inputs: 
                   13825: 
                   13826: =over 4
                   13827: 
1.957     raeburn  13828: =item B<$udom> Student's loncapa domain
1.286     matthew  13829: 
1.957     raeburn  13830: =item B<$uname> Student's loncapa login name
1.286     matthew  13831: 
1.964     bisitz   13832: =item B<$uid> Student/Employee ID
1.286     matthew  13833: 
1.957     raeburn  13834: =item B<$umode> Student's authentication mode
1.286     matthew  13835: 
1.957     raeburn  13836: =item B<$upass> Student's password
1.286     matthew  13837: 
1.957     raeburn  13838: =item B<$first> Student's first name
1.286     matthew  13839: 
1.957     raeburn  13840: =item B<$middle> Student's middle name
1.286     matthew  13841: 
1.957     raeburn  13842: =item B<$last> Student's last name
1.286     matthew  13843: 
1.957     raeburn  13844: =item B<$gene> Student's generation
1.286     matthew  13845: 
1.957     raeburn  13846: =item B<$usec> Student's section in course
1.286     matthew  13847: 
                   13848: =item B<$end> Unix time of the roles expiration
                   13849: 
                   13850: =item B<$start> Unix time of the roles start date
                   13851: 
                   13852: =item B<$forceid> If defined, allow $uid to be changed
                   13853: 
                   13854: =item B<$desiredhome> server to use as home server for student
                   13855: 
1.957     raeburn  13856: =item B<$email> Student's permanent e-mail address
                   13857: 
                   13858: =item B<$type> Type of enrollment (auto or manual)
                   13859: 
1.963     raeburn  13860: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   13861: 
                   13862: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  13863: 
1.963     raeburn  13864: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  13865: 
1.963     raeburn  13866: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  13867: 
1.1216    raeburn  13868: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   13869: 
                   13870: =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  13871: 
1.286     matthew  13872: =back
1.297     matthew  13873: 
                   13874: =item *
                   13875: 
                   13876: modify_student_enrollment
                   13877: 
1.1235    raeburn  13878: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  13879: 'role.request.course' must be defined for this function to proceed.
                   13880: 
                   13881: Inputs:
                   13882: 
                   13883: =over 4
                   13884: 
1.1235    raeburn  13885: =item $udom, student's domain
1.297     matthew  13886: 
1.1235    raeburn  13887: =item $uname, student's name
1.297     matthew  13888: 
1.1235    raeburn  13889: =item $uid, student's user id
1.297     matthew  13890: 
1.1235    raeburn  13891: =item $first, student's first name
1.297     matthew  13892: 
                   13893: =item $middle
                   13894: 
                   13895: =item $last
                   13896: 
                   13897: =item $gene
                   13898: 
                   13899: =item $usec
                   13900: 
                   13901: =item $end
                   13902: 
                   13903: =item $start
                   13904: 
1.957     raeburn  13905: =item $type
                   13906: 
                   13907: =item $locktype
                   13908: 
                   13909: =item $cid
                   13910: 
                   13911: =item $selfenroll
                   13912: 
                   13913: =item $context
                   13914: 
1.1216    raeburn  13915: =item $credits, number of credits student will earn from this class
                   13916: 
1.1314    raeburn  13917: =item $instsec, institutional course section code for student
                   13918: 
1.297     matthew  13919: =back
                   13920: 
1.191     harris41 13921: 
                   13922: =item *
                   13923: 
1.243     albertel 13924: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   13925: custom role; give a custom role to a user for the level given by URL.  Specify
                   13926: name and domain of role author, and role name
1.191     harris41 13927: 
                   13928: =item *
                   13929: 
1.243     albertel 13930: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 13931: 
                   13932: =item *
                   13933: 
1.243     albertel 13934: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   13935: 
                   13936: =back
                   13937: 
                   13938: =head2 Course Infomation
                   13939: 
                   13940: =over 4
1.191     harris41 13941: 
                   13942: =item *
                   13943: 
1.1118    foxr     13944: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 13945: specified course id, including all environment settings for the
                   13946: course, the description of the course will be in the hash under the
                   13947: key 'description'
1.191     harris41 13948: 
1.1118    foxr     13949: $options is an optional parameter that if supplied is a hash reference that controls
                   13950: what how this function works.  It has the following key/values:
                   13951: 
                   13952: =over 4
                   13953: 
                   13954: =item freshen_cache
                   13955: 
                   13956: If defined, and the environment cache for the course is valid, it is 
                   13957: returned in the returned hash.
                   13958: 
                   13959: =item one_time
                   13960: 
                   13961: If defined, the last cache time is set to _now_
                   13962: 
                   13963: =item user
                   13964: 
                   13965: If defined, the supplied username is used instead of the current user.
                   13966: 
                   13967: 
                   13968: =back
                   13969: 
1.191     harris41 13970: =item *
                   13971: 
1.624     albertel 13972: resdata($name,$domain,$type,@which) : request for current parameter
                   13973: setting for a specific $type, where $type is either 'course' or 'user',
                   13974: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  13975: answers for 10 minutes.
1.243     albertel 13976: 
1.877     foxr     13977: =item *
                   13978: 
                   13979: get_courseresdata($courseid, $domain) : dump the entire course resource
                   13980: data base, returning a hash that is keyed by the resource name and has
                   13981: values that are the resource value.  I believe that the timestamps and
                   13982: versions are also returned.
                   13983: 
1.1236    raeburn  13984: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   13985: supplemental content area. This routine caches the number of files for 
                   13986: 10 minutes.
                   13987: 
1.243     albertel 13988: =back
                   13989: 
                   13990: =head2 Course Modification
                   13991: 
                   13992: =over 4
1.191     harris41 13993: 
                   13994: =item *
                   13995: 
1.243     albertel 13996: writecoursepref($courseid,%prefs) : write preferences (environment
                   13997: database) for a course
1.191     harris41 13998: 
                   13999: =item *
                   14000: 
1.1011    raeburn  14001: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14002: 
                   14003: =item *
                   14004: 
1.1038    raeburn  14005: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14006: 
1.1167    droeschl 14007: =item *
                   14008: 
                   14009: is_course($courseid), is_course($cdom, $cnum)
                   14010: 
                   14011: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14012: two component version $cdom, $cnum. It checks if the specified course exists.
                   14013: 
                   14014: Returns:
                   14015:     undef if the course doesn't exist, otherwise
                   14016:     in scalar context the combined courseid.
                   14017:     in list context the two components of the course identifier, domain and 
                   14018:     courseid.    
                   14019: 
1.243     albertel 14020: =back
                   14021: 
                   14022: =head2 Resource Subroutines
                   14023: 
                   14024: =over 4
1.191     harris41 14025: 
                   14026: =item *
                   14027: 
1.243     albertel 14028: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14029: 
                   14030: =item *
                   14031: 
1.243     albertel 14032: repcopy($filename) : subscribes to the requested file, and attempts to
                   14033: replicate from the owning library server, Might return
1.607     raeburn  14034: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14035: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14036: resource. Expects the local filesystem pathname
                   14037: (/home/httpd/html/res/....)
                   14038: 
                   14039: =back
                   14040: 
                   14041: =head2 Resource Information
                   14042: 
                   14043: =over 4
1.191     harris41 14044: 
                   14045: =item *
                   14046: 
1.1228    raeburn  14047: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14048: and returns the value of a variety of different possible values,
                   14049: $varname should be a request string, and the other parameters can be
                   14050: used to specify who and what one is asking about. Ordinarily, $cid 
                   14051: does not need to be specified, as it is retrived from 
                   14052: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14053: within lonuserstate::loadmap() when initializing a course, before
                   14054: $env{'request.course.id'} has been set, so it needs to be provided
                   14055: in that one case.
1.243     albertel 14056: 
                   14057: Possible values for $varname are environment.lastname (or other item
                   14058: from the envirnment hash), user.name (or someother aspect about the
                   14059: user), resource.0.maxtries (or some other part and parameter of a
                   14060: resource)
1.204     albertel 14061: 
                   14062: =item *
                   14063: 
1.243     albertel 14064: directcondval($number) : get current value of a condition; reads from a state
                   14065: string
1.204     albertel 14066: 
                   14067: =item *
                   14068: 
1.243     albertel 14069: condval($condidx) : value of condition index based on state
1.204     albertel 14070: 
                   14071: =item *
                   14072: 
1.243     albertel 14073: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14074: resource's metadata, $what should be either a specific key, or either
                   14075: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14076: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14077: 
                   14078: this function automatically caches all requests
1.191     harris41 14079: 
                   14080: =item *
                   14081: 
1.243     albertel 14082: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14083: network of library servers; returns file handle of where SQL and regex results
                   14084: will be stored for query
1.191     harris41 14085: 
                   14086: =item *
                   14087: 
1.1282    raeburn  14088: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   14089: return symbolic list entry (all arguments optional). 
                   14090: 
                   14091: Args: filename is the filename (including path) for the file for which a symb 
                   14092: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   14093: to check access status if more than one resource was found in the bighash 
                   14094: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   14095: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   14096: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14097: cause possible symbs to be checked to determine if they are subject to content
                   14098: blocking, if so they will not be included as possible symbs; possibles is a
                   14099: ref to a hash, which, as a side effect, will be populated with all possible 
                   14100: symbs (content blocking not tested).
                   14101:  
1.243     albertel 14102: returns the data handle
1.191     harris41 14103: 
                   14104: =item *
                   14105: 
1.1190    raeburn  14106: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   14107: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14108: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  14109: on failure, user must be in a course, as it assumes the existence of
                   14110: the course initial hash, and uses $env('request.course.id'}.  The third
                   14111: arg is an optional reference to a scalar.  If this arg is passed in the 
                   14112: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14113: encrypted; otherwise it will be null.  
1.191     harris41 14114: 
                   14115: =item *
                   14116: 
1.243     albertel 14117: symbclean($symb) : removes versions numbers from a symb, returns the
                   14118: cleaned symb
1.191     harris41 14119: 
                   14120: =item *
                   14121: 
1.243     albertel 14122: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14123: course map, user must be in a course for it to work.
1.191     harris41 14124: 
                   14125: =item *
                   14126: 
1.243     albertel 14127: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14128: 
                   14129: =item *
                   14130: 
1.243     albertel 14131: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14132: a random seed, all arguments are optional, if they aren't sent it uses the
                   14133: environment to derive them. Note: if symb isn't sent and it can't get one
                   14134: from &symbread it will use the current time as its return value
1.191     harris41 14135: 
                   14136: =item *
                   14137: 
1.243     albertel 14138: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14139: unfakeable, receipt
1.191     harris41 14140: 
                   14141: =item *
                   14142: 
1.620     albertel 14143: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14144: 
                   14145: =item *
                   14146: 
1.243     albertel 14147: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14148: 
                   14149: =item *
                   14150: 
1.243     albertel 14151: 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 14152: 
                   14153: =item *
                   14154: 
1.243     albertel 14155: 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 14156: 
                   14157: =item *
                   14158: 
1.243     albertel 14159: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14160: 
                   14161: =item *
                   14162: 
1.243     albertel 14163: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14164: forcing spreadsheet to reevaluate the resource scores next time.
                   14165: 
1.1195    raeburn  14166: =item * 
                   14167: 
1.1196    raeburn  14168: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14169: when viewing in course context.
1.1195    raeburn  14170: 
1.1196    raeburn  14171:  input: six args -- filename (decluttered), course number, course domain,
                   14172:                     url, symb (if registered) and group (if this is a 
                   14173:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  14174: 
1.1196    raeburn  14175:  output: array of five scalars --
1.1195    raeburn  14176:          $cfile -- url for file editing if editable on current server
                   14177:          $home -- homeserver of resource (i.e., for author if published,
                   14178:                                           or course if uploaded.).
                   14179:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  14180:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   14181:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  14182: 
                   14183: =item *
                   14184: 
                   14185: is_course_upload($file,$cnum,$cdom)
                   14186: 
                   14187: Used in course context to determine if current file was uploaded to 
                   14188: the course (i.e., would be found in /userfiles/docs on the course's 
                   14189: homeserver.
                   14190: 
                   14191:   input: 3 args -- filename (decluttered), course number and course domain.
                   14192:   output: boolean -- 1 if file was uploaded.
                   14193: 
1.243     albertel 14194: =back
                   14195: 
                   14196: =head2 Storing/Retreiving Data
                   14197: 
                   14198: =over 4
1.191     harris41 14199: 
                   14200: =item *
                   14201: 
1.1269    raeburn  14202: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   14203: permanently for this url; hashref needs to be given and should be a \%hashname;
                   14204: the remaining args aren't required and if they aren't passed or are '' they will
                   14205: be derived from the env (with the exception of $laststore, which is an 
                   14206: optional arg used when a user's submission is stored in grading).
                   14207: $laststore is $version=$timestamp, where $version is the most recent version
                   14208: number retrieved for the corresponding $symb in the $namespace db file, and
                   14209: $timestamp is the timestamp for that transaction (UNIX time).
                   14210: $laststore is currently only passed when cstore() is called by 
                   14211: structuretags::finalize_storage().
1.191     harris41 14212: 
                   14213: =item *
                   14214: 
1.1269    raeburn  14215: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   14216: but uses critical subroutine
1.191     harris41 14217: 
                   14218: =item *
                   14219: 
1.243     albertel 14220: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14221: all args are optional
1.191     harris41 14222: 
                   14223: =item *
                   14224: 
1.717     albertel 14225: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14226: dumps the complete (or key matching regexp) namespace into a hash
                   14227: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14228: normally &store()ed into
                   14229: 
                   14230: $range should be either an integer '100' (give me the first 100
                   14231:                                            matching records)
                   14232:               or be  two integers sperated by a - with no spaces
                   14233:                  '30-50' (give me the 30th through the 50th matching
                   14234:                           records)
                   14235: 
                   14236: 
                   14237: =item *
                   14238: 
1.1269    raeburn  14239: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14240: replaces a &store() version of data with a replacement set of data
                   14241: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  14242: reference. If $tolog is true, the transaction is logged in the courselog
                   14243: with an action=PUTSTORE.
1.717     albertel 14244: 
                   14245: =item *
                   14246: 
1.243     albertel 14247: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14248: works very similar to store/cstore, but all data is stored in a
                   14249: temporary location and can be reset using tmpreset, $storehash should
                   14250: be a hash reference, returns nothing on success
1.191     harris41 14251: 
                   14252: =item *
                   14253: 
1.243     albertel 14254: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14255: similar to restore, but all data is stored in a temporary location and
                   14256: can be reset using tmpreset. Returns a hash of values on success,
                   14257: error string otherwise.
1.191     harris41 14258: 
                   14259: =item *
                   14260: 
1.243     albertel 14261: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14262: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14263: 
                   14264: =item *
                   14265: 
1.243     albertel 14266: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14267: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14268: 
                   14269: =item *
                   14270: 
1.243     albertel 14271: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14272: namesp ($udom and $uname are optional)
1.191     harris41 14273: 
                   14274: =item *
                   14275: 
1.702     albertel 14276: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14277: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14278: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  14279: 
1.702     albertel 14280: $range should be either an integer '100' (give me the first 100
                   14281:                                            matching records)
                   14282:               or be  two integers sperated by a - with no spaces
                   14283:                  '30-50' (give me the 30th through the 50th matching
                   14284:                           records)
1.449     matthew  14285: =item *
                   14286: 
                   14287: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   14288: $store can be a scalar, an array reference, or if the amount to be 
                   14289: incremented is > 1, a hash reference.
                   14290: 
                   14291: ($udom and $uname are optional)
1.191     harris41 14292: 
                   14293: =item *
                   14294: 
1.243     albertel 14295: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   14296: ($udom and $uname are optional)
1.191     harris41 14297: 
                   14298: =item *
                   14299: 
1.243     albertel 14300: cput($namespace,$storehash,$udom,$uname) : critical put
                   14301: ($udom and $uname are optional)
1.191     harris41 14302: 
                   14303: =item *
                   14304: 
1.748     albertel 14305: newput($namespace,$storehash,$udom,$uname) :
                   14306: 
                   14307: Attempts to store the items in the $storehash, but only if they don't
                   14308: currently exist, if this succeeds you can be certain that you have 
                   14309: successfully created a new key value pair in the $namespace db.
                   14310: 
                   14311: 
                   14312: Args:
                   14313:  $namespace: name of database to store values to
                   14314:  $storehash: hashref to store to the db
                   14315:  $udom: (optional) domain of user containing the db
                   14316:  $uname: (optional) name of user caontaining the db
                   14317: 
                   14318: Returns:
                   14319:  'ok' -> succeeded in storing all keys of $storehash
                   14320:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   14321:                         least <key> already existed in the db (other
                   14322:                         requested keys may also already exist)
1.967     bisitz   14323:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 14324:  'con_lost' -> unable to contact request server
                   14325:  'refused' -> action was not allowed by remote machine
                   14326: 
                   14327: 
                   14328: =item *
                   14329: 
1.243     albertel 14330: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14331: reference filled in from namesp (encrypts the return communication)
                   14332: ($udom and $uname are optional)
1.191     harris41 14333: 
                   14334: =item *
                   14335: 
1.243     albertel 14336: log($udom,$name,$home,$message) : write to permanent log for user; use
                   14337: critical subroutine
                   14338: 
1.806     raeburn  14339: =item *
                   14340: 
1.860     raeburn  14341: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   14342: array reference filled in from namespace found in domain level on either
                   14343: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  14344: 
                   14345: =item *
                   14346: 
1.860     raeburn  14347: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   14348: domain level either on specified domain server ($uhome) or primary domain 
                   14349: server ($udom and $uhome are optional)
1.806     raeburn  14350: 
1.943     raeburn  14351: =item * 
                   14352: 
1.1240    raeburn  14353: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   14354: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   14355: the target domain.
                   14356: 
                   14357: May also include additional key => value pairs for the following groups:
                   14358: 
                   14359: =over
                   14360: 
                   14361: =item
                   14362: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   14363: 
                   14364: =over
                   14365: 
                   14366: =item defaultquota, authorquota
                   14367: 
                   14368: =back
                   14369: 
                   14370: =item
                   14371: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   14372: portfolio for users).
                   14373: 
                   14374: =over
                   14375: 
                   14376: =item
                   14377: aboutme, blog, webdav, portfolio
                   14378: 
                   14379: =back
                   14380: 
                   14381: =item
                   14382: requestcourses: ability to request courses, and how requests are processed.
                   14383: 
                   14384: =over
                   14385: 
                   14386: =item
1.1305    raeburn  14387: official, unofficial, community, textbook, placement
1.1240    raeburn  14388: 
                   14389: =back
                   14390: 
                   14391: =item
                   14392: inststatus: types of institutional affiliation, and order in which they are displayed.
                   14393: 
                   14394: =over
                   14395: 
                   14396: =item
1.1256    raeburn  14397: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  14398: 
                   14399: =back
                   14400: 
                   14401: =item
                   14402: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   14403: for course's uploaded content.
                   14404: 
                   14405: =over
                   14406: 
                   14407: =item
1.1246    raeburn  14408: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  14409: communityquota, textbookquota, placementquota
1.1240    raeburn  14410: 
                   14411: =back
                   14412: 
                   14413: =item
                   14414: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   14415: on your servers.
                   14416: 
                   14417: =over
                   14418: 
                   14419: =item 
                   14420: remotesessions, hostedsessions
                   14421: 
                   14422: =back
                   14423: 
                   14424: =back
                   14425: 
                   14426: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   14427: utility to create a configuration.db file on a domain's primary library server 
                   14428: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   14429: -- corresponding values are authentication type (internal, krb4, krb5,
                   14430: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   14431: will be available. Values are retrieved from cache (if current), unless the
                   14432: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   14433: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   14434: 
                   14435: Typical usage:
1.943     raeburn  14436: 
1.1240    raeburn  14437: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  14438: 
1.243     albertel 14439: =back
                   14440: 
                   14441: =head2 Network Status Functions
                   14442: 
                   14443: =over 4
1.191     harris41 14444: 
                   14445: =item *
                   14446: 
1.1137    raeburn  14447: dirlist() : return directory list based on URI (first arg).
                   14448: 
                   14449: Inputs: 1 required, 5 optional.
                   14450: 
                   14451: =over
                   14452: 
                   14453: =item 
                   14454: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   14455: 
                   14456: =item
                   14457: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   14458: 
                   14459: =item
                   14460: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   14461: 
                   14462: =item
                   14463: $getpropath - boolean: 1 if prepend path using &propath(). 
                   14464: 
                   14465: =item
                   14466: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   14467: 
                   14468: =item 
                   14469: $alternateRoot - path to prepend in place of path from $uri.
                   14470: 
                   14471: =back
                   14472: 
                   14473: Returns: Array of up to two items.
                   14474: 
                   14475: =over
                   14476: 
                   14477: a reference to an array of files/subdirectories
                   14478: 
                   14479: =over
                   14480: 
                   14481: Each element in the array of files/subdirectories is a & separated list of
                   14482: item name and the result of running stat on the item.  If dirlist was requested
                   14483: for a file instead of a directory, the item name will be ''. For a directory 
                   14484: listing, if the item is a metadata file, the element will end &N&M 
                   14485: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   14486: default copyright set (1).  
                   14487: 
                   14488: =back
                   14489: 
                   14490: a scalar containing error condition (if encountered).
                   14491: 
                   14492: =over
                   14493: 
                   14494: =item 
                   14495: no_host (no homeserver identified for $username:$domain).
                   14496: 
                   14497: =item 
                   14498: no_such_host (server contacted for listing not identified as valid host).
                   14499: 
                   14500: =item 
                   14501: con_lost (connection to remote server failed).
                   14502: 
                   14503: =item 
                   14504: refused (invalid $username:$domain received on lond side).
                   14505: 
                   14506: =item 
                   14507: no_such_dir (directory at specified path on lond side does not exist). 
                   14508: 
                   14509: =item 
                   14510: empty (directory at specified path on lond side is empty).
                   14511: 
                   14512: =over
                   14513: 
                   14514: This is currently not encountered because the &ls3, &ls2, 
                   14515: &ls (_handler) routines on the lond side do not filter out
                   14516: . and .. from a directory listing. 
                   14517: 
                   14518: =back
                   14519: 
                   14520: =back
                   14521: 
                   14522: =back
1.191     harris41 14523: 
                   14524: =item *
                   14525: 
1.243     albertel 14526: spareserver() : find server with least workload from spare.tab
                   14527: 
1.986     foxr     14528: 
                   14529: =item *
                   14530: 
                   14531: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   14532: if there is no corresponding loncapa host.
                   14533: 
1.243     albertel 14534: =back
                   14535: 
1.986     foxr     14536: 
1.243     albertel 14537: =head2 Apache Request
                   14538: 
                   14539: =over 4
1.191     harris41 14540: 
                   14541: =item *
                   14542: 
1.243     albertel 14543: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   14544: localhost, posts hash
                   14545: 
                   14546: =back
                   14547: 
                   14548: =head2 Data to String to Data
                   14549: 
                   14550: =over 4
1.191     harris41 14551: 
                   14552: =item *
                   14553: 
1.243     albertel 14554: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   14555: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 14556: 
                   14557: =item *
                   14558: 
1.243     albertel 14559: hashref2str($hashref) : convert a hashref into a string complete with
                   14560: escaping and '=' and '&' separators, supports elements that are
                   14561: arrayrefs and hashrefs
1.191     harris41 14562: 
                   14563: =item *
                   14564: 
1.243     albertel 14565: arrayref2str($arrayref) : convert an arrayref into a string complete
                   14566: with escaping and '&' separators, supports elements that are arrayrefs
                   14567: and hashrefs
1.191     harris41 14568: 
                   14569: =item *
                   14570: 
1.243     albertel 14571: str2hash($string) : convert string to hash using unescaping and
                   14572: splitting on '=' and '&', supports elements that are arrayrefs and
                   14573: hashrefs
1.191     harris41 14574: 
                   14575: =item *
                   14576: 
1.243     albertel 14577: str2array($string) : convert string to hash using unescaping and
                   14578: splitting on '&', supports elements that are arrayrefs and hashrefs
                   14579: 
                   14580: =back
                   14581: 
                   14582: =head2 Logging Routines
                   14583: 
                   14584: 
                   14585: These routines allow one to make log messages in the lonnet.log and
                   14586: lonnet.perm logfiles.
1.191     harris41 14587: 
1.1119    foxr     14588: =over 4
                   14589: 
1.191     harris41 14590: =item *
                   14591: 
1.243     albertel 14592: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 14593: 
                   14594: =item *
                   14595: 
1.243     albertel 14596: logthis() : append message to the normal lonnet.log file, it gets
                   14597: preiodically rolled over and deleted.
1.191     harris41 14598: 
                   14599: =item *
                   14600: 
1.243     albertel 14601: logperm() : append a permanent message to lonnet.perm.log, this log
                   14602: file never gets deleted by any automated portion of the system, only
                   14603: messages of critical importance should go in here.
                   14604: 
1.1119    foxr     14605: 
1.243     albertel 14606: =back
                   14607: 
                   14608: =head2 General File Helper Routines
                   14609: 
                   14610: =over 4
1.191     harris41 14611: 
                   14612: =item *
                   14613: 
1.481     raeburn  14614: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   14615: (a) files in /uploaded
                   14616:   (i) If a local copy of the file exists - 
                   14617:       compares modification date of local copy with last-modified date for 
                   14618:       definitive version stored on home server for course. If local copy is 
                   14619:       stale, requests a new version from the home server and stores it. 
                   14620:       If the original has been removed from the home server, then local copy 
                   14621:       is unlinked.
                   14622:   (ii) If local copy does not exist -
                   14623:       requests the file from the home server and stores it. 
                   14624:   
                   14625:   If $caller is 'uploadrep':  
                   14626:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   14627:     for request for files originally uploaded via DOCS. 
                   14628:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   14629:   
                   14630:   Otherwise:
                   14631:      This indicates a call from the content generation phase of the request.
                   14632:      -  returns the entire contents of the file or -1.
                   14633:      
                   14634: (b) files in /res
                   14635:    - returns the entire contents of a file or -1; 
                   14636:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 14637: 
1.712     albertel 14638: 
                   14639: =item *
                   14640: 
                   14641: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   14642:                   reference
                   14643: 
                   14644: returns either a stat() list of data about the file or an empty list
                   14645: if the file doesn't exist or couldn't find out about it (connection
                   14646: problems or user unknown)
                   14647: 
1.191     harris41 14648: =item *
                   14649: 
1.243     albertel 14650: filelocation($dir,$file) : returns file system location of a file
                   14651: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   14652: directory that relative $file lookups are to looked in ($dir of /a/dir
                   14653: and a file of ../bob will become /a/bob)
1.191     harris41 14654: 
                   14655: =item *
                   14656: 
                   14657: hreflocation($dir,$file) : returns file system location or a URL; same as
                   14658: filelocation except for hrefs
                   14659: 
                   14660: =item *
                   14661: 
1.1261    raeburn  14662: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   14663: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 14664: 
1.243     albertel 14665: =back
                   14666: 
1.608     albertel 14667: =head2 Usererfile file routines (/uploaded*)
                   14668: 
                   14669: =over 4
                   14670: 
                   14671: =item *
                   14672: 
                   14673: userfileupload(): main rotine for putting a file in a user or course's
                   14674:                   filespace, arguments are,
                   14675: 
1.620     albertel 14676:  formname - required - this is the name of the element in $env where the
1.608     albertel 14677:            filename, and the contents of the file to create/modifed exist
1.620     albertel 14678:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   14679:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  14680:  context - if coursedoc, store the file in the course of the active role
                   14681:              of the current user; 
                   14682:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   14683:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 14684:  subdir - required - subdirectory to put the file in under ../userfiles/
                   14685:          if undefined, it will be placed in "unknown"
                   14686: 
                   14687:  (This routine calls clean_filename() to remove any dangerous
                   14688:  characters from the filename, and then calls finuserfileupload() to
                   14689:  complete the transaction)
                   14690: 
                   14691:  returns either the url of the uploaded file (/uploaded/....) if successful
                   14692:  and /adm/notfound.html if unsuccessful
                   14693: 
                   14694: =item *
                   14695: 
                   14696: clean_filename(): routine for cleaing a filename up for storage in
                   14697:                  userfile space, argument is:
                   14698: 
                   14699:  filename - proposed filename
                   14700: 
                   14701: returns: the new clean filename
                   14702: 
                   14703: =item *
                   14704: 
1.1090    raeburn  14705: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 14706: userspace, probably shouldn't be called directly
                   14707: 
                   14708:   docuname: username or courseid of destination for the file
                   14709:   docudom: domain of user/course of destination for the file
                   14710:   formname: same as for userfileupload()
1.1090    raeburn  14711:   fname: filename (including subdirectories) for the file
                   14712:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   14713:   allfiles: reference to hash used to store objects found by parser
                   14714:   codebase: reference to hash used for codebases of java objects found by parser
                   14715:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   14716:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   14717:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   14718:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   14719:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   14720:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  14721:   mimetype: reference to scalar to accommodate mime type determined
                   14722:             from File::MMagic if $parser = parse.
1.608     albertel 14723: 
                   14724:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  14725:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   14726:  was 'overwrite').
                   14727:  
1.608     albertel 14728: 
                   14729: =item *
                   14730: 
                   14731: renameuserfile(): renames an existing userfile to a new name
                   14732: 
                   14733:   Args:
                   14734:    docuname: username or courseid of destination for the file
                   14735:    docudom: domain of user/course of destination for the file
                   14736:    old: current file name (including any subdirs under userfiles)
                   14737:    new: desired file name (including any subdirs under userfiles)
                   14738: 
                   14739: =item *
                   14740: 
                   14741: mkdiruserfile(): creates a directory is a userfiles dir
                   14742: 
                   14743:   Args:
                   14744:    docuname: username or courseid of destination for the file
                   14745:    docudom: domain of user/course of destination for the file
                   14746:    dir: dir to create (including any subdirs under userfiles)
                   14747: 
                   14748: =item *
                   14749: 
                   14750: removeuserfile(): removes a file that exists in userfiles
                   14751: 
                   14752:   Args:
                   14753:    docuname: username or courseid of destination for the file
                   14754:    docudom: domain of user/course of destination for the file
                   14755:    fname: filname to delete (including any subdirs under userfiles)
                   14756: 
                   14757: =item *
                   14758: 
                   14759: removeuploadedurl(): convience function for removeuserfile()
                   14760: 
                   14761:   Args:
                   14762:    url:  a full /uploaded/... url to delete
                   14763: 
1.747     albertel 14764: =item * 
                   14765: 
                   14766: get_portfile_permissions():
                   14767:   Args:
                   14768:     domain: domain of user or course contain the portfolio files
                   14769:     user: name of user or num of course contain the portfolio files
                   14770:   Returns:
                   14771:     hashref of a dump of the proper file_permissions.db
                   14772:    
                   14773: 
                   14774: =item * 
                   14775: 
                   14776: get_access_controls():
                   14777: 
                   14778: Args:
                   14779:   current_permissions: the hash ref returned from get_portfile_permissions()
                   14780:   group: (optional) the group you want the files associated with
                   14781:   file: (optional) the file you want access info on
                   14782: 
                   14783: Returns:
1.749     raeburn  14784:     a hash (keys are file names) of hashes containing
                   14785:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   14786:         values are XML containing access control settings (see below) 
1.747     albertel 14787: 
                   14788: Internal notes:
                   14789: 
1.749     raeburn  14790:  access controls are stored in file_permissions.db as key=value pairs.
                   14791:     key -> path to file/file_name\0uniqueID:scope_end_start
                   14792:         where scope -> public,guest,course,group,domains or users.
                   14793:               end -> UNIX time for end of access (0 -> no end date)
                   14794:               start -> UNIX time for start of access
                   14795: 
                   14796:     value -> XML description of access control
                   14797:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   14798:             <start></start>
                   14799:             <end></end>
                   14800: 
                   14801:             <password></password>  for scope type = guest
                   14802: 
                   14803:             <domain></domain>     for scope type = course or group
                   14804:             <number></number>
                   14805:             <roles id="">
                   14806:              <role></role>
                   14807:              <access></access>
                   14808:              <section></section>
                   14809:              <group></group>
                   14810:             </roles>
                   14811: 
                   14812:             <dom></dom>         for scope type = domains
                   14813: 
                   14814:             <users>             for scope type = users
                   14815:              <user>
                   14816:               <uname></uname>
                   14817:               <udom></udom>
                   14818:              </user>
                   14819:             </users>
                   14820:            </scope> 
                   14821:               
                   14822:  Access data is also aggregated for each file in an additional key=value pair:
                   14823:  key -> path to file/file_name\0accesscontrol 
                   14824:  value -> reference to hash
                   14825:           hash contains key = value pairs
                   14826:           where key = uniqueID:scope_end_start
                   14827:                 value = UNIX time record was last updated
                   14828: 
                   14829:           Used to improve speed of look-ups of access controls for each file.  
                   14830:  
                   14831:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   14832: 
1.1198    raeburn  14833: =item *
                   14834: 
1.749     raeburn  14835: modify_access_controls():
                   14836: 
                   14837: Modifies access controls for a portfolio file
                   14838: Args
                   14839: 1. file name
                   14840: 2. reference to hash of required changes,
                   14841: 3. domain
                   14842: 4. username
                   14843:   where domain,username are the domain of the portfolio owner 
                   14844:   (either a user or a course) 
                   14845: 
                   14846: Returns:
                   14847: 1. result of additions or updates ('ok' or 'error', with error message). 
                   14848: 2. result of deletions ('ok' or 'error', with error message).
                   14849: 3. reference to hash of any new or updated access controls.
                   14850: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   14851:    key = integer (inbound ID)
1.1198    raeburn  14852:    value = uniqueID
                   14853: 
                   14854: =item *
                   14855: 
                   14856: get_timebased_id():
                   14857: 
                   14858: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   14859: course via the Course Editor (e.g., folders, composite pages, 
                   14860: group bulletin boards).
                   14861: 
                   14862: Args: (first three required; six others optional)
                   14863: 
                   14864: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   14865:    docssequence, or name of group
                   14866: 
                   14867: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   14868:    e.g., num, boardids
                   14869: 
                   14870: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   14871:    file will be named nohist_namespace.db
                   14872: 
                   14873: 4. cdom: domain of course; default is current course domain from %env
                   14874: 
                   14875: 5. cnum: course number; default is current course number from %env
                   14876: 
                   14877: 6. idtype: set to concat if an additional digit is to be appended to the 
                   14878:    unix timestamp to form the suffix, if the plain timestamp is already
                   14879:    in use.  Default is to not do this, but simply increment the unix 
                   14880:    timestamp by 1 until a unique key is obtained.
                   14881: 
                   14882: 7. who: holder of locking key; defaults to user:domain for user.
                   14883: 
                   14884: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   14885:    retrying); default is 3.
                   14886: 
                   14887: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   14888: 
                   14889: Returns:
                   14890: 
                   14891: 1. suffix obtained (numeric)
                   14892: 
                   14893: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   14894: 
                   14895: 3. error: contains (localized) error message if an error occurred.
                   14896: 
1.747     albertel 14897: 
1.608     albertel 14898: =back
                   14899: 
1.243     albertel 14900: =head2 HTTP Helper Routines
                   14901: 
                   14902: =over 4
                   14903: 
1.191     harris41 14904: =item *
                   14905: 
                   14906: escape() : unpack non-word characters into CGI-compatible hex codes
                   14907: 
                   14908: =item *
                   14909: 
                   14910: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   14911: 
1.243     albertel 14912: =back
                   14913: 
                   14914: =head1 PRIVATE SUBROUTINES
                   14915: 
                   14916: =head2 Underlying communication routines (Shouldn't call)
                   14917: 
                   14918: =over 4
                   14919: 
                   14920: =item *
                   14921: 
                   14922: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   14923: 
                   14924: =item *
                   14925: 
                   14926: reply() : uses subreply to send a message to remote machine, logs all failures
                   14927: 
                   14928: =item *
                   14929: 
                   14930: critical() : passes a critical message to another server; if cannot
                   14931: get through then place message in connection buffer directory and
                   14932: returns con_delayed, if incapable of saving message, returns
                   14933: con_failed
                   14934: 
                   14935: =item *
                   14936: 
                   14937: reconlonc() : tries to reconnect lonc client processes.
                   14938: 
                   14939: =back
                   14940: 
                   14941: =head2 Resource Access Logging
                   14942: 
                   14943: =over 4
                   14944: 
                   14945: =item *
                   14946: 
                   14947: flushcourselogs() : flush (save) buffer logs and access logs
                   14948: 
                   14949: =item *
                   14950: 
                   14951: courselog($what) : save message for course in hash
                   14952: 
                   14953: =item *
                   14954: 
                   14955: courseacclog($what) : save message for course using &courselog().  Perform
                   14956: special processing for specific resource types (problems, exams, quizzes, etc).
                   14957: 
1.191     harris41 14958: =item *
                   14959: 
                   14960: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   14961: as a PerlChildExitHandler
1.243     albertel 14962: 
                   14963: =back
                   14964: 
                   14965: =head2 Other
                   14966: 
                   14967: =over 4
                   14968: 
                   14969: =item *
                   14970: 
                   14971: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 14972: 
                   14973: =back
                   14974: 
                   14975: =cut
1.877     foxr     14976: 

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