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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1319  ! damieng     4: # $Id: lonnet.pm,v 1.1318 2016/08/25 08:09:34 droeschl Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.1182    foxr       78: 
1.1173    foxr       79: use Encode;
                     80: 
1.1245    raeburn    81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138    raeburn    82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     83:             %managerstab);
1.871     albertel   84: 
                     85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        88:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        89: 
1.1       albertel   90: use IO::Socket;
1.31      www        91: use GDBM_File;
1.208     albertel   92: use HTML::LCParser;
1.88      www        93: use Fcntl qw(:flock);
1.870     albertel   94: use Storable qw(thaw nfreeze);
1.1289    damieng    95: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   96: use Cache::Memcached;
1.676     albertel   97: use Digest::MD5;
1.790     albertel   98: use Math::Random;
1.1024    raeburn    99: use File::MMagic;
1.807     albertel  100: use LONCAPA qw(:DEFAULT :match);
1.740     www       101: use LONCAPA::Configuration;
1.1160    www       102: use LONCAPA::lonmetadata;
1.1167    droeschl  103: use LONCAPA::Lond;
1.1117    foxr      104: 
1.1090    raeburn   105: use File::Copy;
1.676     albertel  106: 
1.195     www       107: my $readit;
1.1288    damieng   108: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  109: 
1.619     albertel  110: require Exporter;
                    111: 
                    112: our @ISA = qw (Exporter);
                    113: our @EXPORT = qw(%env);
                    114: 
1.449     matthew   115: 
1.1187    raeburn   116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       117: {
                    118:     my $logid;
1.1187    raeburn   119:     sub write_log {
1.1188    raeburn   120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184    raeburn   121:         if ($context eq 'course') {
                    122:             if (($cnum eq '') || ($cdom eq '')) {
                    123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    125:             }
1.957     raeburn   126:         }
1.1184    raeburn   127: 	$logid ++;
1.957     raeburn   128:         my $now = time();
                    129: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1184    raeburn   130:         my $logentry = { 
                    131:                           $id => {
                    132:                                    'exe_uname' => $env{'user.name'},
                    133:                                    'exe_udom'  => $env{'user.domain'},
                    134:                                    'exe_time'  => $now,
                    135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    136:                                    'delflag'   => $delflag,
                    137:                                    'logentry'  => $storehash,
                    138:                                    'uname'     => $uname,
                    139:                                    'udom'      => $udom,
                    140:                                   }
                    141:                        };
                    142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       143:     }
                    144: }
1.1       albertel  145: 
1.163     harris41  146: sub logtouch {
                    147:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  148:     unless (-e "$execdir/logs/lonnet.log") {	
                    149: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  150: 	close $fh;
                    151:     }
                    152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    154: }
                    155: 
1.1       albertel  156: sub logthis {
                    157:     my $message=shift;
                    158:     my $execdir=$perlvar{'lonDaemons'};
                    159:     my $now=time;
                    160:     my $local=localtime($now);
1.448     albertel  161:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    163: 	print $fh $logstring;
1.448     albertel  164: 	close($fh);
                    165:     }
1.1       albertel  166:     return 1;
                    167: }
                    168: 
                    169: sub logperm {
                    170:     my $message=shift;
                    171:     my $execdir=$perlvar{'lonDaemons'};
                    172:     my $now=time;
                    173:     my $local=localtime($now);
1.448     albertel  174:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    175: 	print $fh "$now:$message:$local\n";
                    176: 	close($fh);
                    177:     }
1.1       albertel  178:     return 1;
                    179: }
                    180: 
1.850     albertel  181: sub create_connection {
1.853     albertel  182:     my ($hostname,$lonid) = @_;
1.851     albertel  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  184: 				     Type    => SOCK_STREAM,
                    185: 				     Timeout => 10);
                    186:     return 0 if (!$client);
1.890     albertel  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  188:     my $result = <$client>;
                    189:     chomp($result);
                    190:     return 1 if ($result eq 'done');
                    191:     return 0;
                    192: }
                    193: 
1.983     raeburn   194: sub get_server_timezone {
                    195:     my ($cnum,$cdom) = @_;
                    196:     my $home=&homeserver($cnum,$cdom);
                    197:     if ($home ne 'no_host') {
                    198:         my $cachetime = 24*3600;
                    199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    200:         if (defined($cached)) {
                    201:             return $timezone;
                    202:         } else {
                    203:             my $timezone = &reply('servertimezone',$home);
                    204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    205:         }
                    206:     }
                    207: }
1.850     albertel  208: 
1.1106    raeburn   209: sub get_server_distarch {
                    210:     my ($lonhost,$ignore_cache) = @_;
                    211:     if (defined($lonhost)) {
                    212:         if (!defined(&hostname($lonhost))) {
                    213:             return;
                    214:         }
                    215:         my $cachetime = 12*3600;
                    216:         if (!$ignore_cache) {
                    217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    218:             if (defined($cached)) {
                    219:                 return $distarch;
                    220:             }
                    221:         }
                    222:         my $rep = &reply('serverdistarch',$lonhost);
                    223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    225:                 $rep eq '') {
                    226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    227:         }
                    228:     }
                    229:     return;
                    230: }
                    231: 
1.1315    raeburn   232: sub get_servercerts_info {
                    233:     my ($lonhost,$context) = @_;
                    234:     my ($rep,$uselocal);
                    235:     if (grep { $_ eq $lonhost } &current_machine_ids()) {
                    236:         $uselocal = 1;
                    237:     }
1.1316    raeburn   238:     if (($context ne 'cgi') && ($uselocal)) {
1.1315    raeburn   239:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                    240:         if ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
                    241:             if ($1 < 6) {
                    242:                 $uselocal = 0;
                    243:             }
                    244:         }
                    245:     }
                    246:     if ($uselocal) {
                    247:         $rep = LONCAPA::Lond::server_certs(\%perlvar);
                    248:     } else {
                    249:         $rep=&reply('servercerts',$lonhost);
                    250:     }
                    251:     my ($result,%returnhash);
                    252:     if (defined($lonhost)) {
                    253:         if (!defined(&hostname($lonhost))) {
                    254:             return;
                    255:         }
                    256:     }
                    257:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    258:         ($rep eq 'unknown_cmd')) {
                    259:         $result = $rep;
                    260:     } else {
                    261:         $result = 'ok';
                    262:         my @pairs=split(/\&/,$rep);
                    263:         foreach my $item (@pairs) {
                    264:             my ($key,$value)=split(/=/,$item,2);
                    265:             my $what = &unescape($key);
                    266:             $returnhash{$what}=&thaw_unescape($value);
                    267:         }
                    268:     }
                    269:     return ($result,\%returnhash);
                    270: }
                    271: 
1.993     raeburn   272: sub get_server_loncaparev {
1.1073    raeburn   273:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   274:     if (defined($lonhost)) {
                    275:         if (!defined(&hostname($lonhost))) {
                    276:             undef($lonhost);
                    277:         }
                    278:     }
                    279:     if (!defined($lonhost)) {
                    280:         if (defined(&domain($dom,'primary'))) {
                    281:             $lonhost=&domain($dom,'primary');
                    282:             if ($lonhost eq 'no_host') {
                    283:                 undef($lonhost);
                    284:             }
                    285:         }
                    286:     }
                    287:     if (defined($lonhost)) {
1.1073    raeburn   288:         my $cachetime = 12*3600;
                    289:         if (!$ignore_cache) {
                    290:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    291:             if (defined($cached)) {
                    292:                 return $loncaparev;
                    293:             }
                    294:         }
                    295:         my ($answer,$loncaparev);
                    296:         my @ids=&current_machine_ids();
                    297:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    298:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   299:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   300:                 $loncaparev = $1;
                    301:             }
                    302:         } else {
                    303:             $answer = &reply('serverloncaparev',$lonhost);
                    304:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    305:                 if ($caller eq 'loncron') {
                    306:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   307:                     $ua->timeout(4);
1.1073    raeburn   308:                     my $protocol = $protocol{$lonhost};
                    309:                     $protocol = 'http' if ($protocol ne 'https');
                    310:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    311:                     my $request=new HTTP::Request('GET',$url);
                    312:                     my $response=$ua->request($request);
                    313:                     unless ($response->is_error()) {
                    314:                         my $content = $response->content;
1.1081    raeburn   315:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   316:                             $loncaparev = $1;
                    317:                         }
                    318:                     }
                    319:                 } else {
                    320:                     $loncaparev = $loncaparevs{$lonhost};
                    321:                 }
1.1081    raeburn   322:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   323:                 $loncaparev = $1;
                    324:             }
1.993     raeburn   325:         }
1.1073    raeburn   326:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   327:     }
                    328: }
                    329: 
1.1074    raeburn   330: sub get_server_homeID {
                    331:     my ($hostname,$ignore_cache,$caller) = @_;
                    332:     unless ($ignore_cache) {
                    333:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    334:         if (defined($cached)) {
                    335:             return $serverhomeID;
                    336:         }
                    337:     }
                    338:     my $cachetime = 12*3600;
                    339:     my $serverhomeID;
                    340:     if ($caller eq 'loncron') { 
                    341:         my @machine_ids = &machine_ids($hostname);
                    342:         foreach my $id (@machine_ids) {
                    343:             my $response = &reply('serverhomeID',$id);
                    344:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    345:                 $serverhomeID = $response;
                    346:                 last;
                    347:             }
                    348:         }
                    349:         if ($serverhomeID eq '') {
                    350:             $serverhomeID = $machine_ids[-1];
                    351:         }
                    352:     } else {
                    353:         $serverhomeID = $serverhomeIDs{$hostname};
                    354:     }
                    355:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    356: }
                    357: 
1.1121    raeburn   358: sub get_remote_globals {
                    359:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   360:     my ($result,%returnhash,%whatneeded);
                    361:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   362:         foreach my $what (sort(keys(%{$whathash}))) {
                    363:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   364:             my ($response,$cached);
1.1121    raeburn   365:             unless ($ignore_cache) {
1.1125    raeburn   366:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   367:             }
                    368:             if (defined($cached)) {
1.1125    raeburn   369:                 $returnhash{$what} = $response;
1.1121    raeburn   370:             } else {
1.1125    raeburn   371:                 $whatneeded{$what} = 1;
1.1121    raeburn   372:             }
                    373:         }
1.1125    raeburn   374:         if (keys(%whatneeded) == 0) {
                    375:             $result = 'ok';
                    376:         } else {
1.1121    raeburn   377:             my $requested = &freeze_escape(\%whatneeded);
                    378:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   379:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    380:                 ($rep eq 'unknown_cmd')) {
                    381:                 $result = $rep;
                    382:             } else {
                    383:                 $result = 'ok';
1.1121    raeburn   384:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   385:                 foreach my $item (@pairs) {
                    386:                     my ($key,$value)=split(/=/,$item,2);
                    387:                     my $what = &unescape($key);
                    388:                     my $hashid = $lonhost.'-'.$what;
                    389:                     $returnhash{$what}=&thaw_unescape($value);
                    390:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   391:                 }
                    392:             }
                    393:         }
                    394:     }
1.1125    raeburn   395:     return ($result,\%returnhash);
1.1121    raeburn   396: }
                    397: 
1.1124    raeburn   398: sub remote_devalidate_cache {
1.1241    raeburn   399:     my ($lonhost,$cachekeys) = @_;
                    400:     my $items;
                    401:     return unless (ref($cachekeys) eq 'ARRAY');
                    402:     my $cachestr = join('&',@{$cachekeys});
                    403:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   404:     return $response;
                    405: }
                    406: 
1.1       albertel  407: # -------------------------------------------------- Non-critical communication
                    408: sub subreply {
                    409:     my ($cmd,$server)=@_;
1.838     albertel  410:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      411:     #
                    412:     #  With loncnew process trimming, there's a timing hole between lonc server
                    413:     #  process exit and the master server picking up the listen on the AF_UNIX
                    414:     #  socket.  In that time interval, a lock file will exist:
                    415: 
                    416:     my $lockfile=$peerfile.".lock";
                    417:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1289    damieng   418: 	sleep(0.1);
1.549     foxr      419:     }
                    420:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      421:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      422:     #
1.550     foxr      423:     #   We'll give the connection a few tries before abandoning it.  If
                    424:     #   connection is not possible, we'll con_lost back to the client.
                    425:     #   
                    426:     my $client;
                    427:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    428: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    429: 				      Type    => SOCK_STREAM,
                    430: 				      Timeout => 10);
1.869     albertel  431: 	if ($client) {
1.550     foxr      432: 	    last;		# Connected!
1.850     albertel  433: 	} else {
1.853     albertel  434: 	    &create_connection(&hostname($server),$server);
1.550     foxr      435: 	}
1.1289    damieng   436:         sleep(0.1);	# Try again later if failed connection.
1.550     foxr      437:     }
                    438:     my $answer;
                    439:     if ($client) {
1.704     albertel  440: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      441: 	$answer=<$client>;
                    442: 	if (!$answer) { $answer="con_lost"; }
                    443: 	chomp($answer);
                    444:     } else {
                    445: 	$answer = 'con_lost';	# Failed connection.
                    446:     }
1.1       albertel  447:     return $answer;
                    448: }
                    449: 
                    450: sub reply {
                    451:     my ($cmd,$server)=@_;
1.838     albertel  452:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  453:     my $answer=subreply($cmd,$server);
1.65      www       454:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  455:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       456:                 " $cmd to $server returned $answer</font>");
                    457:     }
1.1       albertel  458:     return $answer;
                    459: }
                    460: 
                    461: # ----------------------------------------------------------- Send USR1 to lonc
                    462: 
                    463: sub reconlonc {
1.891     albertel  464:     my ($lonid) = @_;
                    465:     if ($lonid) {
1.1295    raeburn   466:         my $hostname = &hostname($lonid);
1.891     albertel  467: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    468: 	if ($hostname && -e $peerfile) {
                    469: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    470: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    471: 					     Type    => SOCK_STREAM,
                    472: 					     Timeout => 10);
                    473: 	    if ($client) {
                    474: 		print $client ("reset_retries\n");
                    475: 		my $answer=<$client>;
                    476: 		#reset just this one.
                    477: 	    }
                    478: 	}
                    479: 	return;
                    480:     }
                    481: 
1.836     www       482:     &logthis("Trying to reconnect lonc");
1.1       albertel  483:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  484:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  485: 	my $loncpid=<$fh>;
                    486:         chomp($loncpid);
                    487:         if (kill 0 => $loncpid) {
                    488: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    489:             kill USR1 => $loncpid;
                    490:             sleep 1;
1.1295    raeburn   491:         } else {
1.12      www       492: 	    &logthis(
1.672     albertel  493:                "<font color=\"blue\">WARNING:".
1.12      www       494:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  495:         }
                    496:     } else {
1.836     www       497: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  498:     }
                    499: }
                    500: 
                    501: # ------------------------------------------------------ Critical communication
1.12      www       502: 
1.1       albertel  503: sub critical {
                    504:     my ($cmd,$server)=@_;
1.838     albertel  505:     unless (&hostname($server)) {
1.672     albertel  506:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       507:                " Critical message to unknown server ($server)</font>");
                    508:         return 'no_such_host';
                    509:     }
1.1       albertel  510:     my $answer=reply($cmd,$server);
                    511:     if ($answer eq 'con_lost') {
1.1295    raeburn   512: 	&reconlonc($server);
1.589     albertel  513: 	my $answer=reply($cmd,$server);
1.1       albertel  514:         if ($answer eq 'con_lost') {
                    515:             my $now=time;
                    516:             my $middlename=$cmd;
1.5       www       517:             $middlename=substr($middlename,0,16);
1.1       albertel  518:             $middlename=~s/\W//g;
                    519:             my $dfilename=
1.305     www       520:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    521:             $dumpcount++;
1.1       albertel  522:             {
1.448     albertel  523: 		my $dfh;
                    524: 		if (open($dfh,">$dfilename")) {
                    525: 		    print $dfh "$cmd\n"; 
                    526: 		    close($dfh);
                    527: 		}
1.1       albertel  528:             }
1.1288    damieng   529:             sleep 1;
1.1       albertel  530:             my $wcmd='';
                    531:             {
1.448     albertel  532: 		my $dfh;
                    533: 		if (open($dfh,"<$dfilename")) {
                    534: 		    $wcmd=<$dfh>; 
                    535: 		    close($dfh);
                    536: 		}
1.1       albertel  537:             }
                    538:             chomp($wcmd);
1.7       www       539:             if ($wcmd eq $cmd) {
1.672     albertel  540: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       541:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  542:                 &logperm("D:$server:$cmd");
                    543: 	        return 'con_delayed';
                    544:             } else {
1.672     albertel  545:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       546:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  547:                 &logperm("F:$server:$cmd");
                    548:                 return 'con_failed';
                    549:             }
                    550:         }
                    551:     }
                    552:     return $answer;
1.405     albertel  553: }
                    554: 
1.755     albertel  555: # ------------------------------------------- check if return value is an error
                    556: 
                    557: sub error {
                    558:     my ($result) = @_;
1.756     albertel  559:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  560: 	if ($2 == 2) { return undef; }
                    561: 	return $1;
                    562:     }
                    563:     return undef;
                    564: }
                    565: 
1.783     albertel  566: sub convert_and_load_session_env {
                    567:     my ($lonidsdir,$handle)=@_;
                    568:     my @profile;
                    569:     {
1.917     albertel  570: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    571: 	if (!$opened) {
1.915     albertel  572: 	    return 0;
                    573: 	}
1.783     albertel  574: 	flock($idf,LOCK_SH);
                    575: 	@profile=<$idf>;
                    576: 	close($idf);
                    577:     }
                    578:     my %temp_env;
                    579:     foreach my $line (@profile) {
1.786     albertel  580: 	if ($line !~ m/=/) {
                    581: 	    return 0;
                    582: 	}
1.783     albertel  583: 	chomp($line);
                    584: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    585: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    586:     }
                    587:     unlink("$lonidsdir/$handle.id");
                    588:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    589: 	    0640)) {
                    590: 	%disk_env = %temp_env;
                    591: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    592: 	untie(%disk_env);
                    593:     }
1.786     albertel  594:     return 1;
1.783     albertel  595: }
                    596: 
1.374     www       597: # ------------------------------------------- Transfer profile into environment
1.780     albertel  598: my $env_loaded;
                    599: sub transfer_profile_to_env {
1.788     albertel  600:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    601:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       602: 
1.720     albertel  603:     if (!defined($lonidsdir)) {
                    604: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    605:     }
                    606:     if (!defined($handle)) {
                    607:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    608:     }
                    609: 
1.786     albertel  610:     my $convert;
                    611:     {
1.917     albertel  612:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    613: 	if (!$opened) {
1.915     albertel  614: 	    return;
                    615: 	}
1.786     albertel  616: 	flock($idf,LOCK_SH);
                    617: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    618: 		&GDBM_READER(),0640)) {
                    619: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    620: 	    untie(%disk_env);
                    621: 	} else {
                    622: 	    $convert = 1;
                    623: 	}
                    624:     }
                    625:     if ($convert) {
                    626: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    627: 	    &logthis("Failed to load session, or convert session.");
                    628: 	}
1.374     www       629:     }
1.783     albertel  630: 
1.786     albertel  631:     my %remove;
1.783     albertel  632:     while ( my $envname = each(%env) ) {
1.433     matthew   633:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    634:             if ($time < time-300) {
1.783     albertel  635:                 $remove{$key}++;
1.433     matthew   636:             }
                    637:         }
                    638:     }
1.783     albertel  639: 
1.619     albertel  640:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  641:     $env_loaded=1;
1.783     albertel  642:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   643:         &delenv($expired_key);
1.374     www       644:     }
1.1       albertel  645: }
                    646: 
1.916     albertel  647: # ---------------------------------------------------- Check for valid session 
                    648: sub check_for_valid_session {
1.1245    raeburn   649:     my ($r,$name,$userhashref) = @_;
1.916     albertel  650:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   651:     if ($name eq '') {
                    652:         $name = 'lonID';
                    653:     }
                    654:     my $lonid=$cookies{$name};
1.916     albertel  655:     return undef if (!$lonid);
                    656: 
                    657:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   658:     my $lonidsdir;
                    659:     if ($name eq 'lonDAV') {
                    660:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    661:     } else {
                    662:         $lonidsdir=$r->dir_config('lonIDsDir');
                    663:     }
1.916     albertel  664:     return undef if (!-e "$lonidsdir/$handle.id");
                    665: 
1.917     albertel  666:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    667:     return undef if (!$opened);
1.916     albertel  668: 
                    669:     flock($idf,LOCK_SH);
                    670:     my %disk_env;
                    671:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    672: 	    &GDBM_READER(),0640)) {
                    673: 	return undef;	
                    674:     }
                    675: 
                    676:     if (!defined($disk_env{'user.name'})
                    677: 	|| !defined($disk_env{'user.domain'})) {
                    678: 	return undef;
                    679:     }
1.1245    raeburn   680: 
                    681:     if (ref($userhashref) eq 'HASH') {
                    682:         $userhashref->{'name'} = $disk_env{'user.name'};
                    683:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1212    raeburn   684:     }
1.1245    raeburn   685: 
1.916     albertel  686:     return $handle;
                    687: }
                    688: 
1.830     albertel  689: sub timed_flock {
                    690:     my ($file,$lock_type) = @_;
                    691:     my $failed=0;
                    692:     eval {
                    693: 	local $SIG{__DIE__}='DEFAULT';
                    694: 	local $SIG{ALRM}=sub {
                    695: 	    $failed=1;
                    696: 	    die("failed lock");
                    697: 	};
                    698: 	alarm(13);
                    699: 	flock($file,$lock_type);
                    700: 	alarm(0);
                    701:     };
                    702:     if ($failed) {
                    703: 	return undef;
                    704:     } else {
                    705: 	return 1;
                    706:     }
                    707: }
                    708: 
1.5       www       709: # ---------------------------------------------------------- Append Environment
                    710: 
                    711: sub appenv {
1.949     raeburn   712:     my ($newenv,$roles) = @_;
                    713:     if (ref($newenv) eq 'HASH') {
                    714:         foreach my $key (keys(%{$newenv})) {
                    715:             my $refused = 0;
                    716: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    717:                 $refused = 1;
                    718:                 if (ref($roles) eq 'ARRAY') {
1.1250    raeburn   719:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   720:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    721:                         $refused = 0;
                    722:                     }
                    723:                 }
                    724:             }
                    725:             if ($refused) {
                    726:                 &logthis("<font color=\"blue\">WARNING: ".
                    727:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    728:                          .'</font>');
                    729: 	        delete($newenv->{$key});
                    730:             } else {
                    731:                 $env{$key}=$newenv->{$key};
                    732:             }
                    733:         }
                    734:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    735:         if ($opened
                    736: 	    && &timed_flock($env_file,LOCK_EX)
                    737: 	    &&
                    738: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    739: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    740: 	    while (my ($key,$value) = each(%{$newenv})) {
                    741: 	        $disk_env{$key} = $value;
                    742: 	    }
                    743: 	    untie(%disk_env);
1.35      www       744:         }
1.191     harris41  745:     }
1.56      www       746:     return 'ok';
                    747: }
                    748: # ----------------------------------------------------- Delete from Environment
                    749: 
                    750: sub delenv {
1.1104    raeburn   751:     my ($delthis,$regexp,$roles) = @_;
                    752:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    753:         my $refused = 1;
                    754:         if (ref($roles) eq 'ARRAY') {
                    755:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    756:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    757:                 $refused = 0;
                    758:             }
                    759:         }
                    760:         if ($refused) {
                    761:             &logthis("<font color=\"blue\">WARNING: ".
                    762:                      "Attempt to delete from environment ".$delthis);
                    763:             return 'error';
                    764:         }
1.56      www       765:     }
1.917     albertel  766:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    767:     if ($opened
1.915     albertel  768: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  769: 	&&
                    770: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    771: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  772: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   773: 	    if ($regexp) {
                    774:                 if ($key=~/^$delthis/) {
                    775:                     delete($env{$key});
                    776:                     delete($disk_env{$key});
                    777:                 } 
                    778:             } else {
                    779:                 if ($key=~/^\Q$delthis\E/) {
                    780: 		    delete($env{$key});
                    781: 		    delete($disk_env{$key});
                    782: 	        }
                    783:             }
1.448     albertel  784: 	}
1.783     albertel  785: 	untie(%disk_env);
1.5       www       786:     }
                    787:     return 'ok';
1.369     albertel  788: }
                    789: 
1.790     albertel  790: sub get_env_multiple {
                    791:     my ($name) = @_;
                    792:     my @values;
                    793:     if (defined($env{$name})) {
                    794:         # exists is it an array
                    795:         if (ref($env{$name})) {
                    796:             @values=@{ $env{$name} };
                    797:         } else {
                    798:             $values[0]=$env{$name};
                    799:         }
                    800:     }
                    801:     return(@values);
                    802: }
                    803: 
1.958     www       804: # ------------------------------------------------------------------- Locking
                    805: 
                    806: sub set_lock {
                    807:     my ($text)=@_;
                    808:     $locknum++;
                    809:     my $id=$$.'-'.$locknum;
                    810:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    811:              'session.lock.'.$id => $text});
                    812:     return $id;
                    813: }
                    814: 
                    815: sub get_locks {
                    816:     my $num=0;
                    817:     my %texts=();
                    818:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    819:        if ($lock=~/\w/) {
                    820:           $num++;
                    821:           $texts{$lock}=$env{'session.lock.'.$lock};
                    822:        }
                    823:    }
                    824:    return ($num,%texts);
                    825: }
                    826: 
                    827: sub remove_lock {
                    828:     my ($id)=@_;
                    829:     my $newlocks='';
                    830:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    831:        if (($lock=~/\w/) && ($lock ne $id)) {
                    832:           $newlocks.=','.$lock;
                    833:        }
                    834:     }
                    835:     &appenv({'session.locks' => $newlocks});
                    836:     &delenv('session.lock.'.$id);
                    837: }
                    838: 
                    839: sub remove_all_locks {
                    840:     my $activelocks=$env{'session.locks'};
                    841:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    842:        if ($lock=~/\w/) {
                    843:           &remove_lock($lock);
                    844:        }
                    845:     }
                    846: }
                    847: 
                    848: 
1.369     albertel  849: # ------------------------------------------ Find out current server userload
                    850: sub userload {
                    851:     my $numusers=0;
                    852:     {
                    853: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    854: 	my $filename;
                    855: 	my $curtime=time;
                    856: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  857: 	    next if ($filename eq '.' || $filename eq '..');
                    858: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  859: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  860: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  861: 	}
                    862: 	closedir(LONIDS);
                    863:     }
                    864:     my $userloadpercent=0;
                    865:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    866:     if ($maxuserload) {
1.371     albertel  867: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  868:     }
1.372     albertel  869:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  870:     return $userloadpercent;
1.283     www       871: }
                    872: 
1.1       albertel  873: # ------------------------------ Find server with least workload from spare.tab
1.11      www       874: 
1.1       albertel  875: sub spareserver {
1.1083    raeburn   876:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  877:     my $spare_server;
1.370     albertel  878:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  879:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    880:                                                      :  $userloadpercent;
1.1083    raeburn   881:     my ($uint_dom,$remotesessions);
                    882:     if (($udom ne '') && (&domain($udom) ne '')) {
                    883:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    884:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    885:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    886:         $remotesessions = $udomdefaults{'remotesessions'};
                    887:     }
1.1123    raeburn   888:     my $spareshash = &this_host_spares($udom);
                    889:     if (ref($spareshash) eq 'HASH') {
                    890:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    891:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279    raeburn   892:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    893:                                              $try_server));
1.1123    raeburn   894: 	        ($spare_server, $lowest_load) =
                    895: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    896:             }
1.1083    raeburn   897:         }
1.784     albertel  898: 
1.1123    raeburn   899:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    900: 
                    901:         if (!$found_server) {
                    902:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    903: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn   904:                     next unless (&spare_can_host($udom,$uint_dom,
                    905:                                                  $remotesessions,$try_server));
1.1123    raeburn   906: 	            ($spare_server, $lowest_load) =
                    907: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    908:                 }
                    909: 	    }
                    910:         }
1.784     albertel  911:     }
                    912: 
                    913:     if (!$want_server_name) {
1.968     raeburn   914:         my $protocol = 'http';
                    915:         if ($protocol{$spare_server} eq 'https') {
                    916:             $protocol = $protocol{$spare_server};
                    917:         }
1.1001    raeburn   918:         if (defined($spare_server)) {
                    919:             my $hostname = &hostname($spare_server);
1.1083    raeburn   920:             if (defined($hostname)) {
1.1001    raeburn   921: 	        $spare_server = $protocol.'://'.$hostname;
                    922:             }
                    923:         }
1.784     albertel  924:     }
                    925:     return $spare_server;
                    926: }
                    927: 
                    928: sub compare_server_load {
1.1253    raeburn   929:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    930: 
                    931:     if ($required) {
                    932:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    933:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    934:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    935:         if (($major eq '' && $minor eq '') ||
                    936:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    937:             return ($spare_server,$lowest_load);
                    938:         }
                    939:     }
1.784     albertel  940: 
                    941:     my $loadans     = &reply('load',    $try_server);
                    942:     my $userloadans = &reply('userload',$try_server);
                    943: 
                    944:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   945: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  946:     }
                    947: 
                    948:     my $load;
                    949:     if ($loadans =~ /\d/) {
                    950: 	if ($userloadans =~ /\d/) {
                    951: 	    #both are numbers, pick the bigger one
                    952: 	    $load = ($loadans > $userloadans) ? $loadans 
                    953: 		                              : $userloadans;
1.411     albertel  954: 	} else {
1.784     albertel  955: 	    $load = $loadans;
1.411     albertel  956: 	}
1.784     albertel  957:     } else {
                    958: 	$load = $userloadans;
                    959:     }
                    960: 
                    961:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    962: 	$spare_server = $try_server;
                    963: 	$lowest_load  = $load;
1.370     albertel  964:     }
1.784     albertel  965:     return ($spare_server,$lowest_load);
1.202     matthew   966: }
1.914     albertel  967: 
                    968: # --------------------------- ask offload servers if user already has a session
                    969: sub find_existing_session {
                    970:     my ($udom,$uname) = @_;
1.1123    raeburn   971:     my $spareshash = &this_host_spares($udom);
                    972:     if (ref($spareshash) eq 'HASH') {
                    973:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    974:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    975:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    976:             }
                    977:         }
                    978:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    979:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    980:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    981:             }
                    982:         }
1.914     albertel  983:     }
                    984:     return;
                    985: }
                    986: 
                    987: # -------------------------------- ask if server already has a session for user
                    988: sub has_user_session {
                    989:     my ($lonid,$udom,$uname) = @_;
                    990:     my $result = &reply(join(':','userhassession',
                    991: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    992:     return 1 if ($result eq 'ok');
                    993: 
                    994:     return 0;
                    995: }
                    996: 
1.1076    raeburn   997: # --------- determine least loaded server in a user's domain which allows login
                    998: 
                    999: sub choose_server {
1.1259    raeburn  1000:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1001:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1002:     my %servers = &get_servers($udom);
1.1076    raeburn  1003:     my $lowest_load = 30000;
1.1259    raeburn  1004:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1005:     if ($skiploadbal) {
                   1006:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1007:         unless (defined($cached)) {
                   1008:             my $cachetime = 60*60*24;
                   1009:             my %domconfig =
                   1010:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1011:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1012:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1013:                                            $cachetime);
                   1014:             }
                   1015:         }
                   1016:     }
1.1076    raeburn  1017:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn  1018:         if ($skiploadbal) {
                   1019:             if (ref($balancers) eq 'HASH') {
                   1020:                 next if (exists($balancers->{$lonhost}));
                   1021:             }
                   1022:         }   
1.1115    raeburn  1023:         my $loginvia;
                   1024:         if ($checkloginvia) {
                   1025:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1026:             if ($loginvia) {
                   1027:                 my ($server,$path) = split(/:/,$loginvia);
                   1028:                 ($login_host, $lowest_load) =
1.1253    raeburn  1029:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1030:                 if ($login_host eq $server) {
                   1031:                     $portal_path = $path;
1.1151    raeburn  1032:                     $isredirect = 1;
1.1116    raeburn  1033:                 }
                   1034:             } else {
                   1035:                 ($login_host, $lowest_load) =
1.1253    raeburn  1036:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1037:                 if ($login_host eq $lonhost) {
                   1038:                     $portal_path = '';
1.1151    raeburn  1039:                     $isredirect = ''; 
1.1116    raeburn  1040:                 }
                   1041:             }
                   1042:         } else {
1.1076    raeburn  1043:             ($login_host, $lowest_load) =
1.1253    raeburn  1044:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1045:         }
                   1046:     }
                   1047:     if ($login_host ne '') {
1.1116    raeburn  1048:         $hostname = &hostname($login_host);
1.1076    raeburn  1049:     }
1.1151    raeburn  1050:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn  1051: }
                   1052: 
1.202     matthew  1053: # --------------------------------------------- Try to change a user's password
                   1054: 
                   1055: sub changepass {
1.799     raeburn  1056:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1057:     $currentpass = &escape($currentpass);
                   1058:     $newpass     = &escape($newpass);
1.1030    raeburn  1059:     my $lonhost = $perlvar{'lonHostID'};
                   1060:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1061: 		       $server);
                   1062:     if (! $answer) {
                   1063: 	&logthis("No reply on password change request to $server ".
                   1064: 		 "by $uname in domain $udom.");
                   1065:     } elsif ($answer =~ "^ok") {
                   1066:         &logthis("$uname in $udom successfully changed their password ".
                   1067: 		 "on $server.");
                   1068:     } elsif ($answer =~ "^pwchange_failure") {
                   1069: 	&logthis("$uname in $udom was unable to change their password ".
                   1070: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1071: 		 "or pwchange");
                   1072:     } elsif ($answer =~ "^non_authorized") {
                   1073:         &logthis("$uname in $udom did not get their password correct when ".
                   1074: 		 "attempting to change it on $server.");
                   1075:     } elsif ($answer =~ "^auth_mode_error") {
                   1076:         &logthis("$uname in $udom attempted to change their password despite ".
                   1077: 		 "not being locally or internally authenticated on $server.");
                   1078:     } elsif ($answer =~ "^unknown_user") {
                   1079:         &logthis("$uname in $udom attempted to change their password ".
                   1080: 		 "on $server but were unable to because $server is not ".
                   1081: 		 "their home server.");
                   1082:     } elsif ($answer =~ "^refused") {
                   1083: 	&logthis("$server refused to change $uname in $udom password because ".
                   1084: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1085:     } elsif ($answer =~ "invalid_client") {
                   1086:         &logthis("$server refused to change $uname in $udom password because ".
                   1087:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1088:     }
                   1089:     return $answer;
1.1       albertel 1090: }
                   1091: 
1.169     harris41 1092: # ----------------------- Try to determine user's current authentication scheme
                   1093: 
                   1094: sub queryauthenticate {
                   1095:     my ($uname,$udom)=@_;
1.456     albertel 1096:     my $uhome=&homeserver($uname,$udom);
                   1097:     if (!$uhome) {
                   1098: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1099: 	return 'no_host';
                   1100:     }
                   1101:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1102:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1103: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1104:     }
1.456     albertel 1105:     return $answer;
1.169     harris41 1106: }
                   1107: 
1.1       albertel 1108: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1109: 
1.1       albertel 1110: sub authenticate {
1.1073    raeburn  1111:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1112:     $upass=&escape($upass);
                   1113:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1114:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1115:     my $newhome;
1.836     www      1116:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1117: # Maybe the machine was offline and only re-appeared again recently?
                   1118:         &reconlonc();
                   1119: # One more
1.952     raeburn  1120: 	$uhome=&homeserver($uname,$udom,1);
                   1121:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1122:             if (defined(&domain($udom,'primary'))) {
                   1123:                 $newhome=&domain($udom,'primary');
                   1124:             }
                   1125:             if ($newhome ne '') {
                   1126:                 $uhome = $newhome;
                   1127:             }
                   1128:         }
1.836     www      1129: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1130: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1131: 	    return 'no_host';
                   1132:         }
1.1       albertel 1133:     }
1.1073    raeburn  1134:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1135:     if ($answer eq 'authorized') {
1.952     raeburn  1136:         if ($newhome) {
                   1137:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1138:             return 'no_account_on_host'; 
                   1139:         } else {
                   1140:             &logthis("User $uname at $udom authorized by $uhome");
                   1141:             return $uhome;
                   1142:         }
1.471     albertel 1143:     }
                   1144:     if ($answer eq 'non_authorized') {
                   1145: 	&logthis("User $uname at $udom rejected by $uhome");
                   1146: 	return 'no_host'; 
1.9       www      1147:     }
1.471     albertel 1148:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1149:     return 'no_host';
                   1150: }
                   1151: 
1.1073    raeburn  1152: sub can_host_session {
1.1074    raeburn  1153:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1154:     my $canhost = 1;
1.1074    raeburn  1155:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1156:     if (ref($remotesessions) eq 'HASH') {
                   1157:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1158:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1159:                 $canhost = 0;
                   1160:             } else {
                   1161:                 $canhost = 1;
                   1162:             }
                   1163:         }
                   1164:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1165:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1166:                 $canhost = 1;
                   1167:             } else {
                   1168:                 $canhost = 0;
                   1169:             }
                   1170:         }
                   1171:         if ($canhost) {
                   1172:             if ($remotesessions->{'version'} ne '') {
                   1173:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1174:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1175:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1176:                         my $major = $1;
                   1177:                         my $minor = $2;
                   1178:                         if (($major < $reqmajor ) ||
                   1179:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1180:                             $canhost = 0;
                   1181:                         }
                   1182:                     } else {
                   1183:                         $canhost = 0;
                   1184:                     }
                   1185:                 }
                   1186:             }
                   1187:         }
                   1188:     }
                   1189:     if ($canhost) {
                   1190:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1191:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1192:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1193:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1194:                 if (($uint_dom ne '') && 
                   1195:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1196:                     $canhost = 0;
                   1197:                 } else {
                   1198:                     $canhost = 1;
                   1199:                 }
                   1200:             }
                   1201:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1202:                 if (($uint_dom ne '') && 
                   1203:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1204:                     $canhost = 1;
                   1205:                 } else {
                   1206:                     $canhost = 0;
                   1207:                 }
                   1208:             }
                   1209:         }
                   1210:     }
                   1211:     return $canhost;
                   1212: }
                   1213: 
1.1083    raeburn  1214: sub spare_can_host {
                   1215:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1216:     my $canhost=1;
1.1279    raeburn  1217:     my $try_server_hostname = &hostname($try_server);
                   1218:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1219:     my $serverhomedom = &host_domain($serverhomeID);
                   1220:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1221:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1222:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1223:             $canhost = 0;
                   1224:         }
                   1225:     }
                   1226:     if (($canhost) && ($uint_dom)) {
                   1227:         my @intdoms;
                   1228:         my $internet_names = &get_internet_names($try_server);
                   1229:         if (ref($internet_names) eq 'ARRAY') {
                   1230:             @intdoms = @{$internet_names};
                   1231:         }
                   1232:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1233:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1234:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1235:                                          $remotesessions,
                   1236:                                          $defdomdefaults{'hostedsessions'});
                   1237:         }
1.1083    raeburn  1238:     }
                   1239:     return $canhost;
                   1240: }
                   1241: 
1.1123    raeburn  1242: sub this_host_spares {
                   1243:     my ($dom) = @_;
1.1126    raeburn  1244:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1245:     my @hosts = &current_machine_ids();
                   1246:     foreach my $lonhost (@hosts) {
                   1247:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1248:             $dom_in_use = $dom;
                   1249:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1250:             last;
                   1251:         }
                   1252:     }
1.1126    raeburn  1253:     if ($dom_in_use ne '') {
                   1254:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1255:     }
                   1256:     if (ref($result) ne 'HASH') {
                   1257:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1258:         $dom_in_use = &host_domain($lonhost_in_use);
                   1259:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1260:         if (ref($result) ne 'HASH') {
                   1261:             $result = \%spareid;
                   1262:         }
                   1263:     }
                   1264:     return $result;
                   1265: }
                   1266: 
                   1267: sub spares_for_offload  {
                   1268:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1269:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1270:     if (defined($cached)) {
                   1271:         return $result;
                   1272:     } else {
1.1126    raeburn  1273:         my $cachetime = 60*60*24;
                   1274:         my %domconfig =
                   1275:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1276:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1277:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1278:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1279:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1280:                 }
                   1281:             }
                   1282:         }
                   1283:     }
1.1126    raeburn  1284:     return;
1.1123    raeburn  1285: }
                   1286: 
1.1129    raeburn  1287: sub get_lonbalancer_config {
                   1288:     my ($servers) = @_;
                   1289:     my ($currbalancer,$currtargets);
                   1290:     if (ref($servers) eq 'HASH') {
                   1291:         foreach my $server (keys(%{$servers})) {
                   1292:             my %what = (
                   1293:                          spareid => 1,
                   1294:                          perlvar => 1,
                   1295:                        );
                   1296:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1297:             if ($result eq 'ok') {
                   1298:                 if (ref($returnhash) eq 'HASH') {
                   1299:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1300:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1301:                             $currbalancer = $server;
                   1302:                             $currtargets = {};
                   1303:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1304:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1305:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1306:                                 }
                   1307:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1308:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1309:                                 }
                   1310:                             }
                   1311:                             last;
                   1312:                         }
                   1313:                     }
                   1314:                 }
                   1315:             }
                   1316:         }
                   1317:     }
                   1318:     return ($currbalancer,$currtargets);
                   1319: }
                   1320: 
                   1321: sub check_loadbalancing {
                   1322:     my ($uname,$udom) = @_;
1.1191    raeburn  1323:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1324:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1325:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1326:     my @hosts = &current_machine_ids();
1.1129    raeburn  1327:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1328:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1329:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1330:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1331:     my $domneedscache;
1.1129    raeburn  1332:     my $cachetime = 60*60*24;
                   1333: 
                   1334:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1335:         $dom_in_use = $udom;
                   1336:         $homeintdom = 1;
                   1337:     } else {
                   1338:         $dom_in_use = $serverhomedom;
                   1339:     }
                   1340:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1341:     unless (defined($cached)) {
                   1342:         my %domconfig =
                   1343:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1344:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1345:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1346:         } else {
                   1347:             $domneedscache = $dom_in_use;
1.1129    raeburn  1348:         }
                   1349:     }
                   1350:     if (ref($result) eq 'HASH') {
1.1191    raeburn  1351:         ($is_balancer,$currtargets,$currrules) = 
                   1352:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1353:         if ($is_balancer) {
                   1354:             if (ref($currrules) eq 'HASH') {
                   1355:                 if ($homeintdom) {
                   1356:                     if ($uname ne '') {
                   1357:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1358:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1359:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1360:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1361:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1362:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1363:                             }
                   1364:                         }
                   1365:                         if ($rule_in_effect eq '') {
                   1366:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1367:                             if ($userenv{'inststatus'} ne '') {
                   1368:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1369:                                 my ($othertitle,$usertypes,$types) =
                   1370:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1371:                                 if (ref($types) eq 'ARRAY') {
                   1372:                                     foreach my $type (@{$types}) {
                   1373:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1374:                                             if (exists($currrules->{$type})) {
                   1375:                                                 $rule_in_effect = $currrules->{$type};
                   1376:                                             }
                   1377:                                         }
                   1378:                                     }
                   1379:                                 }
                   1380:                             } else {
                   1381:                                 if (exists($currrules->{'default'})) {
                   1382:                                     $rule_in_effect = $currrules->{'default'};
                   1383:                                 }
                   1384:                             }
                   1385:                         }
                   1386:                     } else {
                   1387:                         if (exists($currrules->{'default'})) {
                   1388:                             $rule_in_effect = $currrules->{'default'};
                   1389:                         }
                   1390:                     }
                   1391:                 } else {
                   1392:                     if ($currrules->{'_LC_external'} ne '') {
                   1393:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1394:                     }
                   1395:                 }
                   1396:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1397:                                                        $uname,$udom);
                   1398:             }
                   1399:         }
                   1400:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1401:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1402:         unless (defined($cached)) {
                   1403:             my %domconfig =
                   1404:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1405:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1406:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1407:             } else {
                   1408:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1409:             }
                   1410:         }
                   1411:         if (ref($result) eq 'HASH') {
1.1191    raeburn  1412:             ($is_balancer,$currtargets,$currrules) = 
                   1413:                 &check_balancer_result($result,@hosts);
                   1414:             if ($is_balancer) {
1.1129    raeburn  1415:                 if (ref($currrules) eq 'HASH') {
                   1416:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1417:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1418:                     }
                   1419:                 }
                   1420:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1421:                                                        $uname,$udom);
                   1422:             }
                   1423:         } else {
                   1424:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1425:                 $is_balancer = 1;
                   1426:                 $offloadto = &this_host_spares($dom_in_use);
                   1427:             }
1.1307    raeburn  1428:             unless (defined($cached)) {
                   1429:                 $domneedscache = $serverhomedom;
                   1430:             }
1.1129    raeburn  1431:         }
                   1432:     } else {
                   1433:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1434:             $is_balancer = 1;
                   1435:             $offloadto = &this_host_spares($dom_in_use);
                   1436:         }
1.1307    raeburn  1437:         unless (defined($cached)) {
                   1438:             $domneedscache = $serverhomedom;
                   1439:         }
                   1440:     }
                   1441:     if ($domneedscache) {
                   1442:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1443:     }
1.1176    raeburn  1444:     if ($is_balancer) {
                   1445:         my $lowest_load = 30000;
                   1446:         if (ref($offloadto) eq 'HASH') {
                   1447:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1448:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1449:                     ($otherserver,$lowest_load) =
                   1450:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1451:                 }
1.1129    raeburn  1452:             }
1.1176    raeburn  1453:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1454: 
1.1176    raeburn  1455:             if (!$found_server) {
                   1456:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1457:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1458:                         ($otherserver,$lowest_load) =
                   1459:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1460:                     }
                   1461:                 }
                   1462:             }
                   1463:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1464:             if (@{$offloadto} == 1) {
                   1465:                 $otherserver = $offloadto->[0];
                   1466:             } elsif (@{$offloadto} > 1) {
                   1467:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1468:                     ($otherserver,$lowest_load) =
                   1469:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1470:                 }
                   1471:             }
                   1472:         }
1.1176    raeburn  1473:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1474:             $is_balancer = 0;
                   1475:             if ($uname ne '' && $udom ne '') {
                   1476:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1477:                     
                   1478:                     &appenv({'user.loadbalexempt'     => $lonhost,  
                   1479:                              'user.loadbalcheck.time' => time});
                   1480:                 }
1.1129    raeburn  1481:             }
                   1482:         }
                   1483:     }
                   1484:     return ($is_balancer,$otherserver);
                   1485: }
                   1486: 
1.1191    raeburn  1487: sub check_balancer_result {
                   1488:     my ($result,@hosts) = @_;
                   1489:     my ($is_balancer,$currtargets,$currrules);
                   1490:     if (ref($result) eq 'HASH') {
                   1491:         if ($result->{'lonhost'} ne '') {
                   1492:             my $currbalancer = $result->{'lonhost'};
                   1493:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1494:                 $is_balancer = 1;
                   1495:                 $currtargets = $result->{'targets'};
                   1496:                 $currrules = $result->{'rules'};
                   1497:             }
                   1498:         } else {
                   1499:             foreach my $key (keys(%{$result})) {
                   1500:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1501:                     (ref($result->{$key}) eq 'HASH')) {
                   1502:                     $is_balancer = 1;
                   1503:                     $currrules = $result->{$key}{'rules'};
                   1504:                     $currtargets = $result->{$key}{'targets'};
                   1505:                     last;
                   1506:                 }
                   1507:             }
                   1508:         }
                   1509:     }
                   1510:     return ($is_balancer,$currtargets,$currrules);
                   1511: }
                   1512: 
1.1129    raeburn  1513: sub get_loadbalancer_targets {
                   1514:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1515:     my $offloadto;
1.1175    raeburn  1516:     if ($rule_in_effect eq 'none') {
                   1517:         return [$perlvar{'lonHostID'}];
                   1518:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1519:         $offloadto = $currtargets;
                   1520:     } else {
                   1521:         if ($rule_in_effect eq 'homeserver') {
                   1522:             my $homeserver = &homeserver($uname,$udom);
                   1523:             if ($homeserver ne 'no_host') {
                   1524:                 $offloadto = [$homeserver];
                   1525:             }
                   1526:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1527:             my %domconfig =
                   1528:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1529:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1530:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1531:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1532:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1533:                     }
                   1534:                 }
                   1535:             } else {
1.1178    raeburn  1536:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1537:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1538:                 if (&hostname($remotebalancer) ne '') {
                   1539:                     $offloadto = [$remotebalancer];
                   1540:                 }
                   1541:             }
                   1542:         } elsif (&hostname($rule_in_effect) ne '') {
                   1543:             $offloadto = [$rule_in_effect];
                   1544:         }
                   1545:     }
                   1546:     return $offloadto;
                   1547: }
                   1548: 
1.1127    raeburn  1549: sub internet_dom_servers {
                   1550:     my ($dom) = @_;
                   1551:     my (%uniqservers,%servers);
                   1552:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1553:     my @machinedoms = &machine_domains($primaryserver);
                   1554:     foreach my $mdom (@machinedoms) {
                   1555:         my %currservers = %servers;
                   1556:         my %server = &get_servers($mdom);
                   1557:         %servers = (%currservers,%server);
                   1558:     }
                   1559:     my %by_hostname;
                   1560:     foreach my $id (keys(%servers)) {
                   1561:         push(@{$by_hostname{$servers{$id}}},$id);
                   1562:     }
                   1563:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1564:         if (@{$by_hostname{$hostname}} > 1) {
                   1565:             my $match = 0;
                   1566:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1567:                 if (&host_domain($id) eq $dom) {
                   1568:                     $uniqservers{$id} = $hostname;
                   1569:                     $match = 1;
                   1570:                 }
                   1571:             }
                   1572:             unless ($match) {
                   1573:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1574:             }
                   1575:         } else {
                   1576:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1577:         }
                   1578:     }
                   1579:     return %uniqservers;
                   1580: }
                   1581: 
1.1       albertel 1582: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1583: 
1.599     albertel 1584: my %homecache;
1.1       albertel 1585: sub homeserver {
1.230     stredwic 1586:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1587:     my $index="$uname:$udom";
1.426     albertel 1588: 
1.599     albertel 1589:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1590: 
                   1591:     my %servers = &get_servers($udom,'library');
                   1592:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1593:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1594: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1595: 
                   1596: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1597: 	if ($answer eq 'found') {
                   1598: 	    delete($badServerCache{$tryserver}); 
                   1599: 	    return $homecache{$index}=$tryserver;
                   1600: 	} elsif ($answer eq 'no_host') {
                   1601: 	    $badServerCache{$tryserver}=1;
                   1602: 	}
1.1       albertel 1603:     }    
                   1604:     return 'no_host';
1.70      www      1605: }
                   1606: 
1.1300    raeburn  1607: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1608: 
                   1609: sub idget {
1.1300    raeburn  1610:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1611:     my %returnhash=();
1.1300    raeburn  1612:     my @ids=(); 
                   1613:     if (ref($idsref) eq 'ARRAY') {
                   1614:         @ids = @{$idsref};
                   1615:     } else {
                   1616:         return %returnhash; 
                   1617:     }
                   1618:     if ($namespace eq '') {
                   1619:         $namespace = 'ids';
                   1620:     }
1.70      www      1621:     
1.841     albertel 1622:     my %servers = &get_servers($udom,'library');
                   1623:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1624: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1625: 	if ($namespace eq 'ids') {
                   1626: 	    $idlist=~tr/A-Z/a-z/;
                   1627: 	}
                   1628: 	my $reply;
                   1629: 	if ($namespace eq 'ids') {
                   1630: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1631: 	} else {
                   1632: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1633: 	}
1.841     albertel 1634: 	my @answer=();
                   1635: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1636: 	    @answer=split(/\&/,$reply);
                   1637: 	}                    ;
                   1638: 	my $i;
                   1639: 	for ($i=0;$i<=$#ids;$i++) {
                   1640: 	    if ($answer[$i]) {
1.1299    raeburn  1641: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1642: 	    }
1.841     albertel 1643: 	}
1.1300    raeburn  1644:     }
1.70      www      1645:     return %returnhash;
                   1646: }
                   1647: 
                   1648: # ------------------------------------- Find the IDs behind a list of usernames
                   1649: 
                   1650: sub idrget {
                   1651:     my ($udom,@unames)=@_;
                   1652:     my %returnhash=();
1.800     albertel 1653:     foreach my $uname (@unames) {
                   1654:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1655:     }
1.70      www      1656:     return %returnhash;
                   1657: }
                   1658: 
1.1300    raeburn  1659: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      1660: 
                   1661: sub idput {
1.1300    raeburn  1662:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      1663:     my %servers=();
1.1300    raeburn  1664:     my %ids=();
                   1665:     my %byid = ();
                   1666:     if (ref($idsref) eq 'HASH') {
                   1667:         %ids=%{$idsref};
                   1668:     }
                   1669:     if ($namespace eq '') {
                   1670:         $namespace = 'ids'; 
                   1671:     }
1.800     albertel 1672:     foreach my $uname (keys(%ids)) {
                   1673: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  1674:         if ($uhom eq '') {
                   1675:             $uhom=&homeserver($uname,$udom);
                   1676:         }
1.70      www      1677:         if ($uhom ne 'no_host') {
1.800     albertel 1678:             my $esc_unam=&escape($uname);
1.1300    raeburn  1679:             if ($namespace eq 'ids') {
                   1680:                 my $id=&escape($ids{$uname});
                   1681:                 $id=~tr/A-Z/a-z/;
                   1682:                 my $esc_unam=&escape($uname);
                   1683:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      1684:             } else {
1.1300    raeburn  1685:                 my @currids = split(/,/,$ids{$uname});
                   1686:                 foreach my $id (@currids) {
                   1687:                     $byid{$uhom}{$id} .= $uname.',';
                   1688:                 }
                   1689:             }
                   1690:         }
                   1691:     }
                   1692:     if ($namespace eq 'clickers') {
                   1693:         foreach my $server (keys(%byid)) {
                   1694:             if (ref($byid{$server}) eq 'HASH') {
                   1695:                 foreach my $id (keys(%{$byid{$server}})) {
                   1696:                     $byid{$server} =~ s/,$//;
                   1697:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   1698:                 }
1.70      www      1699:             }
                   1700:         }
1.191     harris41 1701:     }
1.800     albertel 1702:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1703:         $servers{$server} =~ s/\&$//;
                   1704:         if ($namespace eq 'ids') {     
                   1705:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   1706:         } else {
                   1707:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   1708:         }
1.191     harris41 1709:     }
1.344     www      1710: }
                   1711: 
1.1300    raeburn  1712: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  1713: 
                   1714: sub iddel {
1.1300    raeburn  1715:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  1716:     my %result=();
1.1300    raeburn  1717:     my %ids=();
                   1718:     my %byid = ();
                   1719:     if (ref($idshashref) eq 'HASH') {
                   1720:         %ids=%{$idshashref};
                   1721:     } else {
1.1231    raeburn  1722:         return %result;
                   1723:     }
1.1300    raeburn  1724:     if ($namespace eq '') {
                   1725:         $namespace = 'ids';
                   1726:     }
1.1231    raeburn  1727:     my %servers=();
1.1300    raeburn  1728:     while (my ($id,$unamestr) = each(%ids)) {
                   1729:         if ($namespace eq 'ids') {
                   1730:             my $uhom = $uhome;
                   1731:             if ($uhom eq '') { 
                   1732:                 $uhom=&homeserver($unamestr,$udom);
                   1733:             }
                   1734:             if ($uhom ne 'no_host') {
                   1735:                 $servers{$uhom}.='&'.&escape($id);
                   1736:             }
                   1737:          } else {
                   1738:             my @curritems = split(/,/,$ids{$id});
                   1739:             foreach my $uname (@curritems) {
                   1740:                 my $uhom = $uhome;
                   1741:                 if ($uhom eq '') {
                   1742:                     $uhom=&homeserver($uname,$udom);
                   1743:                 }
                   1744:                 if ($uhom ne 'no_host') { 
                   1745:                     $byid{$uhom}{$id} .= $uname.',';
                   1746:                 }
                   1747:             }
1.1231    raeburn  1748:         }
1.1300    raeburn  1749:     }
                   1750:     if ($namespace eq 'clickers') {
                   1751:         foreach my $server (keys(%byid)) {
                   1752:             if (ref($byid{$server}) eq 'HASH') {
                   1753:                 foreach my $id (keys(%{$byid{$server}})) {
                   1754:                     $byid{$server}{$id} =~ s/,$//;
                   1755:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   1756:                 }
1.1231    raeburn  1757:             }
                   1758:         }
                   1759:     }
                   1760:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1761:         $servers{$server} =~ s/\&$//;
                   1762:         if ($namespace eq 'ids') {
                   1763:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1764:         } elsif ($namespace eq 'clickers') {
                   1765:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   1766:         }
1.1231    raeburn  1767:     }
                   1768:     return %result;
                   1769: }
                   1770: 
1.1300    raeburn  1771: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   1772: 
                   1773: sub updateclickers {
                   1774:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   1775:     my %clickers;
                   1776:     if (ref($idshashref) eq 'HASH') {
                   1777:         %clickers=%{$idshashref};
                   1778:     } else {
                   1779:         return;
                   1780:     }
                   1781:     my $items='';
                   1782:     foreach my $item (keys(%clickers)) {
                   1783:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   1784:     }
                   1785:     $items=~s/\&$//;
                   1786:     my $request = "updateclickers:$udom:$action:$items";
                   1787:     if ($critical) {
                   1788:         return &critical($request,$uhome);
                   1789:     } else {
                   1790:         return &reply($request,$uhome);
                   1791:     }
                   1792: }
                   1793: 
1.1023    raeburn  1794: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1795: sub dump_dom {
1.1165    droeschl 1796:     my ($namespace, $udom, $regexp) = @_;
                   1797: 
                   1798:     $udom ||= $env{'user.domain'};
                   1799: 
                   1800:     return () unless $udom;
                   1801: 
                   1802:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1803: }
                   1804: 
1.1023    raeburn  1805: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1806: 
                   1807: sub get_dom {
1.860     raeburn  1808:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  1809:     return if ($udom eq 'public');
1.806     raeburn  1810:     my $items='';
                   1811:     foreach my $item (@$storearr) {
                   1812:         $items.=&escape($item).'&';
                   1813:     }
                   1814:     $items=~s/\&$//;
1.860     raeburn  1815:     if (!$udom) {
                   1816:         $udom=$env{'user.domain'};
1.1267    raeburn  1817:         return if ($udom eq 'public');
1.860     raeburn  1818:         if (defined(&domain($udom,'primary'))) {
                   1819:             $uhome=&domain($udom,'primary');
                   1820:         } else {
1.874     albertel 1821:             undef($uhome);
1.860     raeburn  1822:         }
                   1823:     } else {
                   1824:         if (!$uhome) {
                   1825:             if (defined(&domain($udom,'primary'))) {
                   1826:                 $uhome=&domain($udom,'primary');
                   1827:             }
                   1828:         }
                   1829:     }
                   1830:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1831:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1832:         my %returnhash;
1.875     albertel 1833:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1834:             return %returnhash;
                   1835:         }
1.806     raeburn  1836:         my @pairs=split(/\&/,$rep);
                   1837:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1838:             return @pairs;
                   1839:         }
                   1840:         my $i=0;
                   1841:         foreach my $item (@$storearr) {
                   1842:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1843:             $i++;
                   1844:         }
                   1845:         return %returnhash;
                   1846:     } else {
1.880     banghart 1847:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1848:     }
                   1849: }
                   1850: 
                   1851: # -------------------------------------------- put items in domain db files 
                   1852: 
                   1853: sub put_dom {
1.860     raeburn  1854:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1855:     if (!$udom) {
                   1856:         $udom=$env{'user.domain'};
                   1857:         if (defined(&domain($udom,'primary'))) {
                   1858:             $uhome=&domain($udom,'primary');
                   1859:         } else {
1.874     albertel 1860:             undef($uhome);
1.860     raeburn  1861:         }
                   1862:     } else {
                   1863:         if (!$uhome) {
                   1864:             if (defined(&domain($udom,'primary'))) {
                   1865:                 $uhome=&domain($udom,'primary');
                   1866:             }
                   1867:         }
                   1868:     } 
                   1869:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1870:         my $items='';
                   1871:         foreach my $item (keys(%$storehash)) {
                   1872:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1873:         }
                   1874:         $items=~s/\&$//;
                   1875:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1876:     } else {
1.860     raeburn  1877:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1878:     }
                   1879: }
                   1880: 
1.1023    raeburn  1881: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1882: sub newput_dom {
1.1023    raeburn  1883:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1884:     my $result;
                   1885:     if (!$udom) {
                   1886:         $udom=$env{'user.domain'};
                   1887:     }
1.1023    raeburn  1888:     if ($udom) {
                   1889:         my $uname = &get_domainconfiguser($udom);
                   1890:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1891:     }
                   1892:     return $result;
                   1893: }
                   1894: 
1.1023    raeburn  1895: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1896: sub del_dom {
1.1023    raeburn  1897:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1898:     if (ref($storearr) eq 'ARRAY') {
                   1899:         if (!$udom) {
                   1900:             $udom=$env{'user.domain'};
                   1901:         }
1.1023    raeburn  1902:         if ($udom) {
                   1903:             my $uname = &get_domainconfiguser($udom); 
                   1904:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1905:         }
                   1906:     }
                   1907: }
                   1908: 
1.1023    raeburn  1909: # ----------------------------------construct domainconfig user for a domain 
                   1910: sub get_domainconfiguser {
                   1911:     my ($udom) = @_;
                   1912:     return $udom.'-domainconfig';
                   1913: }
                   1914: 
1.837     raeburn  1915: sub retrieve_inst_usertypes {
                   1916:     my ($udom) = @_;
                   1917:     my (%returnhash,@order);
1.989     raeburn  1918:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1919:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1920:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  1921:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1922:     } else {
                   1923:         if (defined(&domain($udom,'primary'))) {
                   1924:             my $uhome=&domain($udom,'primary');
                   1925:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1926:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  1927:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1928:                 return (\%returnhash,\@order);
                   1929:             }
                   1930:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1931:             my @pairs=split(/\&/,$hashitems);
                   1932:             foreach my $item (@pairs) {
                   1933:                 my ($key,$value)=split(/=/,$item,2);
                   1934:                 $key = &unescape($key);
                   1935:                 next if ($key =~ /^error: 2 /);
                   1936:                 $returnhash{$key}=&thaw_unescape($value);
                   1937:             }
                   1938:             my @esc_order = split(/\&/,$orderitems);
                   1939:             foreach my $item (@esc_order) {
                   1940:                 push(@order,&unescape($item));
                   1941:             }
                   1942:         } else {
1.1256    raeburn  1943:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1944:         }
1.1256    raeburn  1945:         return (\%returnhash,\@order);
1.837     raeburn  1946:     }
                   1947: }
                   1948: 
1.868     raeburn  1949: sub is_domainimage {
                   1950:     my ($url) = @_;
1.1306    raeburn  1951:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  1952:         if (&domain($1) ne '') {
                   1953:             return '1';
                   1954:         }
                   1955:     }
                   1956:     return;
                   1957: }
                   1958: 
1.899     raeburn  1959: sub inst_directory_query {
                   1960:     my ($srch) = @_;
                   1961:     my $udom = $srch->{'srchdomain'};
                   1962:     my %results;
                   1963:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1964:     my $outcome;
1.899     raeburn  1965:     if ($homeserver ne '') {
1.904     albertel 1966: 	my $queryid=&reply("querysend:instdirsearch:".
                   1967: 			   &escape($srch->{'srchby'}).':'.
                   1968: 			   &escape($srch->{'srchterm'}).':'.
                   1969: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1970: 	my $host=&hostname($homeserver);
                   1971: 	if ($queryid !~/^\Q$host\E\_/) {
                   1972: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1973: 	    return;
                   1974: 	}
                   1975: 	my $response = &get_query_reply($queryid);
                   1976: 	my $maxtries = 5;
                   1977: 	my $tries = 1;
                   1978: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1979: 	    $response = &get_query_reply($queryid);
                   1980: 	    $tries ++;
                   1981: 	}
                   1982: 
                   1983:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1984:             if ($response eq 'unavailable') {
                   1985:                 $outcome = $response;
                   1986:             } else {
                   1987:                 $outcome = 'ok';
                   1988:                 my @matches = split(/\n/,$response);
                   1989:                 foreach my $match (@matches) {
                   1990:                     my ($key,$value) = split(/=/,$match);
                   1991:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1992:                 }
1.899     raeburn  1993:             }
                   1994:         }
                   1995:     }
1.909     raeburn  1996:     return ($outcome,%results);
1.899     raeburn  1997: }
                   1998: 
                   1999: sub usersearch {
                   2000:     my ($srch) = @_;
                   2001:     my $dom = $srch->{'srchdomain'};
                   2002:     my %results;
                   2003:     my %libserv = &all_library();
                   2004:     my $query = 'usersearch';
                   2005:     foreach my $tryserver (keys(%libserv)) {
                   2006:         if (&host_domain($tryserver) eq $dom) {
                   2007:             my $host=&hostname($tryserver);
                   2008:             my $queryid=
1.911     raeburn  2009:                 &reply("querysend:".&escape($query).':'.
                   2010:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2011:                        &escape($srch->{'srchtype'}).':'.
                   2012:                        &escape($srch->{'srchterm'}),$tryserver);
                   2013:             if ($queryid !~/^\Q$host\E\_/) {
                   2014:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2015:                 next;
1.899     raeburn  2016:             }
                   2017:             my $reply = &get_query_reply($queryid);
                   2018:             my $maxtries = 1;
                   2019:             my $tries = 1;
                   2020:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2021:                 $reply = &get_query_reply($queryid);
                   2022:                 $tries ++;
                   2023:             }
                   2024:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2025:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2026:             } else {
1.911     raeburn  2027:                 my @matches;
                   2028:                 if ($reply =~ /\n/) {
                   2029:                     @matches = split(/\n/,$reply);
                   2030:                 } else {
                   2031:                     @matches = split(/\&/,$reply);
                   2032:                 }
1.899     raeburn  2033:                 foreach my $match (@matches) {
                   2034:                     my ($uname,$udom,%userhash);
1.911     raeburn  2035:                     foreach my $entry (split(/:/,$match)) {
                   2036:                         my ($key,$value) =
                   2037:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2038:                         $userhash{$key} = $value;
                   2039:                         if ($key eq 'username') {
                   2040:                             $uname = $value;
                   2041:                         } elsif ($key eq 'domain') {
                   2042:                             $udom = $value;
1.911     raeburn  2043:                         }
1.899     raeburn  2044:                     }
                   2045:                     $results{$uname.':'.$udom} = \%userhash;
                   2046:                 }
                   2047:             }
                   2048:         }
                   2049:     }
                   2050:     return %results;
                   2051: }
                   2052: 
1.912     raeburn  2053: sub get_instuser {
                   2054:     my ($udom,$uname,$id) = @_;
                   2055:     my $homeserver = &domain($udom,'primary');
                   2056:     my ($outcome,%results);
                   2057:     if ($homeserver ne '') {
                   2058:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2059:                            &escape($id).':'.&escape($udom),$homeserver);
                   2060:         my $host=&hostname($homeserver);
                   2061:         if ($queryid !~/^\Q$host\E\_/) {
                   2062:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2063:             return;
                   2064:         }
                   2065:         my $response = &get_query_reply($queryid);
                   2066:         my $maxtries = 5;
                   2067:         my $tries = 1;
                   2068:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2069:             $response = &get_query_reply($queryid);
                   2070:             $tries ++;
                   2071:         }
                   2072:         if (!&error($response) && $response ne 'refused') {
                   2073:             if ($response eq 'unavailable') {
                   2074:                 $outcome = $response;
                   2075:             } else {
                   2076:                 $outcome = 'ok';
                   2077:                 my @matches = split(/\n/,$response);
                   2078:                 foreach my $match (@matches) {
                   2079:                     my ($key,$value) = split(/=/,$match);
                   2080:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2081:                 }
                   2082:             }
                   2083:         }
                   2084:     }
                   2085:     my %userinfo;
                   2086:     if (ref($results{$uname}) eq 'HASH') {
                   2087:         %userinfo = %{$results{$uname}};
                   2088:     } 
                   2089:     return ($outcome,%userinfo);
                   2090: }
                   2091: 
1.1290    raeburn  2092: sub get_multiple_instusers {
                   2093:     my ($udom,$users,$caller) = @_;
                   2094:     my ($outcome,$results);
                   2095:     if (ref($users) eq 'HASH') {
                   2096:         my $count = keys(%{$users}); 
                   2097:         my $requested = &freeze_escape($users);
                   2098:         my $homeserver = &domain($udom,'primary');
                   2099:         if ($homeserver ne '') {
                   2100:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2101:             my $host=&hostname($homeserver);
                   2102:             if ($queryid !~/^\Q$host\E\_/) {
                   2103:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2104:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2105:                 return ($outcome,$results);
                   2106:             }
                   2107:             my $response = &get_query_reply($queryid);
                   2108:             my $maxtries = 5;
                   2109:             if ($count > 100) {
                   2110:                 $maxtries = 1+int($count/20);
                   2111:             }
                   2112:             my $tries = 1;
                   2113:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2114:                 $response = &get_query_reply($queryid);
                   2115:                 $tries ++;
                   2116:             }
                   2117:             if ($response eq '') {
                   2118:                 $results = {};
                   2119:                 foreach my $key (keys(%{$users})) {
                   2120:                     my ($uname,$id);
                   2121:                     if ($caller eq 'id') {
                   2122:                         $id = $key;
                   2123:                     } else {
                   2124:                         $uname = $key;
                   2125:                     }
                   2126:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2127:                     $outcome = $resp;
1.1290    raeburn  2128:                     if ($resp eq 'ok') {
                   2129:                         %{$results} = (%{$results}, %info);
                   2130:                     } else {
                   2131:                         last;
                   2132:                     }
                   2133:                 }
                   2134:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2135:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2136:                     $outcome = $response;
                   2137:                 } else {
1.1291    raeburn  2138:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2139:                     if ($outcome eq 'ok') {
                   2140:                         $results = &thaw_unescape($userdata); 
                   2141:                     }
                   2142:                 }
                   2143:             }
                   2144:         }
                   2145:     }
                   2146:     return ($outcome,$results);
                   2147: }
                   2148: 
1.912     raeburn  2149: sub inst_rulecheck {
1.923     raeburn  2150:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2151:     my %returnhash;
                   2152:     if ($udom ne '') {
                   2153:         if (ref($rules) eq 'ARRAY') {
                   2154:             @{$rules} = map {&escape($_);} (@{$rules});
                   2155:             my $rulestr = join(':',@{$rules});
                   2156:             my $homeserver=&domain($udom,'primary');
                   2157:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2158:                 my $response;
                   2159:                 if ($item eq 'username') {                
                   2160:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2161:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2162:                                               $homeserver));
1.923     raeburn  2163:                 } elsif ($item eq 'id') {
                   2164:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2165:                                               ':'.&escape($id).':'.$rulestr,
                   2166:                                               $homeserver));
1.945     raeburn  2167:                 } elsif ($item eq 'selfcreate') {
                   2168:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2169:                                                &escape($udom).':'.&escape($uname).
                   2170:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2171:                 }
1.912     raeburn  2172:                 if ($response ne 'refused') {
                   2173:                     my @pairs=split(/\&/,$response);
                   2174:                     foreach my $item (@pairs) {
                   2175:                         my ($key,$value)=split(/=/,$item,2);
                   2176:                         $key = &unescape($key);
                   2177:                         next if ($key =~ /^error: 2 /);
                   2178:                         $returnhash{$key}=&thaw_unescape($value);
                   2179:                     }
                   2180:                 }
                   2181:             }
                   2182:         }
                   2183:     }
                   2184:     return %returnhash;
                   2185: }
                   2186: 
                   2187: sub inst_userrules {
1.923     raeburn  2188:     my ($udom,$check) = @_;
1.912     raeburn  2189:     my (%ruleshash,@ruleorder);
                   2190:     if ($udom ne '') {
                   2191:         my $homeserver=&domain($udom,'primary');
                   2192:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2193:             my $response;
                   2194:             if ($check eq 'id') {
                   2195:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2196:                                  $homeserver);
1.943     raeburn  2197:             } elsif ($check eq 'email') {
                   2198:                 $response=&reply('instemailrules:'.&escape($udom),
                   2199:                                  $homeserver);
1.923     raeburn  2200:             } else {
                   2201:                 $response=&reply('instuserrules:'.&escape($udom),
                   2202:                                  $homeserver);
                   2203:             }
1.912     raeburn  2204:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2205:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2206:                 ($response ne 'no_such_host')) {
                   2207:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2208:                 my @pairs=split(/\&/,$hashitems);
                   2209:                 foreach my $item (@pairs) {
                   2210:                     my ($key,$value)=split(/=/,$item,2);
                   2211:                     $key = &unescape($key);
                   2212:                     next if ($key =~ /^error: 2 /);
                   2213:                     $ruleshash{$key}=&thaw_unescape($value);
                   2214:                 }
                   2215:                 my @esc_order = split(/\&/,$orderitems);
                   2216:                 foreach my $item (@esc_order) {
                   2217:                     push(@ruleorder,&unescape($item));
                   2218:                 }
                   2219:             }
                   2220:         }
                   2221:     }
                   2222:     return (\%ruleshash,\@ruleorder);
                   2223: }
                   2224: 
1.976     raeburn  2225: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2226: 
                   2227: sub get_domain_defaults {
1.1240    raeburn  2228:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2229:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2230:     my $cachetime = 60*60*24;
1.1240    raeburn  2231:     unless ($ignore_cache) {
                   2232:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2233:         if (defined($cached)) {
                   2234:             if (ref($result) eq 'HASH') {
                   2235:                 return %{$result};
                   2236:             }
1.943     raeburn  2237:         }
                   2238:     }
                   2239:     my %domdefaults;
                   2240:     my %domconfig =
1.989     raeburn  2241:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2242:                                   'requestcourses','inststatus',
1.1183    raeburn  2243:                                   'coursedefaults','usersessions',
1.1258    raeburn  2244:                                   'requestauthor','selfenrollment',
1.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.1319  ! damieng  2638:     my $remembered_id=$name.':'.$id;
1.849     albertel 2639:     $id=&make_key($name,$id);
1.599     albertel 2640:     $memcache->delete($id);
1.1319  ! damieng  2641:     delete($remembered{$remembered_id});
        !          2642:     delete($accessed{$remembered_id});
1.599     albertel 2643: }
                   2644: 
                   2645: sub is_cached_new {
                   2646:     my ($name,$id,$debug) = @_;
1.1319  ! damieng  2647:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
        !          2648:     if (exists($remembered{$remembered_id})) {
        !          2649: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
        !          2650: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2651: 	$hits++;
1.1319  ! damieng  2652: 	return ($remembered{$remembered_id},1);
1.599     albertel 2653:     }
1.1319  ! damieng  2654:     $id=&make_key($name,$id);
1.599     albertel 2655:     my $value = $memcache->get($id);
                   2656:     if (!(defined($value))) {
                   2657: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2658: 	return (undef,undef);
1.416     albertel 2659:     }
1.599     albertel 2660:     if ($value eq '__undef__') {
                   2661: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2662: 	$value=undef;
                   2663:     }
1.1319  ! damieng  2664:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2665:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2666:     return ($value,1);
                   2667: }
                   2668: 
                   2669: sub do_cache_new {
                   2670:     my ($name,$id,$value,$time,$debug) = @_;
1.1319  ! damieng  2671:     my $remembered_id=$name.':'.$id;
1.849     albertel 2672:     $id=&make_key($name,$id);
1.599     albertel 2673:     my $setvalue=$value;
                   2674:     if (!defined($setvalue)) {
                   2675: 	$setvalue='__undef__';
                   2676:     }
1.623     albertel 2677:     if (!defined($time) ) {
                   2678: 	$time=600;
                   2679:     }
1.599     albertel 2680:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2681:     my $result = $memcache->set($id,$setvalue,$time);
                   2682:     if (! $result) {
1.872     albertel 2683: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2684: 	$memcache->disconnect_all();
1.872     albertel 2685:     }
1.600     albertel 2686:     # need to make a copy of $value
1.1319  ! damieng  2687:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2688:     return $value;
                   2689: }
                   2690: 
                   2691: sub make_room {
1.1319  ! damieng  2692:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2693: 
1.1319  ! damieng  2694:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2695:                                     : $value;
1.599     albertel 2696:     if ($to_remember<0) { return; }
1.1319  ! damieng  2697:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2698:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2699:     my $to_kick;
                   2700:     my $max_time=0;
                   2701:     foreach my $other (keys(%accessed)) {
                   2702: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2703: 	    $to_kick=$other;
                   2704: 	    $max_time=&tv_interval($accessed{$other});
                   2705: 	}
                   2706:     }
                   2707:     delete($remembered{$to_kick});
                   2708:     delete($accessed{$to_kick});
                   2709:     $kicks++;
                   2710:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2711:     return;
                   2712: }
                   2713: 
1.599     albertel 2714: sub purge_remembered {
1.604     albertel 2715:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2716:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2717:     undef(%remembered);
                   2718:     undef(%accessed);
1.428     albertel 2719: }
1.70      www      2720: # ------------------------------------- Read an entry from a user's environment
                   2721: 
                   2722: sub userenvironment {
                   2723:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2724:     my $items;
                   2725:     foreach my $item (@what) {
                   2726:         $items.=&escape($item).'&';
                   2727:     }
                   2728:     $items=~s/\&$//;
1.70      www      2729:     my %returnhash=();
1.1009    raeburn  2730:     my $uhome = &homeserver($unam,$udom);
                   2731:     unless ($uhome eq 'no_host') {
                   2732:         my @answer=split(/\&/, 
                   2733:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2734:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2735:             return %returnhash;
                   2736:         }
1.1009    raeburn  2737:         my $i;
                   2738:         for ($i=0;$i<=$#what;$i++) {
                   2739: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2740:         }
1.70      www      2741:     }
                   2742:     return %returnhash;
1.1       albertel 2743: }
                   2744: 
1.617     albertel 2745: # ---------------------------------------------------------- Get a studentphoto
                   2746: sub studentphoto {
                   2747:     my ($udom,$unam,$ext) = @_;
                   2748:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2749:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2750:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2751:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2752:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2753:             } else {
                   2754:                 my ($result,$perm_reqd)=
1.707     albertel 2755: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2756:                 if ($result eq 'ok') {
                   2757:                     if (!($perm_reqd eq 'yes')) {
                   2758:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2759:                     }
                   2760:                 }
                   2761:             }
                   2762:         }
                   2763:     } else {
                   2764:         my ($result,$perm_reqd) = 
1.707     albertel 2765: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2766:         if ($result eq 'ok') {
                   2767:             if (!($perm_reqd eq 'yes')) {
                   2768:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2769:             }
                   2770:         }
                   2771:     }
                   2772:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2773: }
                   2774: 
                   2775: sub retrievestudentphoto {
                   2776:     my ($udom,$unam,$ext,$type) = @_;
                   2777:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2778:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2779:     if ($ret eq 'ok') {
                   2780:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2781:         if ($type eq 'thumbnail') {
                   2782:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2783:         }
                   2784:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2785:         return $tokenurl;
                   2786:     } else {
                   2787:         if ($type eq 'thumbnail') {
                   2788:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2789:         } else { 
                   2790:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2791:         }
1.617     albertel 2792:     }
                   2793: }
                   2794: 
1.263     www      2795: # -------------------------------------------------------------------- New chat
                   2796: 
                   2797: sub chatsend {
1.724     raeburn  2798:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2799:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2800:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2801:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2802:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2803: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2804: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2805: }
                   2806: 
                   2807: # ------------------------------------------ Find current version of a resource
                   2808: 
                   2809: sub getversion {
                   2810:     my $fname=&clutter(shift);
1.1189    raeburn  2811:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2812:     return &currentversion(&filelocation('',$fname));
                   2813: }
                   2814: 
                   2815: sub currentversion {
                   2816:     my $fname=shift;
                   2817:     my $author=$fname;
                   2818:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2819:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2820:     my $home=&homeserver($uname,$udom);
1.292     www      2821:     if ($home eq 'no_host') { 
                   2822:         return -1; 
                   2823:     }
1.1112    www      2824:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2825:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2826: 	return -1;
                   2827:     }
1.1112    www      2828:     return $answer;
1.263     www      2829: }
                   2830: 
1.1111    www      2831: #
                   2832: # Return special version number of resource if set by override, empty otherwise
                   2833: #
                   2834: sub usedversion {
                   2835:     my $fname=shift;
                   2836:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2837:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2838:     if ($urlversion) { return $urlversion; }
                   2839:     return '';
                   2840: }
                   2841: 
1.1       albertel 2842: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2843: 
1.1       albertel 2844: sub subscribe {
                   2845:     my $fname=shift;
1.761     raeburn  2846:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2847:     $fname=~s/[\n\r]//g;
1.1       albertel 2848:     my $author=$fname;
                   2849:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2850:     my ($udom,$uname)=split(/\//,$author);
                   2851:     my $home=homeserver($uname,$udom);
1.335     albertel 2852:     if ($home eq 'no_host') {
                   2853:         return 'not_found';
1.1       albertel 2854:     }
                   2855:     my $answer=reply("sub:$fname",$home);
1.64      www      2856:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2857: 	$answer.=' by '.$home;
                   2858:     }
1.1       albertel 2859:     return $answer;
                   2860: }
                   2861:     
1.8       www      2862: # -------------------------------------------------------------- Replicate file
                   2863: 
                   2864: sub repcopy {
                   2865:     my $filename=shift;
1.23      www      2866:     $filename=~s/\/+/\//g;
1.1142    raeburn  2867:     my $londocroot = $perlvar{'lonDocRoot'};
                   2868:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2869:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2870:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2871: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2872: 	return &repcopy_userfile($filename);
                   2873:     }
1.532     albertel 2874:     $filename=~s/[\n\r]//g;
1.8       www      2875:     my $transname="$filename.in.transfer";
1.828     www      2876: # FIXME: this should flock
1.607     raeburn  2877:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2878:     my $remoteurl=subscribe($filename);
1.64      www      2879:     if ($remoteurl =~ /^con_lost by/) {
                   2880: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2881:            return 'unavailable';
1.8       www      2882:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2883: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2884: 	   return 'not_found';
1.64      www      2885:     } elsif ($remoteurl =~ /^rejected by/) {
                   2886: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2887:            return 'forbidden';
1.20      www      2888:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2889:            return 'ok';
1.8       www      2890:     } else {
1.290     www      2891:         my $author=$filename;
                   2892:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2893:         my ($udom,$uname)=split(/\//,$author);
                   2894:         my $home=homeserver($uname,$udom);
                   2895:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2896:            my @parts=split(/\//,$filename);
                   2897:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2898:            if ($path ne "$londocroot/res") {
1.8       www      2899:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2900: 	       return 'bad_request';
1.8       www      2901:            }
                   2902:            my $count;
                   2903:            for ($count=5;$count<$#parts;$count++) {
                   2904:                $path.="/$parts[$count]";
                   2905:                if ((-e $path)!=1) {
                   2906: 		   mkdir($path,0777);
                   2907:                }
                   2908:            }
                   2909:            my $ua=new LWP::UserAgent;
                   2910:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2911:            my $response=$ua->request($request,$transname);
                   2912:            if ($response->is_error()) {
                   2913: 	       unlink($transname);
                   2914:                my $message=$response->status_line;
1.672     albertel 2915:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2916:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2917:                return 'unavailable';
1.8       www      2918:            } else {
1.16      www      2919: 	       if ($remoteurl!~/\.meta$/) {
                   2920:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2921:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2922:                   if ($mresponse->is_error()) {
                   2923: 		      unlink($filename.'.meta');
                   2924:                       &logthis(
1.672     albertel 2925:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2926:                   }
                   2927: 	       }
1.8       www      2928:                rename($transname,$filename);
1.607     raeburn  2929:                return 'ok';
1.8       www      2930:            }
1.290     www      2931:        }
1.8       www      2932:     }
1.330     www      2933: }
                   2934: 
                   2935: # ------------------------------------------------ Get server side include body
                   2936: sub ssi_body {
1.381     albertel 2937:     my ($filelink,%form)=@_;
1.606     matthew  2938:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2939:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2940:     }
1.953     www      2941:     my $output='';
                   2942:     my $response;
1.980     raeburn  2943:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2944:        ($output,$response)=&externalssi($filelink);
1.953     www      2945:     } else {
1.1004    droeschl 2946:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2947:        $filelink .= 'inhibitmenu=yes';
1.953     www      2948:        ($output,$response)=&ssi($filelink,%form);
                   2949:     }
1.778     albertel 2950:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2951:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2952:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2953:     if (wantarray) {
                   2954:         return ($output, $response);
                   2955:     } else {
                   2956:         return $output;
                   2957:     }
1.8       www      2958: }
                   2959: 
1.15      www      2960: # --------------------------------------------------------- Server Side Include
                   2961: 
1.782     albertel 2962: sub absolute_url {
                   2963:     my ($host_name) = @_;
                   2964:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2965:     if ($host_name eq '') {
                   2966: 	$host_name = $ENV{'SERVER_NAME'};
                   2967:     }
                   2968:     return $protocol.$host_name;
                   2969: }
                   2970: 
1.942     foxr     2971: #
                   2972: #   Server side include.
                   2973: # Parameters:
                   2974: #  fn     Possibly encrypted resource name/id.
                   2975: #  form   Hash that describes how the rendering should be done
                   2976: #         and other things.
1.944     foxr     2977: # Returns:
1.950     raeburn  2978: #   Scalar context: The content of the response.
                   2979: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2980: #     
1.15      www      2981: sub ssi {
                   2982: 
1.944     foxr     2983:     my ($fn,%form)=@_;
1.15      www      2984:     my $ua=new LWP::UserAgent;
1.23      www      2985:     my $request;
1.711     albertel 2986: 
                   2987:     $form{'no_update_last_known'}=1;
1.895     albertel 2988:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2989:     if (%form) {
1.782     albertel 2990:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 2991:       $request->content(join('&',map { 
                   2992:             my $name = escape($_);
                   2993:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   2994:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   2995:             : &escape($form{$_}) );    
                   2996:         } keys(%form)));
1.23      www      2997:     } else {
1.782     albertel 2998:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2999:     }
                   3000: 
1.15      www      3001:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173    foxr     3002:     my $response= $ua->request($request);
1.1182    foxr     3003:     my $content = $response->content;
                   3004: 
                   3005: 
1.944     foxr     3006:     if (wantarray) {
1.1173    foxr     3007: 	return ($content, $response);
1.944     foxr     3008:     } else {
1.1173    foxr     3009: 	return $content;
1.942     foxr     3010:     }
1.324     www      3011: }
                   3012: 
                   3013: sub externalssi {
                   3014:     my ($url)=@_;
                   3015:     my $ua=new LWP::UserAgent;
                   3016:     my $request=new HTTP::Request('GET',$url);
                   3017:     my $response=$ua->request($request);
1.954     raeburn  3018:     if (wantarray) {
                   3019:         return ($response->content, $response);
                   3020:     } else {
                   3021:         return $response->content;
                   3022:     }
1.15      www      3023: }
1.254     www      3024: 
1.492     albertel 3025: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3026: 
                   3027: sub allowuploaded {
                   3028:     my ($srcurl,$url)=@_;
                   3029:     $url=&clutter(&declutter($url));
                   3030:     my $dir=$url;
                   3031:     $dir=~s/\/[^\/]+$//;
                   3032:     my %httpref=();
                   3033:     my $httpurl=&hreflocation('',$url);
                   3034:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3035:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3036: }
1.477     raeburn  3037: 
1.1193    raeburn  3038: #
                   3039: # Determine if the current user should be able to edit a particular resource,
                   3040: # when viewing in course context.
                   3041: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3042: #     Functions.
                   3043: # (b) When displaying folder contents in course editor, used to determine if
                   3044: #     "Edit" link will be displayed alongside resource.
                   3045: #
1.1196    raeburn  3046: #  input: six args -- filename (decluttered), course number, course domain,
                   3047: #                   url, symb (if registered) and group (if this is a group
                   3048: #                   item -- e.g., bulletin board, group page etc.).
                   3049: #  output: array of five scalars -- 
1.1193    raeburn  3050: #          $cfile -- url for file editing if editable on current server
                   3051: #          $home -- homeserver of resource (i.e., for author if published,
                   3052: #                                           or course if uploaded.).
                   3053: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3054: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3055: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3056: #
                   3057: 
                   3058: sub can_edit_resource {
1.1194    raeburn  3059:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3060:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3061: #
                   3062: # For aboutme pages user can only edit his/her own.
                   3063: #
1.1199    raeburn  3064:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3065:         my ($sdom,$sname) = ($1,$2);
                   3066:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3067:             $home = $env{'user.home'};
                   3068:             $cfile = $resurl;
                   3069:             if ($env{'form.forceedit'}) {
                   3070:                 $forceview = 1;
                   3071:             } else {
                   3072:                 $forceedit = 1;
                   3073:             }
                   3074:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3075:         } else {
                   3076:             return;
                   3077:         }
                   3078:     }
                   3079: 
                   3080:     if ($env{'request.course.id'}) {
                   3081:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3082:         if ($group ne '') {
                   3083: # if this is a group homepage or group bulletin board, check group privs
                   3084:             my $allowed = 0;
1.1197    raeburn  3085:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3086:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3087:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3088:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3089:                     $allowed = 1;
                   3090:                 }
1.1197    raeburn  3091:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3092:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3093:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3094:                     $allowed = 1;
                   3095:                 }
                   3096:             }
                   3097:             if ($allowed) {
                   3098:                 $home=&homeserver($cnum,$cdom);
                   3099:                 if ($env{'form.forceedit'}) {
                   3100:                     $forceview = 1;
                   3101:                 } else {
                   3102:                     $forceedit = 1;
                   3103:                 }
                   3104:                 $cfile = $resurl;
                   3105:             } else {
                   3106:                 return;
                   3107:             }
                   3108:         } else {
1.1208    raeburn  3109:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3110:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3111:                     return;
                   3112:                 }
                   3113:             } elsif (!$crsedit) {
1.1194    raeburn  3114: #
                   3115: # No edit allowed where CC has switched to student role.
                   3116: #
                   3117:                 return;
                   3118:             }
                   3119:         }
                   3120:     }
                   3121: 
1.1193    raeburn  3122:     if ($file ne '') {
                   3123:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3124:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3125:                 $uploaded = 1;
                   3126:                 $incourse = 1;
1.1193    raeburn  3127:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3128:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3129:                     if ($env{'form.forceedit'}) {
                   3130:                         $forceview = 1;
                   3131:                     } else {
                   3132:                         $forceedit = 1;
                   3133:                     }
1.1194    raeburn  3134:                 }
                   3135:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3136:                 $incourse = 1;
                   3137:                 if ($env{'form.forceedit'}) {
                   3138:                     $forceview = 1;
                   3139:                 } else {
                   3140:                     $forceedit = 1;
                   3141:                 }
                   3142:                 $cfile = $resurl;
                   3143:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3144:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3145:                     $incourse = 1;
                   3146:                     if ($env{'form.forceedit'}) {
                   3147:                         $forceview = 1;
                   3148:                     } else {
                   3149:                         $forceedit = 1;
                   3150:                     }
                   3151:                     $cfile = $resurl;
1.1199    raeburn  3152:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3153:                     $incourse = 1;
                   3154:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3155:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3156:                     $incourse = 1;
1.1199    raeburn  3157:                     if ($env{'form.forceedit'}) {
                   3158:                         $forceview = 1;
                   3159:                     } else {
                   3160:                         $forceedit = 1;
                   3161:                     }
                   3162:                     $cfile = $resurl;
1.1298    raeburn  3163:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) {
                   3164:                     $incourse = 1;
                   3165:                     if ($env{'form.forceedit'}) {
                   3166:                         $forceview = 1;
                   3167:                     } else {
                   3168:                         $forceedit = 1;
                   3169:                     }
                   3170:                     $cfile = $resurl;
1.1208    raeburn  3171:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3172:                     $incourse = 1;
                   3173:                     if ($env{'form.forceedit'}) {
                   3174:                         $forceview = 1;
                   3175:                     } else {
                   3176:                         $forceedit = 1;
                   3177:                     }
                   3178:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3179:                 }
                   3180:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3181:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3182:                 if (&is_on_map($template)) { 
                   3183:                     $incourse = 1;
                   3184:                     $forceview = 1;
                   3185:                     $cfile = $template;
1.1193    raeburn  3186:                 }
1.1199    raeburn  3187:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3188:                     $incourse = 1;
                   3189:                     if ($env{'form.forceedit'}) {
                   3190:                         $forceview = 1;
                   3191:                     } else {
                   3192:                         $forceedit = 1;
                   3193:                     }
                   3194:                     $cfile = $resurl;
1.1298    raeburn  3195:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3196:                 $incourse = 1;
                   3197:                 if ($env{'form.forceedit'}) {
                   3198:                     $forceview = 1;
                   3199:                 } else {
                   3200:                     $forceedit = 1;
                   3201:                 }
                   3202:                 $cfile = $resurl;
1.1199    raeburn  3203:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3204:                 $incourse = 1;
                   3205:                 $forceview = 1;
                   3206:                 if ($symb) {
                   3207:                     my ($map,$id,$res)=&decode_symb($symb);
                   3208:                     $env{'request.symb'} = $symb;
                   3209:                     $cfile = &clutter($res);
                   3210:                 } else {
                   3211:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3212:                     my $escfile = &unescape($cfile);
                   3213:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/exttools?$}) {
                   3214:                         $cfile = '/adm/wrapper'.$escfile;
                   3215:                     } else {
                   3216:                         $escfile =~ s{^http://}{};
                   3217:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3218:                     }
1.1199    raeburn  3219:                 }
1.1234    raeburn  3220:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3221:                 if ($env{'form.forceedit'}) {
                   3222:                     $forceview = 1;
                   3223:                 } else {
                   3224:                     $forceedit = 1;
                   3225:                 }
                   3226:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3227:             }
                   3228:         }
1.1194    raeburn  3229:         if ($uploaded || $incourse) {
                   3230:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3231:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3232:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3233:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3234:             # Check that the user has permission to edit this resource
                   3235:             my $setpriv = 1;
                   3236:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3237:             if (defined($cfudom)) {
                   3238:                 $home=&homeserver($cfuname,$cfudom);
                   3239:                 $cfile=$file;
                   3240:             }
                   3241:         }
1.1194    raeburn  3242:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3243:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3244:             my @ids=&current_machine_ids();
                   3245:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3246:                 $switchserver=1;
                   3247:             }
                   3248:         }
                   3249:     }
1.1194    raeburn  3250:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3251: }
                   3252: 
                   3253: sub is_course_upload {
                   3254:     my ($file,$cnum,$cdom) = @_;
                   3255:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3256:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3257:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3258:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3259:         return 1;
                   3260:     }
                   3261:     return;
                   3262: }
                   3263: 
1.1194    raeburn  3264: sub in_course {
1.1195    raeburn  3265:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3266:     if ($hideprivileged) {
                   3267:         my $skipuser;
1.1219    raeburn  3268:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3269:         my @possdoms = ($cdom);  
                   3270:         if ($coursehash{'checkforpriv'}) { 
                   3271:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3272:         }
                   3273:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3274:             $skipuser = 1;
                   3275:             if ($coursehash{'nothideprivileged'}) {
                   3276:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3277:                     my $user;
                   3278:                     if ($item =~ /:/) {
                   3279:                         $user = $item;
                   3280:                     } else {
                   3281:                         $user = join(':',split(/[\@]/,$item));
                   3282:                     }
                   3283:                     if ($user eq $uname.':'.$udom) {
                   3284:                         undef($skipuser);
                   3285:                         last;
                   3286:                     }
                   3287:                 }
                   3288:             }
                   3289:             if ($skipuser) {
                   3290:                 return 0;
                   3291:             }
                   3292:         }
                   3293:     }
1.1194    raeburn  3294:     $type ||= 'any';
                   3295:     if (!defined($cdom) || !defined($cnum)) {
                   3296:         my $cid  = $env{'request.course.id'};
                   3297:         $cdom = $env{'course.'.$cid.'.domain'};
                   3298:         $cnum = $env{'course.'.$cid.'.num'};
                   3299:     }
                   3300:     my $typesref;
1.1195    raeburn  3301:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3302:         $typesref = ['active','previous','future'];
                   3303:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3304:         $typesref = [$type];
                   3305:     }
                   3306:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3307:                               $typesref,undef,[$cdom]);
                   3308:     my ($tmp) = keys(%roles);
                   3309:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3310:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3311:     if (@course_roles > 0) {
                   3312:         return 1;
                   3313:     }
                   3314:     return 0;
                   3315: }
                   3316: 
1.478     albertel 3317: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3318: # input: action, courseID, current domain, intended
1.637     raeburn  3319: #        path to file, source of file, instruction to parse file for objects,
                   3320: #        ref to hash for embedded objects,
                   3321: #        ref to hash for codebase of java objects.
1.1095    raeburn  3322: #        reference to scalar to accommodate mime type determined
                   3323: #          from File::MMagic if $parser = parse.
1.637     raeburn  3324: #
1.485     raeburn  3325: # output: url to file (if action was uploaddoc), 
                   3326: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3327: #
1.478     albertel 3328: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3329: # course.
1.477     raeburn  3330: #
1.478     albertel 3331: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3332: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3333: #          course's home server.
1.477     raeburn  3334: #
1.478     albertel 3335: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3336: #          be copied from $source (current location) to 
                   3337: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3338: #         and will then be copied to
                   3339: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3340: #         course's home server.
1.485     raeburn  3341: #
1.481     raeburn  3342: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3343: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3344: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3345: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3346: #         in course's home server.
1.637     raeburn  3347: #
1.477     raeburn  3348: 
                   3349: sub process_coursefile {
1.1095    raeburn  3350:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3351:         $mimetype)=@_;
1.477     raeburn  3352:     my $fetchresult;
1.638     albertel 3353:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3354:     if ($action eq 'propagate') {
1.638     albertel 3355:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3356: 			     $home);
1.481     raeburn  3357:     } else {
1.477     raeburn  3358:         my $fpath = '';
                   3359:         my $fname = $file;
1.478     albertel 3360:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3361:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3362:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3363:         if ($action eq 'copy') {
                   3364:             if ($source eq '') {
                   3365:                 $fetchresult = 'no source file';
                   3366:                 return $fetchresult;
                   3367:             } else {
                   3368:                 my $destination = $filepath.'/'.$fname;
                   3369:                 rename($source,$destination);
                   3370:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3371:                                  $home);
1.481     raeburn  3372:             }
                   3373:         } elsif ($action eq 'uploaddoc') {
                   3374:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3375:             print $fh $env{'form.'.$source};
1.481     raeburn  3376:             close($fh);
1.637     raeburn  3377:             if ($parser eq 'parse') {
1.1024    raeburn  3378:                 my $mm = new File::MMagic;
1.1095    raeburn  3379:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3380:                 if ($type eq 'text/html') {
1.1024    raeburn  3381:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3382:                     unless ($parse_result eq 'ok') {
                   3383:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3384:                     }
1.637     raeburn  3385:                 }
1.1095    raeburn  3386:                 if (ref($mimetype)) {
                   3387:                     $$mimetype = $type;
                   3388:                 } 
1.637     raeburn  3389:             }
1.477     raeburn  3390:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3391:                                  $home);
1.481     raeburn  3392:             if ($fetchresult eq 'ok') {
                   3393:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3394:             } else {
                   3395:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3396:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3397:                 return '/adm/notfound.html';
                   3398:             }
1.477     raeburn  3399:         }
                   3400:     }
1.485     raeburn  3401:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3402:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3403:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3404:     }
                   3405:     return $fetchresult;
                   3406: }
                   3407: 
1.637     raeburn  3408: sub build_filepath {
                   3409:     my ($fpath) = @_;
                   3410:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3411:     unless ($fpath eq '') {
                   3412:         my @parts=split('/',$fpath);
                   3413:         foreach my $part (@parts) {
                   3414:             $filepath.= '/'.$part;
                   3415:             if ((-e $filepath)!=1) {
                   3416:                 mkdir($filepath,0777);
                   3417:             }
                   3418:         }
                   3419:     }
                   3420:     return $filepath;
                   3421: }
                   3422: 
                   3423: sub store_edited_file {
1.638     albertel 3424:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3425:     my $file = $primary_url;
                   3426:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3427:     my $fpath = '';
                   3428:     my $fname = $file;
                   3429:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3430:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3431:     my $filepath = &build_filepath($fpath);
                   3432:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3433:     print $fh $content;
                   3434:     close($fh);
1.638     albertel 3435:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3436:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3437: 			  $home);
1.637     raeburn  3438:     if ($$fetchresult eq 'ok') {
                   3439:         return '/uploaded/'.$fpath.'/'.$fname;
                   3440:     } else {
1.638     albertel 3441:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3442: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3443:         return '/adm/notfound.html';
                   3444:     }
                   3445: }
                   3446: 
1.531     albertel 3447: sub clean_filename {
1.831     albertel 3448:     my ($fname,$args)=@_;
1.315     www      3449: # Replace Windows backslashes by forward slashes
1.257     www      3450:     $fname=~s/\\/\//g;
1.831     albertel 3451:     if (!$args->{'keep_path'}) {
                   3452:         # Get rid of everything but the actual filename
                   3453: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3454:     }
1.315     www      3455: # Replace spaces by underscores
                   3456:     $fname=~s/\s+/\_/g;
                   3457: # Replace all other weird characters by nothing
1.831     albertel 3458:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3459: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3460: # numbers
                   3461:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3462:     return $fname;
                   3463: }
1.1051    raeburn  3464: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3465: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3466: # image with the same aspect ratio as the original, but with dimensions which do 
                   3467: # not exceed $resizewidth and $resizeheight.
                   3468:  
1.984     neumanie 3469: sub resizeImage {
1.1051    raeburn  3470:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3471:     my $ima = Image::Magick->new;
                   3472:     my $resized;
                   3473:     if (-e $img_path) {
                   3474:         $ima->Read($img_path);
                   3475:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3476:             my $width = $ima->Get('width');
                   3477:             my $height = $ima->Get('height');
                   3478:             if ($width > $resizewidth) {
                   3479: 	        my $factor = $width/$resizewidth;
                   3480:                 my $newheight = $height/$factor;
                   3481:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3482:                 $resized = 1;
                   3483:             }
                   3484:         }
                   3485:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3486:             my $width = $ima->Get('width');
                   3487:             my $height = $ima->Get('height');
                   3488:             if ($height > $resizeheight) {
                   3489:                 my $factor = $height/$resizeheight;
                   3490:                 my $newwidth = $width/$factor;
                   3491:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3492:                 $resized = 1;
                   3493:             }
                   3494:         }
                   3495:         if ($resized) {
                   3496:             $ima->Write($img_path);
                   3497:         }
                   3498:     }
                   3499:     return;
1.977     amueller 3500: }
                   3501: 
1.608     albertel 3502: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3503: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3504: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3505: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3506: #                                    canceloverwrite, or ''. 
                   3507: #                   if 'coursedoc': upload to the current course
                   3508: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3509: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3510: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3511: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3512: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3513: #        $allfiles - reference to hash for embedded objects
                   3514: #        $codebase - reference to hash for codebase of java objects
                   3515: #        $desuname - username for permanent storage of uploaded file
                   3516: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3517: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3518: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3519: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3520: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3521: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3522: #                    from File::MMagic.
1.858     raeburn  3523: # 
1.686     albertel 3524: # output: url of file in userspace, or error: <message> 
                   3525: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3526: 
1.531     albertel 3527: sub userfileupload {
1.1090    raeburn  3528:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3529:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3530:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3531:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3532:     $fname=&clean_filename($fname);
1.1090    raeburn  3533:     # See if there is anything left
1.257     www      3534:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3535:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3536:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3537:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3538:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3539:         my $now = time;
1.1090    raeburn  3540:         my $filepath;
1.1095    raeburn  3541:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3542:              $filepath = 'tmp/helprequests/'.$now;
                   3543:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3544:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3545:                          '_'.$env{'user.domain'}.'/pending';
                   3546:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3547:             my ($docuname,$docudom);
                   3548:             if ($destudom) {
                   3549:                 $docudom = $destudom;
                   3550:             } else {
                   3551:                 $docudom = $env{'user.domain'};
                   3552:             }
                   3553:             if ($destuname) {
                   3554:                 $docuname = $destuname;
                   3555:             } else {
                   3556:                 $docuname = $env{'user.name'};
                   3557:             }
                   3558:             if (exists($env{'form.group'})) {
                   3559:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3560:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3561:             }
                   3562:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3563:             if ($context eq 'canceloverwrite') {
                   3564:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3565:                 if (-e  $tempfile) {
                   3566:                     my @info = stat($tempfile);
                   3567:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3568:                         unlink($tempfile);
                   3569:                     }
                   3570:                 }
                   3571:                 return;
1.523     raeburn  3572:             }
                   3573:         }
1.1090    raeburn  3574:         # Create the directory if not present
1.741     raeburn  3575:         my @parts=split(/\//,$filepath);
                   3576:         my $fullpath = $perlvar{'lonDaemons'};
                   3577:         for (my $i=0;$i<@parts;$i++) {
                   3578:             $fullpath .= '/'.$parts[$i];
                   3579:             if ((-e $fullpath)!=1) {
                   3580:                 mkdir($fullpath,0777);
                   3581:             }
                   3582:         }
                   3583:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3584:         print $fh $env{'form.'.$formname};
                   3585:         close($fh);
1.1090    raeburn  3586:         if ($context eq 'existingfile') {
                   3587:             my @info = stat($fullpath.'/'.$fname);
                   3588:             return ($fullpath.'/'.$fname,$info[9]);
                   3589:         } else {
                   3590:             return $fullpath.'/'.$fname;
                   3591:         }
1.523     raeburn  3592:     }
1.995     raeburn  3593:     if ($subdir eq 'scantron') {
                   3594:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3595:     } else {
1.995     raeburn  3596:         $fname="$subdir/$fname";
                   3597:     }
1.1090    raeburn  3598:     if ($context eq 'coursedoc') {
1.638     albertel 3599: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3600: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3601:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3602:             return &finishuserfileupload($docuname,$docudom,
                   3603: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3604: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3605:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3606:         } else {
1.1218    raeburn  3607:             if ($env{'form.folder'}) {
                   3608:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3609:             }
1.638     albertel 3610:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3611: 				       $fname,$formname,$parser,
1.1095    raeburn  3612: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3613:         }
1.719     banghart 3614:     } elsif (defined($destuname)) {
                   3615:         my $docuname=$destuname;
                   3616:         my $docudom=$destudom;
1.860     raeburn  3617: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3618: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3619:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3620:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3621:     } else {
1.638     albertel 3622:         my $docuname=$env{'user.name'};
                   3623:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3624:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3625:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3626:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3627:         }
1.860     raeburn  3628: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3629: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3630:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3631:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3632:     }
1.271     www      3633: }
                   3634: 
                   3635: sub finishuserfileupload {
1.860     raeburn  3636:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3637:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3638:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3639:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3640:   
1.860     raeburn  3641:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3642:     $file=$fname;
                   3643:     if ($fname=~m|/|) {
                   3644:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3645: 	$path.=$fnamepath.'/';
                   3646:     }
1.259     www      3647:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3648:     my $count;
                   3649:     for ($count=4;$count<=$#parts;$count++) {
                   3650:         $filepath.="/$parts[$count]";
                   3651:         if ((-e $filepath)!=1) {
                   3652: 	    mkdir($filepath,0777);
                   3653:         }
                   3654:     }
1.984     neumanie 3655: 
1.258     www      3656: # Save the file
                   3657:     {
1.701     albertel 3658: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3659: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3660: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3661: 	    return '/adm/notfound.html';
                   3662: 	}
1.1090    raeburn  3663:         if ($context eq 'overwrite') {
1.1117    foxr     3664:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3665:             my $target = $filepath.'/'.$file;
                   3666:             if (-e $source) {
                   3667:                 my @info = stat($source);
                   3668:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3669:                     unless (&File::Copy::move($source,$target)) {
                   3670:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3671:                         return "Moving from $source failed";
                   3672:                     }
                   3673:                 } else {
                   3674:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3675:                 }
                   3676:             } else {
                   3677:                 return "Temporary file: $source missing";
                   3678:             }
                   3679:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3680: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3681: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3682: 	    return '/adm/notfound.html';
                   3683: 	}
1.570     albertel 3684: 	close(FH);
1.1051    raeburn  3685:         if ($resizewidth && $resizeheight) {
                   3686:             my $mm = new File::MMagic;
                   3687:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3688:             if ($mime_type =~ m{^image/}) {
                   3689: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3690:             }  
1.977     amueller 3691: 	}
1.258     www      3692:     }
1.1152    raeburn  3693:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3694:         if (ref($mimetype)) {
                   3695:             if ($$mimetype eq '') {
                   3696:                 my $mm = new File::MMagic;
                   3697:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3698:                 $$mimetype = $type;
                   3699:             }
                   3700:         }
                   3701:     }
1.637     raeburn  3702:     if ($parser eq 'parse') {
1.1152    raeburn  3703:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3704:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3705:                                                        $allfiles,$codebase);
                   3706:             unless ($parse_result eq 'ok') {
                   3707:                 &logthis('Failed to parse '.$filepath.$file.
                   3708: 	   	         ' for embedded media: '.$parse_result); 
                   3709:             }
1.637     raeburn  3710:         }
                   3711:     }
1.860     raeburn  3712:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3713:         my $input = $filepath.'/'.$file;
                   3714:         my $output = $filepath.'/'.'tn-'.$file;
                   3715:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3716:         system("convert -sample $thumbsize $input $output");
                   3717:         if (-e $filepath.'/'.'tn-'.$file) {
                   3718:             $fetchthumb  = 1; 
                   3719:         }
                   3720:     }
1.858     raeburn  3721:  
1.259     www      3722: # Notify homeserver to grep it
                   3723: #
1.984     neumanie 3724:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3725:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3726:     if ($fetchresult eq 'ok') {
1.860     raeburn  3727:         if ($fetchthumb) {
                   3728:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3729:             if ($thumbresult ne 'ok') {
                   3730:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3731:                          $docuhome.': '.$thumbresult);
                   3732:             }
                   3733:         }
1.259     www      3734: #
1.258     www      3735: # Return the URL to it
1.494     albertel 3736:         return '/uploaded/'.$path.$file;
1.263     www      3737:     } else {
1.494     albertel 3738:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3739: 		 ': '.$fetchresult);
1.263     www      3740:         return '/adm/notfound.html';
1.858     raeburn  3741:     }
1.493     albertel 3742: }
                   3743: 
1.637     raeburn  3744: sub extract_embedded_items {
1.961     raeburn  3745:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3746:     my @state = ();
1.1164    raeburn  3747:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3748:     my %javafiles = (
                   3749:                       codebase => '',
                   3750:                       code => '',
                   3751:                       archive => ''
                   3752:                     );
                   3753:     my %mediafiles = (
                   3754:                       src => '',
                   3755:                       movie => '',
                   3756:                      );
1.648     raeburn  3757:     my $p;
                   3758:     if ($content) {
                   3759:         $p = HTML::LCParser->new($content);
                   3760:     } else {
1.961     raeburn  3761:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3762:     }
1.641     albertel 3763:     while (my $t=$p->get_token()) {
1.640     albertel 3764: 	if ($t->[0] eq 'S') {
                   3765: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3766: 	    push(@state, $tagname);
1.648     raeburn  3767:             if (lc($tagname) eq 'allow') {
                   3768:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3769:             }
1.640     albertel 3770: 	    if (lc($tagname) eq 'img') {
                   3771: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3772: 	    }
1.886     albertel 3773: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  3774:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  3775:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3776:                 }
1.886     albertel 3777: 	    }
1.645     raeburn  3778:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3779:                 my $src;
1.645     raeburn  3780:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3781:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3782:                 } else {
1.1164    raeburn  3783:                     if ($attr->{'src'} ne '') {
                   3784:                         $src = $attr->{'src'};
                   3785:                         &add_filetype($allfiles,$src,'src');
                   3786:                     }
                   3787:                 }
                   3788:                 my $text = $p->get_trimmed_text();
                   3789:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3790:                     my @swfargs = split(/,/,$1);
                   3791:                     foreach my $item (@swfargs) {
                   3792:                         $item =~ s/["']//g;
                   3793:                         $item =~ s/^\s+//;
                   3794:                         $item =~ s/\s+$//;
                   3795:                     }
                   3796:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3797:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3798:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3799:                         } else {
                   3800:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3801:                         }
                   3802:                     }
1.645     raeburn  3803:                 }
                   3804:             }
                   3805:             if (lc($tagname) eq 'link') {
                   3806:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3807:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3808:                 }
                   3809:             }
1.640     albertel 3810: 	    if (lc($tagname) eq 'object' ||
                   3811: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3812: 		foreach my $item (keys(%javafiles)) {
                   3813: 		    $javafiles{$item} = '';
                   3814: 		}
1.1164    raeburn  3815:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3816:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3817:                 }
1.640     albertel 3818: 	    }
                   3819: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3820: 		my $name = lc($attr->{'name'});
                   3821: 		foreach my $item (keys(%javafiles)) {
                   3822: 		    if ($name eq $item) {
                   3823: 			$javafiles{$item} = $attr->{'value'};
                   3824: 			last;
                   3825: 		    }
                   3826: 		}
1.1164    raeburn  3827:                 my $pathfrom;
1.640     albertel 3828: 		foreach my $item (keys(%mediafiles)) {
                   3829: 		    if ($name eq $item) {
1.1164    raeburn  3830:                         $pathfrom = $attr->{'value'};
                   3831:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3832: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3833: 			last;
                   3834: 		    }
                   3835: 		}
1.1164    raeburn  3836:                 if ($name eq 'flashvars') {
                   3837:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3838:                 }
                   3839:                 if ($pathfrom ne '') {
                   3840:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3841:                                          $pathfrom);
                   3842:                 }
1.640     albertel 3843: 	    }
                   3844: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3845: 		foreach my $item (keys(%javafiles)) {
                   3846: 		    if ($attr->{$item}) {
                   3847: 			$javafiles{$item} = $attr->{$item};
                   3848: 			last;
                   3849: 		    }
                   3850: 		}
                   3851: 		foreach my $item (keys(%mediafiles)) {
                   3852: 		    if ($attr->{$item}) {
                   3853: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3854: 			last;
                   3855: 		    }
                   3856: 		}
1.1164    raeburn  3857:                 if (lc($tagname) eq 'embed') {
                   3858:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3859:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3860:                                              $attr->{'src'});
                   3861:                     }
                   3862:                 }
1.640     albertel 3863: 	    }
1.1243    raeburn  3864:             if (lc($tagname) eq 'iframe') {
                   3865:                 my $src = $attr->{'src'} ;
                   3866:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3867:                     &add_filetype($allfiles,$src,'src');
                   3868:                 } elsif ($src =~ m{^/}) {
                   3869:                     if ($env{'request.course.id'}) {
                   3870:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3871:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3872:                         my $url = &hreflocation('',$fullpath);
                   3873:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3874:                             my $relpath = $1;
                   3875:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3876:                                 &add_filetype($allfiles,$1,'src');
                   3877:                             }
                   3878:                         }
                   3879:                     }
                   3880:                 }
                   3881:             }
1.1164    raeburn  3882:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  3883:                 pop(@state);
1.1164    raeburn  3884:             }
1.640     albertel 3885: 	} elsif ($t->[0] eq 'E') {
                   3886: 	    my ($tagname) = ($t->[1]);
                   3887: 	    if ($javafiles{'codebase'} ne '') {
                   3888: 		$javafiles{'codebase'} .= '/';
                   3889: 	    }  
                   3890: 	    if (lc($tagname) eq 'applet' ||
                   3891: 		lc($tagname) eq 'object' ||
                   3892: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3893: 		) {
                   3894: 		foreach my $item (keys(%javafiles)) {
                   3895: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3896: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3897: 			&add_filetype($allfiles,$file,$item);
                   3898: 		    }
                   3899: 		}
                   3900: 	    } 
                   3901: 	    pop @state;
                   3902: 	}
                   3903:     }
1.1164    raeburn  3904:     foreach my $id (sort(keys(%flashvars))) {
                   3905:         if ($shockwave{$id} ne '') {
                   3906:             my @pairs = split(/\&/,$flashvars{$id});
                   3907:             foreach my $pair (@pairs) {
                   3908:                 my ($key,$value) = split(/\=/,$pair);
                   3909:                 if ($key eq 'thumb') {
                   3910:                     &add_filetype($allfiles,$value,$key);
                   3911:                 } elsif ($key eq 'content') {
                   3912:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3913:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3914:                     if ($ext ne '') {
                   3915:                         &add_filetype($allfiles,$path.$value,$ext);
                   3916:                     }
                   3917:                 }
                   3918:             }
                   3919:         }
                   3920:     }
1.637     raeburn  3921:     return 'ok';
                   3922: }
                   3923: 
1.639     albertel 3924: sub add_filetype {
                   3925:     my ($allfiles,$file,$type)=@_;
                   3926:     if (exists($allfiles->{$file})) {
                   3927: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3928: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3929: 	}
                   3930:     } else {
                   3931: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3932:     }
                   3933: }
                   3934: 
1.1164    raeburn  3935: sub embedded_dependency {
                   3936:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3937:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3938:         if (($identifier ne '') &&
                   3939:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3940:             ($pathfrom ne '')) {
                   3941:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3942:             foreach my $dep (@{$related->{$identifier}}) {
                   3943:                 &add_filetype($allfiles,$path.$dep,'object');
                   3944:             }
                   3945:         }
                   3946:     }
                   3947:     return;
                   3948: }
                   3949: 
1.493     albertel 3950: sub removeuploadedurl {
1.984     neumanie 3951:     my ($url)=@_;	
                   3952:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3953:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3954: }
                   3955: 
                   3956: sub removeuserfile {
                   3957:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3958:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3959:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3960:     if ($result eq 'ok') {	
1.798     raeburn  3961:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3962:             my $metafile = $fname.'.meta';
                   3963:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3964: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3965:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3966:             my $sqlresult = 
1.823     albertel 3967:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3968:                                         'portfolio_metadata',$group,
                   3969:                                         'delete');
1.798     raeburn  3970:         }
                   3971:     }
                   3972:     return $result;
1.257     www      3973: }
1.15      www      3974: 
1.530     albertel 3975: sub mkdiruserfile {
                   3976:     my ($docuname,$docudom,$dir)=@_;
                   3977:     my $home=&homeserver($docuname,$docudom);
                   3978:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3979: }
                   3980: 
1.531     albertel 3981: sub renameuserfile {
                   3982:     my ($docuname,$docudom,$old,$new)=@_;
                   3983:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3984:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3985:                         &escape("$old").':'.&escape("$new"),$home);
                   3986:     if ($result eq 'ok') {
                   3987:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3988:             my $oldmeta = $old.'.meta';
                   3989:             my $newmeta = $new.'.meta';
                   3990:             my $metaresult = 
                   3991:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3992: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3993:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3994:             my $sqlresult = 
1.823     albertel 3995:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3996:                                         'portfolio_metadata',$group,
                   3997:                                         'delete');
1.798     raeburn  3998:         }
                   3999:     }
                   4000:     return $result;
1.531     albertel 4001: }
                   4002: 
1.14      www      4003: # ------------------------------------------------------------------------- Log
                   4004: 
                   4005: sub log {
                   4006:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4007:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4008: }
                   4009: 
                   4010: # ------------------------------------------------------------------ Course Log
1.352     www      4011: #
                   4012: # This routine flushes several buffers of non-mission-critical nature
                   4013: #
1.157     www      4014: 
                   4015: sub flushcourselogs {
1.352     www      4016:     &logthis('Flushing log buffers');
                   4017: #
                   4018: # course logs
                   4019: # This is a log of all transactions in a course, which can be used
                   4020: # for data mining purposes
                   4021: #
                   4022: # It also collects the courseid database, which lists last transaction
                   4023: # times and course titles for all courseids
                   4024: #
                   4025:     my %courseidbuffer=();
1.921     raeburn  4026:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4027:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4028: 		          &escape($courselogs{$crsid}),
                   4029: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4030: 	    delete $courselogs{$crsid};
                   4031:         } else {
                   4032:             &logthis('Failed to flush log buffer for '.$crsid);
                   4033:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4034:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4035:                         " exceeded maximum size, deleting.</font>");
                   4036:                delete $courselogs{$crsid};
                   4037:             }
1.352     www      4038:         }
1.920     raeburn  4039:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4040:             'description' => $coursedescrbuf{$crsid},
                   4041:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4042:             'type'        => $coursetypebuf{$crsid},
                   4043:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4044:         };
1.191     harris41 4045:     }
1.352     www      4046: #
                   4047: # Write course id database (reverse lookup) to homeserver of courses 
                   4048: # Is used in pickcourse
                   4049: #
1.840     albertel 4050:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4051:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4052:                                     $courseidbuffer{$crs_home},
                   4053:                                     $crs_home,'timeonly');
1.352     www      4054:     }
                   4055: #
                   4056: # File accesses
                   4057: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4058: #
1.449     matthew  4059:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4060:         if ($entry =~ /___count$/) {
                   4061:             my ($dom,$name);
1.807     albertel 4062:             ($dom,$name,undef)=
1.811     albertel 4063: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4064:             if (! defined($dom) || $dom eq '' || 
                   4065:                 ! defined($name) || $name eq '') {
1.620     albertel 4066:                 my $cid = $env{'request.course.id'};
                   4067:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4068:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4069:             }
1.450     matthew  4070:             my $value = $accesshash{$entry};
                   4071:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4072:             my %temphash=($url => $value);
1.449     matthew  4073:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4074:             if ($result eq 'ok') {
                   4075:                 delete $accesshash{$entry};
                   4076:             }
                   4077:         } else {
1.811     albertel 4078:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4079:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4080:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4081:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4082:                 delete $accesshash{$entry};
                   4083:             }
1.185     www      4084:         }
1.191     harris41 4085:     }
1.352     www      4086: #
                   4087: # Roles
                   4088: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4089: #
1.800     albertel 4090:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4091:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4092: 	    split(/\:/,$entry);
                   4093:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4094:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4095:                 $rudom,$runame) eq 'ok') {
                   4096: 	    delete $userrolehash{$entry};
                   4097:         }
                   4098:     }
1.662     raeburn  4099: #
                   4100: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   4101: #
                   4102:     my %domrolebuffer = ();
1.1000    raeburn  4103:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4104:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4105:         if ($domrolebuffer{$rudom}) {
                   4106:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4107:                       '='.&escape($domainrolehash{$entry});
                   4108:         } else {
                   4109:             $domrolebuffer{$rudom}.=&escape($entry).
                   4110:                       '='.&escape($domainrolehash{$entry});
                   4111:         }
                   4112:         delete $domainrolehash{$entry};
                   4113:     }
                   4114:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 4115: 	my %servers = &get_servers($dom,'library');
                   4116: 	foreach my $tryserver (keys(%servers)) {
                   4117: 	    unless (&reply('domroleput:'.$dom.':'.
                   4118: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4119: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4120: 	    }
1.662     raeburn  4121:         }
                   4122:     }
1.186     www      4123:     $dumpcount++;
1.157     www      4124: }
                   4125: 
                   4126: sub courselog {
                   4127:     my $what=shift;
1.158     www      4128:     $what=time.':'.$what;
1.620     albertel 4129:     unless ($env{'request.course.id'}) { return ''; }
                   4130:     $coursedombuf{$env{'request.course.id'}}=
                   4131:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4132:     $coursenumbuf{$env{'request.course.id'}}=
                   4133:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4134:     $coursehombuf{$env{'request.course.id'}}=
                   4135:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4136:     $coursedescrbuf{$env{'request.course.id'}}=
                   4137:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4138:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4139:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4140:     $courseownerbuf{$env{'request.course.id'}}=
                   4141:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4142:     $coursetypebuf{$env{'request.course.id'}}=
                   4143:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4144:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4145: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4146:     } else {
1.620     albertel 4147: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4148:     }
1.620     albertel 4149:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4150: 	&flushcourselogs();
                   4151:     }
1.158     www      4152: }
                   4153: 
                   4154: sub courseacclog {
                   4155:     my $fnsymb=shift;
1.620     albertel 4156:     unless ($env{'request.course.id'}) { return ''; }
                   4157:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4158:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4159:         $what.=':POST';
1.583     matthew  4160:         # FIXME: Probably ought to escape things....
1.800     albertel 4161: 	foreach my $key (keys(%env)) {
                   4162:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4163:                 my $formitem = $1;
                   4164:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4165:                     $what.=':'.$formitem.'='.$env{$key};
                   4166:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4167:                     $what.=':'.$formitem.'='.$env{$key};
                   4168:                 }
1.158     www      4169:             }
1.191     harris41 4170:         }
1.583     matthew  4171:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4172:         # FIXME: We should not be depending on a form parameter that someone
                   4173:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4174:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4175:             $what.= ':POST';
                   4176:             # FIXME: Probably ought to escape things....
                   4177:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4178:                                  'crsdiscuss') {
1.620     albertel 4179:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4180:             }
                   4181:         }
1.158     www      4182:     }
                   4183:     &courselog($what);
1.149     www      4184: }
                   4185: 
1.185     www      4186: sub countacc {
                   4187:     my $url=&declutter(shift);
1.458     matthew  4188:     return if (! defined($url) || $url eq '');
1.620     albertel 4189:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4190: #
                   4191: # Mark that this url was used in this course
                   4192: #
1.620     albertel 4193:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4194: #
                   4195: # Increase the access count for this resource in this child process
                   4196: #
1.281     www      4197:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4198:     $accesshash{$key}++;
1.185     www      4199: }
1.349     www      4200: 
1.361     www      4201: sub linklog {
                   4202:     my ($from,$to)=@_;
                   4203:     $from=&declutter($from);
                   4204:     $to=&declutter($to);
                   4205:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4206:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4207: }
1.1160    www      4208: 
                   4209: sub statslog {
                   4210:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4211:     if ($users<2) { return; }
                   4212:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4213:             'course'       => $env{'request.course.id'},
                   4214:             'sections'     => '"all"',
                   4215:             'num_students' => $users,
                   4216:             'part'         => $part,
                   4217:             'symb'         => $symb,
                   4218:             'mean_tries'   => $av_attempts,
                   4219:             'deg_of_diff'  => $degdiff});
                   4220:     foreach my $key (keys(%dynstore)) {
                   4221:         $accesshash{$key}=$dynstore{$key};
                   4222:     }
                   4223: }
1.361     www      4224:   
1.349     www      4225: sub userrolelog {
                   4226:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4227:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4228:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4229:        $userrolehash
                   4230:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4231:                     =$tend.':'.$tstart;
1.662     raeburn  4232:     }
1.1169    droeschl 4233:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4234:        $userrolehash
                   4235:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4236:                     =$tend.':'.$tstart;
                   4237:     }
1.1169    droeschl 4238:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  4239:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4240:        $domainrolehash
                   4241:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4242:                     = $tend.':'.$tstart;
                   4243:     }
1.351     www      4244: }
                   4245: 
1.957     raeburn  4246: sub courserolelog {
                   4247:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4248:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4249:         my $cdom = $1;
                   4250:         my $cnum = $2;
                   4251:         my $sec = $3;
                   4252:         my $namespace = 'rolelog';
                   4253:         my %storehash = (
                   4254:                            role    => $trole,
                   4255:                            start   => $tstart,
                   4256:                            end     => $tend,
                   4257:                            selfenroll => $selfenroll,
                   4258:                            context    => $context,
                   4259:                         );
                   4260:         if ($trole eq 'gr') {
                   4261:             $namespace = 'groupslog';
                   4262:             $storehash{'group'} = $sec;
                   4263:         } else {
                   4264:             $storehash{'section'} = $sec;
                   4265:         }
1.1188    raeburn  4266:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4267:                    $domain,$cnum,$cdom);
1.1184    raeburn  4268:         if (($trole ne 'st') || ($sec ne '')) {
                   4269:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4270:         }
                   4271:     }
                   4272:     return;
                   4273: }
                   4274: 
1.1184    raeburn  4275: sub domainrolelog {
                   4276:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4277:     if ($area =~ m{^/($match_domain)/$}) {
                   4278:         my $cdom = $1;
                   4279:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4280:         my $namespace = 'rolelog';
                   4281:         my %storehash = (
                   4282:                            role    => $trole,
                   4283:                            start   => $tstart,
                   4284:                            end     => $tend,
                   4285:                            context => $context,
                   4286:                         );
1.1188    raeburn  4287:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4288:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4289:     }
                   4290:     return;
                   4291: 
                   4292: }
                   4293: 
                   4294: sub coauthorrolelog {
                   4295:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4296:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4297:         my $audom = $1;
                   4298:         my $auname = $2;
                   4299:         my $namespace = 'rolelog';
                   4300:         my %storehash = (
                   4301:                            role    => $trole,
                   4302:                            start   => $tstart,
                   4303:                            end     => $tend,
                   4304:                            context => $context,
                   4305:                         );
1.1188    raeburn  4306:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4307:                    $domain,$auname,$audom);
1.1184    raeburn  4308:     }
                   4309:     return;
                   4310: }
                   4311: 
1.351     www      4312: sub get_course_adv_roles {
1.948     raeburn  4313:     my ($cid,$codes) = @_;
1.620     albertel 4314:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4315:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4316:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4317:     my %nothide=();
1.800     albertel 4318:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4319:         if ($user !~ /:/) {
                   4320: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4321:         } else {
                   4322:             $nothide{$user}=1;
                   4323:         }
1.470     www      4324:     }
1.1219    raeburn  4325:     my @possdoms = ($coursehash{'domain'});
                   4326:     if ($coursehash{'checkforpriv'}) {
                   4327:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4328:     }
1.351     www      4329:     my %returnhash=();
                   4330:     my %dumphash=
                   4331:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4332:     my $now=time;
1.997     raeburn  4333:     my %privileged;
1.1000    raeburn  4334:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4335: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4336:         if (($tstart) && ($tstart<0)) { next; }
                   4337:         if (($tend) && ($tend<$now)) { next; }
                   4338:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4339:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4340: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4341:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4342:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4343: 	if ($role eq 'cr') { next; }
1.948     raeburn  4344:         if ($codes) {
                   4345:             if ($section) { $role .= ':'.$section; }
                   4346:             if ($returnhash{$role}) {
                   4347:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4348:             } else {
                   4349:                 $returnhash{$role}=$username.':'.$domain;
                   4350:             }
1.351     www      4351:         } else {
1.988     raeburn  4352:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4353:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4354:             if ($returnhash{$key}) {
                   4355: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4356:             } else {
                   4357:                 $returnhash{$key}=$username.':'.$domain;
                   4358:             }
1.351     www      4359:         }
1.948     raeburn  4360:     }
1.400     www      4361:     return %returnhash;
                   4362: }
                   4363: 
                   4364: sub get_my_roles {
1.937     raeburn  4365:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4366:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4367:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4368:     my (%dumphash,%nothide);
1.1086    raeburn  4369:     if ($context eq 'userroles') {
1.1166    raeburn  4370:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4371:     } else {
1.1219    raeburn  4372:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4373:         if ($hidepriv) {
                   4374:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4375:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4376:                 if ($user !~ /:/) {
                   4377:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4378:                 } else {
                   4379:                     $nothide{$user} = 1;
                   4380:                 }
                   4381:             }
                   4382:         }
1.858     raeburn  4383:     }
1.400     www      4384:     my %returnhash=();
                   4385:     my $now=time;
1.999     raeburn  4386:     my %privileged;
1.800     albertel 4387:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4388:         my ($role,$tend,$tstart);
                   4389:         if ($context eq 'userroles') {
1.1149    raeburn  4390:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4391: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4392:         } else {
                   4393:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4394:         }
1.400     www      4395:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4396:         my $status = 'active';
1.939     raeburn  4397:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4398:             $status = 'previous';
                   4399:         } 
                   4400:         if (($tstart) && ($now<$tstart)) {
                   4401:             $status = 'future';
                   4402:         }
                   4403:         if (ref($types) eq 'ARRAY') {
                   4404:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4405:                 next;
                   4406:             } 
                   4407:         } else {
                   4408:             if ($status ne 'active') {
                   4409:                 next;
                   4410:             }
                   4411:         }
1.867     raeburn  4412:         my ($rolecode,$username,$domain,$section,$area);
                   4413:         if ($context eq 'userroles') {
1.1186    raeburn  4414:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4415:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4416:         } else {
                   4417:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4418:         }
1.832     raeburn  4419:         if (ref($roledoms) eq 'ARRAY') {
                   4420:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4421:                 next;
                   4422:             }
                   4423:         }
                   4424:         if (ref($roles) eq 'ARRAY') {
                   4425:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4426:                 if ($role =~ /^cr\//) {
                   4427:                     if (!grep(/^cr$/,@{$roles})) {
                   4428:                         next;
                   4429:                     }
1.1104    raeburn  4430:                 } elsif ($role =~ /^gr\//) {
                   4431:                     if (!grep(/^gr$/,@{$roles})) {
                   4432:                         next;
                   4433:                     }
1.922     raeburn  4434:                 } else {
                   4435:                     next;
                   4436:                 }
1.832     raeburn  4437:             }
1.867     raeburn  4438:         }
1.937     raeburn  4439:         if ($hidepriv) {
1.1219    raeburn  4440:             my @privroles = ('dc','su');
1.999     raeburn  4441:             if ($context eq 'userroles') {
1.1219    raeburn  4442:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4443:             } else {
1.1219    raeburn  4444:                 my $possdoms = [$domain];
                   4445:                 if (ref($roledoms) eq 'ARRAY') {
                   4446:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4447:                 }
1.1219    raeburn  4448:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4449:                     if (!$nothide{$username.':'.$domain}) {
                   4450:                         next;
                   4451:                     }
                   4452:                 }
1.937     raeburn  4453:             }
                   4454:         }
1.933     raeburn  4455:         if ($withsec) {
                   4456:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4457:                 $tstart.':'.$tend;
                   4458:         } else {
                   4459:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4460:         }
1.832     raeburn  4461:     }
1.373     www      4462:     return %returnhash;
1.399     www      4463: }
                   4464: 
                   4465: # ----------------------------------------------------- Frontpage Announcements
                   4466: #
                   4467: #
                   4468: 
                   4469: sub postannounce {
                   4470:     my ($server,$text)=@_;
1.844     albertel 4471:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4472:     unless ($text=~/\w/) { $text=''; }
                   4473:     return &reply('setannounce:'.&escape($text),$server);
                   4474: }
                   4475: 
                   4476: sub getannounce {
1.448     albertel 4477: 
                   4478:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4479: 	my $announcement='';
1.800     albertel 4480: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4481: 	close($fh);
1.399     www      4482: 	if ($announcement=~/\w/) { 
                   4483: 	    return 
                   4484:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4485:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4486: 	} else {
                   4487: 	    return '';
                   4488: 	}
                   4489:     } else {
                   4490: 	return '';
                   4491:     }
1.351     www      4492: }
1.353     www      4493: 
                   4494: # ---------------------------------------------------------- Course ID routines
                   4495: # Deal with domain's nohist_courseid.db files
                   4496: #
                   4497: 
                   4498: sub courseidput {
1.921     raeburn  4499:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4500:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4501:     my $outcome;
                   4502:     if ($caller eq 'timeonly') {
                   4503:         my $cids = '';
                   4504:         foreach my $item (keys(%$storehash)) {
                   4505:             $cids.=&escape($item).'&';
                   4506:         }
                   4507:         $cids=~s/\&$//;
                   4508:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4509:                           $coursehome);       
                   4510:     } else {
                   4511:         my $items = '';
                   4512:         foreach my $item (keys(%$storehash)) {
                   4513:             $items.= &escape($item).'='.
                   4514:                      &freeze_escape($$storehash{$item}).'&';
                   4515:         }
                   4516:         $items=~s/\&$//;
                   4517:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4518:                           $coursehome);
1.918     raeburn  4519:     }
                   4520:     if ($outcome eq 'unknown_cmd') {
                   4521:         my $what;
                   4522:         foreach my $cid (keys(%$storehash)) {
                   4523:             $what .= &escape($cid).'=';
1.921     raeburn  4524:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4525:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4526:             }
                   4527:             $what =~ s/\:$/&/;
                   4528:         }
                   4529:         $what =~ s/\&$//;  
                   4530:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4531:     } else {
                   4532:         return $outcome;
                   4533:     }
1.353     www      4534: }
                   4535: 
                   4536: sub courseiddump {
1.921     raeburn  4537:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4538:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4539:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  4540:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  4541:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4542:     my $as_hash = 1;
                   4543:     my %returnhash;
                   4544:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4545:     my %libserv = &all_library();
                   4546:     foreach my $tryserver (keys(%libserv)) {
                   4547:         if ( (  $hostidflag == 1 
                   4548: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4549: 	     || (!defined($hostidflag)) ) {
                   4550: 
1.918     raeburn  4551: 	    if (($domfilter eq '') ||
                   4552: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4553:                 my $rep;
                   4554:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4555:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4556:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   4557:                                 &escape($descfilter), &escape($instcodefilter), 
                   4558:                                 &escape($ownerfilter), &escape($coursefilter),
                   4559:                                 &escape($typefilter), &escape($regexp_ok), 
                   4560:                                 $as_hash, &escape($selfenrollonly), 
                   4561:                                 &escape($catfilter), $showhidden, $caller, 
                   4562:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   4563:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  4564:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   4565:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 4566:                 } else {
                   4567:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4568:                              $sincefilter.':'.&escape($descfilter).':'.
                   4569:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4570:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4571:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4572:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4573:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4574:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4575:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  4576:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   4577:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 4578:                 }
                   4579:                      
1.918     raeburn  4580:                 my @pairs=split(/\&/,$rep);
                   4581:                 foreach my $item (@pairs) {
                   4582:                     my ($key,$value)=split(/\=/,$item,2);
                   4583:                     $key = &unescape($key);
                   4584:                     next if ($key =~ /^error: 2 /);
                   4585:                     my $result = &thaw_unescape($value);
                   4586:                     if (ref($result) eq 'HASH') {
                   4587:                         $returnhash{$key}=$result;
                   4588:                     } else {
1.921     raeburn  4589:                         my @responses = split(/:/,$value);
                   4590:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4591:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4592:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4593:                         }
1.1008    raeburn  4594:                     }
1.353     www      4595:                 }
                   4596:             }
                   4597:         }
                   4598:     }
                   4599:     return %returnhash;
                   4600: }
                   4601: 
1.1055    raeburn  4602: sub courselastaccess {
                   4603:     my ($cdom,$cnum,$hostidref) = @_;
                   4604:     my %returnhash;
                   4605:     if ($cdom && $cnum) {
                   4606:         my $chome = &homeserver($cnum,$cdom);
                   4607:         if ($chome ne 'no_host') {
                   4608:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4609:             &extract_lastaccess(\%returnhash,$rep);
                   4610:         }
                   4611:     } else {
                   4612:         if (!$cdom) { $cdom=''; }
                   4613:         my %libserv = &all_library();
                   4614:         foreach my $tryserver (keys(%libserv)) {
                   4615:             if (ref($hostidref) eq 'ARRAY') {
                   4616:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4617:             } 
                   4618:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4619:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4620:                 &extract_lastaccess(\%returnhash,$rep);
                   4621:             }
                   4622:         }
                   4623:     }
                   4624:     return %returnhash;
                   4625: }
                   4626: 
                   4627: sub extract_lastaccess {
                   4628:     my ($returnhash,$rep) = @_;
                   4629:     if (ref($returnhash) eq 'HASH') {
                   4630:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4631:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4632:                  $rep eq '') {
                   4633:             my @pairs=split(/\&/,$rep);
                   4634:             foreach my $item (@pairs) {
                   4635:                 my ($key,$value)=split(/\=/,$item,2);
                   4636:                 $key = &unescape($key);
                   4637:                 next if ($key =~ /^error: 2 /);
                   4638:                 $returnhash->{$key} = &thaw_unescape($value);
                   4639:             }
                   4640:         }
                   4641:     }
                   4642:     return;
                   4643: }
                   4644: 
1.658     raeburn  4645: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4646: 
                   4647: sub dcmailput {
1.685     raeburn  4648:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4649:     my $status = &Apache::lonnet::critical(
1.740     www      4650:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4651:        &escape($message),$server);
1.662     raeburn  4652:     return $status;
                   4653: }
                   4654: 
1.658     raeburn  4655: sub dcmaildump {
                   4656:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4657:     my %returnhash=();
1.846     albertel 4658: 
                   4659:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4660:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4661:                                                          &escape($enddate).':';
                   4662: 	my @esc_senders=map { &escape($_)} @$senders;
                   4663: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4664: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4665:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4666:             if (($key) && ($value)) {
                   4667:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4668:             }
                   4669:         }
                   4670:     }
                   4671:     return %returnhash;
                   4672: }
1.662     raeburn  4673: # ---------------------------------------------------------- Domain roles
                   4674: 
                   4675: sub get_domain_roles {
                   4676:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4677:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4678:         $startdate = '.';
                   4679:     }
1.1018    raeburn  4680:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4681:         $enddate = '.';
                   4682:     }
1.922     raeburn  4683:     my $rolelist;
                   4684:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  4685:         $rolelist = join('&',@{$roles});
1.922     raeburn  4686:     }
1.662     raeburn  4687:     my %personnel = ();
1.841     albertel 4688: 
                   4689:     my %servers = &get_servers($dom,'library');
                   4690:     foreach my $tryserver (keys(%servers)) {
                   4691: 	%{$personnel{$tryserver}}=();
                   4692: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4693: 					    &escape($startdate).':'.
                   4694: 					    &escape($enddate).':'.
                   4695: 					    &escape($rolelist), $tryserver))) {
                   4696: 	    my ($key,$value) = split(/\=/,$line,2);
                   4697: 	    if (($key) && ($value)) {
                   4698: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4699: 	    }
                   4700: 	}
1.662     raeburn  4701:     }
                   4702:     return %personnel;
                   4703: }
1.658     raeburn  4704: 
1.1057    www      4705: # ----------------------------------------------------------- Interval timing 
1.149     www      4706: 
1.1153    www      4707: {
                   4708: # Caches needed for speedup of navmaps
                   4709: # We don't want to cache this for very long at all (5 seconds at most)
                   4710: # 
                   4711: # The user for whom we cache
                   4712: my $cachedkey='';
                   4713: # The cached times for this user
                   4714: my %cachedtimes=();
                   4715: # When this was last done
1.1282    raeburn  4716: my $cachedtime='';
1.1153    www      4717: 
                   4718: sub load_all_first_access {
1.1308    raeburn  4719:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      4720:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  4721:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   4722:         (!$ignorecache)) {
1.1154    raeburn  4723:         return;
                   4724:     }
                   4725:     $cachedtime=time;
                   4726:     $cachedkey=$uname.':'.$udom;
                   4727:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4728: }
                   4729: 
1.504     albertel 4730: sub get_first_access {
1.1308    raeburn  4731:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 4732:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4733:     if ($argsymb) { $symb=$argsymb; }
                   4734:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4735:     if ($argmap) { $map = $argmap; }
1.926     albertel 4736:     if ($type eq 'course') {
                   4737: 	$res='course';
                   4738:     } elsif ($type eq 'map') {
1.588     albertel 4739: 	$res=&symbread($map);
                   4740:     } else {
                   4741: 	$res=$symb;
                   4742:     }
1.1308    raeburn  4743:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      4744:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4745: }
                   4746: 
                   4747: sub set_first_access {
1.1162    raeburn  4748:     my ($type,$interval)=@_;
1.790     albertel 4749:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4750:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4751:     if ($type eq 'course') {
                   4752: 	$res='course';
                   4753:     } elsif ($type eq 'map') {
1.588     albertel 4754: 	$res=&symbread($map);
                   4755:     } else {
                   4756: 	$res=$symb;
                   4757:     }
1.1153    www      4758:     $cachedkey='';
1.1162    raeburn  4759:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4760:     if (!$firstaccess) {
1.1162    raeburn  4761:         my $start = time;
                   4762: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4763:                           $udom,$uname);
                   4764:         if ($putres eq 'ok') {
                   4765:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4766:                  $udom,$uname); 
                   4767:             &appenv(
                   4768:                      {
                   4769:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4770:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4771:                      }
                   4772:                   );
                   4773:         }
                   4774:         return $putres;
1.505     albertel 4775:     }
                   4776:     return 'already_set';
1.504     albertel 4777: }
1.1153    www      4778: }
1.1282    raeburn  4779: 
1.110     www      4780: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4781: 
                   4782: sub expirespread {
                   4783:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4784:     my $cid=$env{'request.course.id'}; 
1.110     www      4785:     if ($cid) {
                   4786:        my $now=time;
                   4787:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4788:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4789:                             $env{'course.'.$cid.'.num'}.
1.110     www      4790: 	        	    ':nohist_expirationdates:'.
                   4791:                             &escape($key).'='.$now,
1.620     albertel 4792:                             $env{'course.'.$cid.'.home'})
1.110     www      4793:     }
                   4794:     return 'ok';
1.14      www      4795: }
                   4796: 
1.109     www      4797: # ----------------------------------------------------- Devalidate Spreadsheets
                   4798: 
                   4799: sub devalidate {
1.325     www      4800:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4801:     my $cid=$env{'request.course.id'}; 
1.109     www      4802:     if ($cid) {
1.391     matthew  4803:         # delete the stored spreadsheets for
                   4804:         # - the student level sheet of this user in course's homespace
                   4805:         # - the assessment level sheet for this resource 
                   4806:         #   for this user in user's homespace
1.553     albertel 4807: 	# - current conditional state info
1.325     www      4808: 	my $key=$uname.':'.$udom.':';
1.109     www      4809:         my $status=
1.299     matthew  4810: 	    &del('nohist_calculatedsheets',
1.391     matthew  4811: 		 [$key.'studentcalc:'],
1.620     albertel 4812: 		 $env{'course.'.$cid.'.domain'},
                   4813: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4814: 		.' '.
                   4815: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4816: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4817:         unless ($status eq 'ok ok') {
                   4818:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4819:                     $uname.' at '.$udom.' for '.
1.109     www      4820: 		    $symb.': '.$status);
1.133     albertel 4821:         }
1.553     albertel 4822: 	&delenv('user.state.'.$cid);
1.109     www      4823:     }
                   4824: }
                   4825: 
1.265     albertel 4826: sub get_scalar {
                   4827:     my ($string,$end) = @_;
                   4828:     my $value;
                   4829:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4830: 	$value = $1;
                   4831:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4832: 	$value = $1;
                   4833:     }
                   4834:     return &unescape($value);
                   4835: }
                   4836: 
                   4837: sub array2str {
                   4838:   my (@array) = @_;
                   4839:   my $result=&arrayref2str(\@array);
                   4840:   $result=~s/^__ARRAY_REF__//;
                   4841:   $result=~s/__END_ARRAY_REF__$//;
                   4842:   return $result;
                   4843: }
                   4844: 
1.204     albertel 4845: sub arrayref2str {
                   4846:   my ($arrayref) = @_;
1.265     albertel 4847:   my $result='__ARRAY_REF__';
1.204     albertel 4848:   foreach my $elem (@$arrayref) {
1.265     albertel 4849:     if(ref($elem) eq 'ARRAY') {
                   4850:       $result.=&arrayref2str($elem).'&';
                   4851:     } elsif(ref($elem) eq 'HASH') {
                   4852:       $result.=&hashref2str($elem).'&';
                   4853:     } elsif(ref($elem)) {
                   4854:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4855:     } else {
                   4856:       $result.=&escape($elem).'&';
                   4857:     }
                   4858:   }
                   4859:   $result=~s/\&$//;
1.265     albertel 4860:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4861:   return $result;
                   4862: }
                   4863: 
1.168     albertel 4864: sub hash2str {
1.204     albertel 4865:   my (%hash) = @_;
                   4866:   my $result=&hashref2str(\%hash);
1.265     albertel 4867:   $result=~s/^__HASH_REF__//;
                   4868:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4869:   return $result;
                   4870: }
                   4871: 
                   4872: sub hashref2str {
                   4873:   my ($hashref)=@_;
1.265     albertel 4874:   my $result='__HASH_REF__';
1.800     albertel 4875:   foreach my $key (sort(keys(%$hashref))) {
                   4876:     if (ref($key) eq 'ARRAY') {
                   4877:       $result.=&arrayref2str($key).'=';
                   4878:     } elsif (ref($key) eq 'HASH') {
                   4879:       $result.=&hashref2str($key).'=';
                   4880:     } elsif (ref($key)) {
1.265     albertel 4881:       $result.='=';
1.800     albertel 4882:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4883:     } else {
1.1132    raeburn  4884: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4885:     }
                   4886: 
1.800     albertel 4887:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4888:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4889:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4890:       $result.=&hashref2str($hashref->{$key}).'&';
                   4891:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4892:        $result.='&';
1.800     albertel 4893:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4894:     } else {
1.800     albertel 4895:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4896:     }
                   4897:   }
1.168     albertel 4898:   $result=~s/\&$//;
1.265     albertel 4899:   $result .= '__END_HASH_REF__';
1.168     albertel 4900:   return $result;
                   4901: }
                   4902: 
                   4903: sub str2hash {
1.265     albertel 4904:     my ($string)=@_;
                   4905:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4906:     return %$hash;
                   4907: }
                   4908: 
                   4909: sub str2hashref {
1.168     albertel 4910:   my ($string) = @_;
1.265     albertel 4911: 
                   4912:   my %hash;
                   4913: 
                   4914:   if($string !~ /^__HASH_REF__/) {
                   4915:       if (! ($string eq '' || !defined($string))) {
                   4916: 	  $hash{'error'}='Not hash reference';
                   4917:       }
                   4918:       return (\%hash, $string);
                   4919:   }
                   4920: 
                   4921:   $string =~ s/^__HASH_REF__//;
                   4922: 
                   4923:   while($string !~ /^__END_HASH_REF__/) {
                   4924:       #key
                   4925:       my $key='';
                   4926:       if($string =~ /^__HASH_REF__/) {
                   4927:           ($key, $string)=&str2hashref($string);
                   4928:           if(defined($key->{'error'})) {
                   4929:               $hash{'error'}='Bad data';
                   4930:               return (\%hash, $string);
                   4931:           }
                   4932:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4933:           ($key, $string)=&str2arrayref($string);
                   4934:           if($key->[0] eq 'Array reference error') {
                   4935:               $hash{'error'}='Bad data';
                   4936:               return (\%hash, $string);
                   4937:           }
                   4938:       } else {
                   4939:           $string =~ s/^(.*?)=//;
1.267     albertel 4940: 	  $key=&unescape($1);
1.265     albertel 4941:       }
                   4942:       $string =~ s/^=//;
                   4943: 
                   4944:       #value
                   4945:       my $value='';
                   4946:       if($string =~ /^__HASH_REF__/) {
                   4947:           ($value, $string)=&str2hashref($string);
                   4948:           if(defined($value->{'error'})) {
                   4949:               $hash{'error'}='Bad data';
                   4950:               return (\%hash, $string);
                   4951:           }
                   4952:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4953:           ($value, $string)=&str2arrayref($string);
                   4954:           if($value->[0] eq 'Array reference error') {
                   4955:               $hash{'error'}='Bad data';
                   4956:               return (\%hash, $string);
                   4957:           }
                   4958:       } else {
                   4959: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4960:       }
                   4961:       $string =~ s/^&//;
                   4962: 
                   4963:       $hash{$key}=$value;
1.204     albertel 4964:   }
1.265     albertel 4965: 
                   4966:   $string =~ s/^__END_HASH_REF__//;
                   4967: 
                   4968:   return (\%hash, $string);
1.204     albertel 4969: }
                   4970: 
                   4971: sub str2array {
1.265     albertel 4972:     my ($string)=@_;
                   4973:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4974:     return @$array;
                   4975: }
                   4976: 
                   4977: sub str2arrayref {
1.204     albertel 4978:   my ($string) = @_;
1.265     albertel 4979:   my @array;
                   4980: 
                   4981:   if($string !~ /^__ARRAY_REF__/) {
                   4982:       if (! ($string eq '' || !defined($string))) {
                   4983: 	  $array[0]='Array reference error';
                   4984:       }
                   4985:       return (\@array, $string);
                   4986:   }
                   4987: 
                   4988:   $string =~ s/^__ARRAY_REF__//;
                   4989: 
                   4990:   while($string !~ /^__END_ARRAY_REF__/) {
                   4991:       my $value='';
                   4992:       if($string =~ /^__HASH_REF__/) {
                   4993:           ($value, $string)=&str2hashref($string);
                   4994:           if(defined($value->{'error'})) {
                   4995:               $array[0] ='Array reference error';
                   4996:               return (\@array, $string);
                   4997:           }
                   4998:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4999:           ($value, $string)=&str2arrayref($string);
                   5000:           if($value->[0] eq 'Array reference error') {
                   5001:               $array[0] ='Array reference error';
                   5002:               return (\@array, $string);
                   5003:           }
                   5004:       } else {
                   5005: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5006:       }
                   5007:       $string =~ s/^&//;
                   5008: 
                   5009:       push(@array, $value);
1.191     harris41 5010:   }
1.265     albertel 5011: 
                   5012:   $string =~ s/^__END_ARRAY_REF__//;
                   5013: 
                   5014:   return (\@array, $string);
1.168     albertel 5015: }
                   5016: 
1.167     albertel 5017: # -------------------------------------------------------------------Temp Store
                   5018: 
1.168     albertel 5019: sub tmpreset {
                   5020:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5021:   if (!$symb) {
                   5022:     $symb=&symbread();
1.620     albertel 5023:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5024:   }
                   5025:   $symb=escape($symb);
                   5026: 
1.620     albertel 5027:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5028:   $namespace=~s/\//\_/g;
                   5029:   $namespace=~s/\W//g;
                   5030: 
1.620     albertel 5031:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5032:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5033:   if ($domain eq 'public' && $stuname eq 'public') {
                   5034:       $stuname=$ENV{'REMOTE_ADDR'};
                   5035:   }
1.1117    foxr     5036:   my $path=LONCAPA::tempdir();
1.168     albertel 5037:   my %hash;
                   5038:   if (tie(%hash,'GDBM_File',
                   5039: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5040: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5041:     foreach my $key (keys(%hash)) {
1.180     albertel 5042:       if ($key=~ /:$symb/) {
1.168     albertel 5043: 	delete($hash{$key});
                   5044:       }
                   5045:     }
                   5046:   }
                   5047: }
                   5048: 
1.167     albertel 5049: sub tmpstore {
1.168     albertel 5050:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5051: 
                   5052:   if (!$symb) {
                   5053:     $symb=&symbread();
1.620     albertel 5054:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5055:   }
                   5056:   $symb=escape($symb);
                   5057: 
                   5058:   if (!$namespace) {
                   5059:     # I don't think we would ever want to store this for a course.
                   5060:     # it seems this will only be used if we don't have a course.
1.620     albertel 5061:     #$namespace=$env{'request.course.id'};
1.168     albertel 5062:     #if (!$namespace) {
1.620     albertel 5063:       $namespace=$env{'request.state'};
1.168     albertel 5064:     #}
                   5065:   }
                   5066:   $namespace=~s/\//\_/g;
                   5067:   $namespace=~s/\W//g;
1.620     albertel 5068:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5069:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5070:   if ($domain eq 'public' && $stuname eq 'public') {
                   5071:       $stuname=$ENV{'REMOTE_ADDR'};
                   5072:   }
1.168     albertel 5073:   my $now=time;
                   5074:   my %hash;
1.1117    foxr     5075:   my $path=LONCAPA::tempdir();
1.168     albertel 5076:   if (tie(%hash,'GDBM_File',
                   5077: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5078: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5079:     $hash{"version:$symb"}++;
                   5080:     my $version=$hash{"version:$symb"};
                   5081:     my $allkeys=''; 
                   5082:     foreach my $key (keys(%$storehash)) {
                   5083:       $allkeys.=$key.':';
1.591     albertel 5084:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5085:     }
                   5086:     $hash{"$version:$symb:timestamp"}=$now;
                   5087:     $allkeys.='timestamp';
                   5088:     $hash{"$version:keys:$symb"}=$allkeys;
                   5089:     if (untie(%hash)) {
                   5090:       return 'ok';
                   5091:     } else {
                   5092:       return "error:$!";
                   5093:     }
                   5094:   } else {
                   5095:     return "error:$!";
                   5096:   }
                   5097: }
1.167     albertel 5098: 
1.168     albertel 5099: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5100: 
1.168     albertel 5101: sub tmprestore {
                   5102:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5103: 
1.168     albertel 5104:   if (!$symb) {
                   5105:     $symb=&symbread();
1.620     albertel 5106:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5107:   }
                   5108:   $symb=escape($symb);
                   5109: 
1.620     albertel 5110:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5111: 
1.620     albertel 5112:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5113:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5114:   if ($domain eq 'public' && $stuname eq 'public') {
                   5115:       $stuname=$ENV{'REMOTE_ADDR'};
                   5116:   }
1.168     albertel 5117:   my %returnhash;
                   5118:   $namespace=~s/\//\_/g;
                   5119:   $namespace=~s/\W//g;
                   5120:   my %hash;
1.1117    foxr     5121:   my $path=LONCAPA::tempdir();
1.168     albertel 5122:   if (tie(%hash,'GDBM_File',
                   5123: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5124: 	  &GDBM_READER(),0640)) {
1.168     albertel 5125:     my $version=$hash{"version:$symb"};
                   5126:     $returnhash{'version'}=$version;
                   5127:     my $scope;
                   5128:     for ($scope=1;$scope<=$version;$scope++) {
                   5129:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5130:       my @keys=split(/:/,$vkeys);
                   5131:       my $key;
                   5132:       $returnhash{"$scope:keys"}=$vkeys;
                   5133:       foreach $key (@keys) {
1.591     albertel 5134: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5135: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5136:       }
                   5137:     }
1.168     albertel 5138:     if (!(untie(%hash))) {
                   5139:       return "error:$!";
                   5140:     }
                   5141:   } else {
                   5142:     return "error:$!";
                   5143:   }
                   5144:   return %returnhash;
1.167     albertel 5145: }
                   5146: 
1.9       www      5147: # ----------------------------------------------------------------------- Store
                   5148: 
                   5149: sub store {
1.1269    raeburn  5150:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5151:     my $home='';
                   5152: 
1.168     albertel 5153:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5154: 
1.213     www      5155:     $symb=&symbclean($symb);
1.122     albertel 5156:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5157: 
1.620     albertel 5158:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5159:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5160: 
                   5161:     &devalidate($symb,$stuname,$domain);
1.109     www      5162: 
                   5163:     $symb=escape($symb);
1.187     www      5164:     if (!$namespace) { 
1.620     albertel 5165:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5166:           return ''; 
                   5167:        } 
                   5168:     }
1.620     albertel 5169:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5170: 
                   5171:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5172:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5173: 
1.12      www      5174:     my $namevalue='';
1.800     albertel 5175:     foreach my $key (keys(%$storehash)) {
                   5176:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5177:     }
1.12      www      5178:     $namevalue=~s/\&$//;
1.187     www      5179:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  5180:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5181: }
                   5182: 
1.47      www      5183: # -------------------------------------------------------------- Critical Store
                   5184: 
                   5185: sub cstore {
1.1269    raeburn  5186:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5187:     my $home='';
                   5188: 
1.168     albertel 5189:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5190: 
1.213     www      5191:     $symb=&symbclean($symb);
1.122     albertel 5192:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5193: 
1.620     albertel 5194:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5195:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5196: 
                   5197:     &devalidate($symb,$stuname,$domain);
1.109     www      5198: 
                   5199:     $symb=escape($symb);
1.187     www      5200:     if (!$namespace) { 
1.620     albertel 5201:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5202:           return ''; 
                   5203:        } 
                   5204:     }
1.620     albertel 5205:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5206: 
                   5207:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5208:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5209: 
1.47      www      5210:     my $namevalue='';
1.800     albertel 5211:     foreach my $key (keys(%$storehash)) {
                   5212:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5213:     }
1.47      www      5214:     $namevalue=~s/\&$//;
1.187     www      5215:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5216:     return critical
1.1269    raeburn  5217:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5218: }
                   5219: 
1.9       www      5220: # --------------------------------------------------------------------- Restore
                   5221: 
                   5222: sub restore {
1.124     www      5223:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5224:     my $home='';
                   5225: 
1.168     albertel 5226:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5227: 
1.122     albertel 5228:     if (!$symb) {
1.1224    raeburn  5229:         return if ($namespace eq 'courserequests');
                   5230:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5231:     } else {
1.1224    raeburn  5232:         unless ($namespace eq 'courserequests') {
                   5233:             $symb=&escape(&symbclean($symb));
                   5234:         }
1.122     albertel 5235:     }
1.188     www      5236:     if (!$namespace) { 
1.620     albertel 5237:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5238:           return ''; 
                   5239:        } 
                   5240:     }
1.620     albertel 5241:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5242:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5243:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5244:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5245: 
1.12      www      5246:     my %returnhash=();
1.800     albertel 5247:     foreach my $line (split(/\&/,$answer)) {
                   5248: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5249:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5250:     }
1.75      www      5251:     my $version;
                   5252:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5253:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5254:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5255:        }
1.75      www      5256:     }
1.13      www      5257:     return %returnhash;
1.34      www      5258: }
                   5259: 
                   5260: # ---------------------------------------------------------- Course Description
1.1118    foxr     5261: #
                   5262: #  
1.34      www      5263: 
                   5264: sub coursedescription {
1.731     albertel 5265:     my ($courseid,$args)=@_;
1.34      www      5266:     $courseid=~s/^\///;
1.49      www      5267:     $courseid=~s/\_/\//g;
1.34      www      5268:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5269:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5270:     my $normalid=$cdomain.'_'.$cnum;
                   5271:     # need to always cache even if we get errors otherwise we keep 
                   5272:     # trying and trying and trying to get the course description.
                   5273:     my %envhash=();
                   5274:     my %returnhash=();
1.731     albertel 5275:     
                   5276:     my $expiretime=600;
                   5277:     if ($env{'request.course.id'} eq $normalid) {
                   5278: 	$expiretime=120;
                   5279:     }
                   5280: 
                   5281:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5282:     if (!$args->{'freshen_cache'}
                   5283: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5284: 	foreach my $key (keys(%env)) {
                   5285: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5286: 	    my ($setting) = $1;
                   5287: 	    $returnhash{$setting} = $env{$key};
                   5288: 	}
                   5289: 	return %returnhash;
                   5290:     }
                   5291: 
1.1118    foxr     5292:     # get the data again
                   5293: 
1.731     albertel 5294:     if (!$args->{'one_time'}) {
                   5295: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5296:     }
1.811     albertel 5297: 
1.34      www      5298:     if ($chome ne 'no_host') {
1.302     albertel 5299:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5300:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5301: 	   my $username = $env{'user.name'}; # Defult username
                   5302: 	   if(defined $args->{'user'}) {
                   5303: 	       $username = $args->{'user'};
                   5304: 	   }
1.129     albertel 5305:            $returnhash{'home'}= $chome;
                   5306: 	   $returnhash{'domain'} = $cdomain;
                   5307: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5308:            if (!defined($returnhash{'type'})) {
                   5309:                $returnhash{'type'} = 'Course';
                   5310:            }
1.130     albertel 5311:            while (my ($name,$value) = each %returnhash) {
1.53      www      5312:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5313:            }
1.270     www      5314:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5315:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5316: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5317:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5318:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5319:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5320:        }
                   5321:     }
1.731     albertel 5322:     if (!$args->{'one_time'}) {
1.949     raeburn  5323: 	&appenv(\%envhash);
1.731     albertel 5324:     }
1.302     albertel 5325:     return %returnhash;
1.461     www      5326: }
                   5327: 
1.1080    raeburn  5328: sub update_released_required {
                   5329:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5330:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5331:         $cid = $env{'request.course.id'};
                   5332:         $cdom = $env{'course.'.$cid.'.domain'};
                   5333:         $cnum = $env{'course.'.$cid.'.num'};
                   5334:         $chome = $env{'course.'.$cid.'.home'};
                   5335:     }
                   5336:     if ($needsrelease) {
                   5337:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5338:         my $needsupdate;
                   5339:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5340:             $needsupdate = 1;
                   5341:         } else {
                   5342:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5343:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5344:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5345:                 $needsupdate = 1;
                   5346:             }
                   5347:         }
                   5348:         if ($needsupdate) {
                   5349:             my %needshash = (
                   5350:                              'internal.releaserequired' => $needsrelease,
                   5351:                             );
                   5352:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5353:             if ($putresult eq 'ok') {
                   5354:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5355:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5356:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5357:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5358:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5359:                 }
                   5360:             }
                   5361:         }
                   5362:     }
                   5363:     return;
                   5364: }
                   5365: 
1.461     www      5366: # -------------------------------------------------See if a user is privileged
                   5367: 
                   5368: sub privileged {
1.1219    raeburn  5369:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5370:     my $now = time;
1.1219    raeburn  5371:     my $roles;
                   5372:     if (ref($possroles) eq 'ARRAY') {
                   5373:         $roles = $possroles; 
                   5374:     } else {
                   5375:         $roles = ['dc','su'];
                   5376:     }
                   5377:     if (ref($possdomains) eq 'ARRAY') {
                   5378:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5379:         foreach my $dom (@{$possdomains}) {
                   5380:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5381:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5382:                 foreach my $role (@{$roles}) {
                   5383:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5384:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5385:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5386:                             return 1 unless (($end && $end < $now) ||
                   5387:                                              ($start && $start > $now));
                   5388:                         }
                   5389:                     }
                   5390:                 }
                   5391:             }
                   5392:         }
                   5393:     } else {
                   5394:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5395:         my $now = time;
1.1170    droeschl 5396: 
1.1275    musolffc 5397:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5398:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5399:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5400:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5401:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5402:             }
1.1219    raeburn  5403:         }
                   5404:     }
                   5405:     return 0;
                   5406: }
1.1170    droeschl 5407: 
1.1219    raeburn  5408: sub privileged_by_domain {
                   5409:     my ($domains,$roles) = @_;
                   5410:     my %privileged = ();
                   5411:     my $cachetime = 60*60*24;
                   5412:     my $now = time;
                   5413:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5414:         return %privileged;
                   5415:     }
                   5416:     foreach my $dom (@{$domains}) {
                   5417:         next if (ref($privileged{$dom}) eq 'HASH');
                   5418:         my $needroles;
                   5419:         foreach my $role (@{$roles}) {
                   5420:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5421:             if (defined($cached)) {
                   5422:                 if (ref($result) eq 'HASH') {
                   5423:                     $privileged{$dom}{$role} = $result;
                   5424:                 }
                   5425:             } else {
                   5426:                 $needroles = 1;
                   5427:             }
                   5428:         }
                   5429:         if ($needroles) {
                   5430:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5431:             $privileged{$dom} = {};
                   5432:             foreach my $server (keys(%dompersonnel)) {
                   5433:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5434:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5435:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5436:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5437:                         next if ($end && $end < $now);
                   5438:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5439:                             $dompersonnel{$server}{$item};
                   5440:                     }
                   5441:                 }
                   5442:             }
                   5443:             if (ref($privileged{$dom}) eq 'HASH') {
                   5444:                 foreach my $role (@{$roles}) {
                   5445:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5446:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5447:                     } else {
                   5448:                         my %hash = ();
                   5449:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5450:                     }
                   5451:                 }
                   5452:             }
                   5453:         }
                   5454:     }
                   5455:     return %privileged;
1.9       www      5456: }
1.1       albertel 5457: 
1.103     harris41 5458: # -------------------------------------------------------- Get user privileges
1.11      www      5459: 
                   5460: sub rolesinit {
1.1169    droeschl 5461:     my ($domain, $username) = @_;
                   5462:     my %userroles = ('user.login.time' => time);
                   5463:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5464: 
                   5465:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5466:     # also, blocking can be triggered by an activating timer
                   5467:     # it's saved in the user's %env.
                   5468:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5469:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5470:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5471:         %timerintchk, %timerintenv);
                   5472: 
1.1162    raeburn  5473:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5474:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5475:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5476:     }
1.1169    droeschl 5477: 
1.1162    raeburn  5478:     foreach my $key (keys(%timerinterval)) {
                   5479:         my ($cid,$rest) = split(/\0/,$key);
                   5480:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5481:     }
1.1169    droeschl 5482: 
1.11      www      5483:     my %allroles=();
1.1162    raeburn  5484:     my %allgroups=();
1.11      www      5485: 
1.1274    raeburn  5486:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5487:         my $role = $rolesdump{$area};
                   5488:         $area =~ s/\_\w\w$//;
                   5489: 
                   5490:         my ($trole, $tend, $tstart, $group_privs);
                   5491: 
                   5492:         if ($role =~ /^cr/) {
                   5493:         # Custom role, defined by a user 
                   5494:         # e.g., user.role.cr/msu/smith/mynewrole
                   5495:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5496:                 $trole = $1;
                   5497:                 ($tend, $tstart) = split('_', $2);
                   5498:             } else {
                   5499:                 $trole = $role;
                   5500:             }
                   5501:         } elsif ($role =~ m|^gr/|) {
                   5502:         # Role of member in a group, defined within a course/community
                   5503:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5504:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5505:             next if $tstart eq '-1';
                   5506:             ($trole, $group_privs) = split(/\//, $trole);
                   5507:             $group_privs = &unescape($group_privs);
                   5508:         } else {
                   5509:         # Just a normal role, defined in roles.tab
                   5510:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5511:         }
                   5512: 
                   5513:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5514:                  $username);
                   5515:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5516: 
                   5517:         # role expired or not available yet?
                   5518:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5519:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5520: 
                   5521:         next if $area eq '' or $trole eq '';
                   5522: 
                   5523:         my $spec = "$trole.$area";
                   5524:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5525: 
                   5526:         if ($trole =~ /^cr\//) {
                   5527:         # Custom role, defined by a user
                   5528:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5529:         } elsif ($trole eq 'gr') {
                   5530:         # Role of a member in a group, defined within a course/community
                   5531:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5532:             next;
                   5533:         } else {
                   5534:         # Normal role, defined in roles.tab
                   5535:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5536:         }
                   5537: 
                   5538:         my $cid = $tdomain.'_'.$trest;
                   5539:         unless ($firstaccchk{$cid}) {
                   5540:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5541:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5542:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5543:                         $coursetimerstarts{$cid}{$item}; 
                   5544:                 }
                   5545:             }
                   5546:             $firstaccchk{$cid} = 1;
                   5547:         }
                   5548:         unless ($timerintchk{$cid}) {
                   5549:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5550:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5551:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5552:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5553:                 }
1.12      www      5554:             }
1.1169    droeschl 5555:             $timerintchk{$cid} = 1;
1.191     harris41 5556:         }
1.11      www      5557:     }
1.1169    droeschl 5558: 
                   5559:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5560:         \%allroles, \%allgroups);
                   5561:     $env{'user.adv'} = $userroles{'user.adv'};
                   5562: 
1.1162    raeburn  5563:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5564: }
                   5565: 
1.567     raeburn  5566: sub set_arearole {
1.1215    raeburn  5567:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5568:     unless ($nolog) {
1.567     raeburn  5569: # log the associated role with the area
1.1215    raeburn  5570:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5571:     }
1.743     albertel 5572:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5573: }
                   5574: 
                   5575: sub custom_roleprivs {
                   5576:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5577:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  5578:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5579:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5580:         my ($rdummy,$roledef)=
                   5581:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5582:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5583:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5584:             if (defined($syspriv)) {
1.1043    raeburn  5585:                 if ($trest =~ /^$match_community$/) {
                   5586:                     $syspriv =~ s/bre\&S//; 
                   5587:                 }
1.567     raeburn  5588:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5589:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5590:             }
                   5591:             if ($tdomain ne '') {
                   5592:                 if (defined($dompriv)) {
                   5593:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5594:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5595:                 }
                   5596:                 if (($trest ne '') && (defined($coursepriv))) {
                   5597:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5598:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5599:                 }
                   5600:             }
                   5601:         }
                   5602:     }
                   5603: }
                   5604: 
1.678     raeburn  5605: sub group_roleprivs {
                   5606:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5607:     my $access = 1;
                   5608:     my $now = time;
                   5609:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5610:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5611:     if ($access) {
1.811     albertel 5612:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5613:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5614:     }
                   5615: }
1.567     raeburn  5616: 
                   5617: sub standard_roleprivs {
                   5618:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5619:     if (defined($pr{$trole.':s'})) {
                   5620:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5621:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5622:     }
                   5623:     if ($tdomain ne '') {
                   5624:         if (defined($pr{$trole.':d'})) {
                   5625:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5626:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5627:         }
                   5628:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5629:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5630:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5631:         }
                   5632:     }
                   5633: }
                   5634: 
                   5635: sub set_userprivs {
1.1064    raeburn  5636:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5637:     my $author=0;
                   5638:     my $adv=0;
1.678     raeburn  5639:     my %grouproles = ();
                   5640:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5641:         my @groupkeys; 
1.1000    raeburn  5642:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5643:             push(@groupkeys,$role);
                   5644:         }
                   5645:         if (ref($groups_roles) eq 'HASH') {
                   5646:             foreach my $key (keys(%{$groups_roles})) {
                   5647:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5648:                     push(@groupkeys,$key);
                   5649:                 }
                   5650:             }
                   5651:         }
                   5652:         if (@groupkeys > 0) {
                   5653:             foreach my $role (@groupkeys) {
                   5654:                 my ($trole,$area,$sec,$extendedarea);
                   5655:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5656:                     $trole = $1;
                   5657:                     $area = $2;
                   5658:                     $sec = $3;
                   5659:                     $extendedarea = $area.$sec;
                   5660:                     if (exists($$allgroups{$area})) {
                   5661:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5662:                             my $spec = $trole.'.'.$extendedarea;
                   5663:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5664:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5665:                         }
1.678     raeburn  5666:                     }
                   5667:                 }
                   5668:             }
                   5669:         }
                   5670:     }
1.800     albertel 5671:     foreach my $group (keys(%grouproles)) {
                   5672:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5673:     }
1.800     albertel 5674:     foreach my $role (keys(%{$allroles})) {
                   5675:         my %thesepriv;
1.941     raeburn  5676:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5677:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5678:             if ($item ne '') {
                   5679:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5680:                 if ($restrictions eq '') {
                   5681:                     $thesepriv{$privilege}='F';
                   5682:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5683:                     $thesepriv{$privilege}.=$restrictions;
                   5684:                 }
                   5685:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5686:             }
                   5687:         }
                   5688:         my $thesestr='';
1.1104    raeburn  5689:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5690: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5691: 	}
                   5692:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5693:     }
                   5694:     return ($author,$adv);
                   5695: }
                   5696: 
1.994     raeburn  5697: sub role_status {
1.1104    raeburn  5698:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5699:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  5700:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5701:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5702:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  5703:             $$where = '/'.$two;
1.994     raeburn  5704:             $$trolecode=$$role.'.'.$$where;
                   5705:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5706:             $$tstatus='is';
1.1104    raeburn  5707:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5708:                 $$tstatus='future';
1.1034    raeburn  5709:                 if ($$tstart<$now) {
                   5710:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5711:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5712:                             my (%allroles,%allgroups,$group_privs,
                   5713:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5714:                             my %userroles = (
                   5715:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5716:                             );
1.1064    raeburn  5717:                             @rolecodes = ('cm'); 
1.1002    raeburn  5718:                             my $spec=$$role.'.'.$$where;
                   5719:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5720:                             if ($$role =~ /^cr\//) {
                   5721:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5722:                                 push(@rolecodes,'cr');
1.1002    raeburn  5723:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5724:                                 push(@rolecodes,$$role);
1.1002    raeburn  5725:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5726:                                                     $env{'user.name'});
1.1064    raeburn  5727:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5728:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5729:                                 $group_privs = &unescape($group_privs);
                   5730:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5731:                                 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  5732:                                 &get_groups_roles($tdomain,$trest,
                   5733:                                                   \%course_roles,\@rolecodes,
                   5734:                                                   \%groups_roles);
1.1002    raeburn  5735:                             } else {
1.1064    raeburn  5736:                                 push(@rolecodes,$$role);
1.1002    raeburn  5737:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5738:                             }
1.1064    raeburn  5739:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5740:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5741:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5742:                         }
                   5743:                     }
1.1034    raeburn  5744:                     $$tstatus = 'is';
1.1002    raeburn  5745:                 }
1.994     raeburn  5746:             }
                   5747:             if ($$tend) {
1.1104    raeburn  5748:                 if ($$tend<$update) {
1.994     raeburn  5749:                     $$tstatus='expired';
                   5750:                 } elsif ($$tend<$now) {
                   5751:                     $$tstatus='will_not';
                   5752:                 }
                   5753:             }
                   5754:         }
                   5755:     }
                   5756: }
                   5757: 
1.1104    raeburn  5758: sub get_groups_roles {
                   5759:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5760:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5761:                   (ref($rolecodes) eq 'ARRAY') && 
                   5762:                   (ref($groups_roles) eq 'HASH')); 
                   5763:     if (keys(%{$cdom_courseroles}) > 0) {
                   5764:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5765:         if ($cdom ne '' && $cnum ne '') {
                   5766:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5767:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5768:                     my $crsrole = $1;
                   5769:                     my $crssec = $2;
                   5770:                     if ($crsrole =~ /^cr/) {
                   5771:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5772:                             push(@{$rolecodes},'cr');
                   5773:                         }
                   5774:                     } else {
                   5775:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5776:                             push(@{$rolecodes},$crsrole);
                   5777:                         }
                   5778:                     }
                   5779:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5780:                     if ($crssec ne '') {
                   5781:                         $rolekey .= "/$crssec";
                   5782:                     }
                   5783:                     $rolekey .= './';
                   5784:                     $groups_roles->{$rolekey} = $rolecodes;
                   5785:                 }
                   5786:             }
                   5787:         }
                   5788:     }
                   5789:     return;
                   5790: }
                   5791: 
                   5792: sub delete_env_groupprivs {
                   5793:     my ($where,$courseroles,$possroles) = @_;
                   5794:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5795:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5796:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5797:         %{$courseroles->{$udom}} =
                   5798:             &get_my_roles('','','userroles',['active'],
                   5799:                           $possroles,[$udom],1);
                   5800:     }
                   5801:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5802:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5803:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5804:             my $area = '/'.$cdom.'/'.$cnum;
                   5805:             my $privkey = "user.priv.$crsrole.$area";
                   5806:             if ($crssec ne '') {
                   5807:                 $privkey .= '/'.$crssec;
                   5808:             }
                   5809:             $privkey .= ".$area/$group";
                   5810:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5811:         }
                   5812:     }
                   5813:     return;
                   5814: }
                   5815: 
1.994     raeburn  5816: sub check_adhoc_privs {
1.1104    raeburn  5817:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5818:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185    raeburn  5819:     my $setprivs;
1.994     raeburn  5820:     if ($env{$cckey}) {
                   5821:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5822:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5823:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5824:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5825:             $setprivs = 1;
1.994     raeburn  5826:         }
                   5827:     } else {
1.1088    raeburn  5828:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5829:         $setprivs = 1;
1.994     raeburn  5830:     }
1.1185    raeburn  5831:     return $setprivs;
1.994     raeburn  5832: }
                   5833: 
                   5834: sub set_adhoc_privileges {
                   5835: # role can be cc or ca
1.1088    raeburn  5836:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5837:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5838:     my $spec = $role.'.'.$area;
                   5839:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  5840:                                   $env{'user.name'},1);
1.994     raeburn  5841:     my %ccrole = ();
                   5842:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5843:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5844:     &appenv(\%userroles,[$role,'cm']);
                   5845:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5846:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5847:         &appenv( {'request.role'        => $spec,
                   5848:                   'request.role.domain' => $dcdom,
                   5849:                   'request.course.sec'  => ''
                   5850:                  }
                   5851:                );
                   5852:         my $tadv=0;
                   5853:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5854:         &appenv({'request.role.adv'    => $tadv});
                   5855:     }
1.994     raeburn  5856: }
                   5857: 
1.12      www      5858: # --------------------------------------------------------------- get interface
                   5859: 
                   5860: sub get {
1.131     albertel 5861:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5862:    my $items='';
1.800     albertel 5863:    foreach my $item (@$storearr) {
                   5864:        $items.=&escape($item).'&';
1.191     harris41 5865:    }
1.12      www      5866:    $items=~s/\&$//;
1.620     albertel 5867:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5868:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5869:    my $uhome=&homeserver($uname,$udomain);
                   5870: 
1.133     albertel 5871:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5872:    my @pairs=split(/\&/,$rep);
1.273     albertel 5873:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5874:      return @pairs;
                   5875:    }
1.15      www      5876:    my %returnhash=();
1.42      www      5877:    my $i=0;
1.800     albertel 5878:    foreach my $item (@$storearr) {
                   5879:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5880:       $i++;
1.191     harris41 5881:    }
1.15      www      5882:    return %returnhash;
1.27      www      5883: }
                   5884: 
                   5885: # --------------------------------------------------------------- del interface
                   5886: 
                   5887: sub del {
1.133     albertel 5888:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5889:    my $items='';
1.800     albertel 5890:    foreach my $item (@$storearr) {
                   5891:        $items.=&escape($item).'&';
1.191     harris41 5892:    }
1.984     neumanie 5893: 
1.27      www      5894:    $items=~s/\&$//;
1.620     albertel 5895:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5896:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5897:    my $uhome=&homeserver($uname,$udomain);
                   5898:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5899: }
                   5900: 
                   5901: # -------------------------------------------------------------- dump interface
                   5902: 
1.1180    droeschl 5903: sub unserialize {
                   5904:     my ($rep, $escapedkeys) = @_;
                   5905: 
                   5906:     return {} if $rep =~ /^error/;
                   5907: 
                   5908:     my %returnhash=();
1.1252    raeburn  5909: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 5910: 	    my ($key, $value) = split(/=/, $item, 2);
                   5911: 	    $key = unescape($key) unless $escapedkeys;
                   5912: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  5913: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 5914: 	}
                   5915:     #return %returnhash;
                   5916:     return \%returnhash;
                   5917: }        
                   5918: 
                   5919: # see Lond::dump_with_regexp
                   5920: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5921: sub dump {
1.1180    droeschl 5922:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5923:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5924:     if (!$uname) { $uname=$env{'user.name'}; }
                   5925:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5926: 
1.1266    raeburn  5927:     if ($regexp) {
                   5928:         $regexp=&escape($regexp);
                   5929:     } else {
                   5930:         $regexp='.';
                   5931:     }
1.1180    droeschl 5932:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   5933:         # user is hosted on this machine
1.1266    raeburn  5934:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  5935:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 5936:         return %{unserialize($reply, $escapedkeys)};
                   5937:     }
1.1166    raeburn  5938:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5939:     my @pairs=split(/\&/,$rep);
                   5940:     my %returnhash=();
1.1098    foxr     5941:     if (!($rep =~ /^error/ )) {
                   5942: 	foreach my $item (@pairs) {
                   5943: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 5944:         $key = unescape($key) unless $escapedkeys;
                   5945:         #$key = &unescape($key);
1.1098    foxr     5946: 	    next if ($key =~ /^error: 2 /);
                   5947: 	    $returnhash{$key}=&thaw_unescape($value);
                   5948: 	}
1.755     albertel 5949:     }
                   5950:     return %returnhash;
1.407     www      5951: }
                   5952: 
1.1098    foxr     5953: 
1.717     albertel 5954: # --------------------------------------------------------- dumpstore interface
                   5955: 
                   5956: sub dumpstore {
                   5957:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 5958:    # same as dump but keys must be escaped. They may contain colon separated
                   5959:    # lists of values that may themself contain colons (e.g. symbs).
                   5960:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5961: }
                   5962: 
1.407     www      5963: # -------------------------------------------------------------- keys interface
                   5964: 
                   5965: sub getkeys {
                   5966:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5967:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5968:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5969:    my $uhome=&homeserver($uname,$udomain);
                   5970:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5971:    my @keyarray=();
1.800     albertel 5972:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5973:       next if ($key =~ /^error: 2 /);
1.800     albertel 5974:       push(@keyarray,&unescape($key));
1.407     www      5975:    }
                   5976:    return @keyarray;
1.318     matthew  5977: }
                   5978: 
1.319     matthew  5979: # --------------------------------------------------------------- currentdump
                   5980: sub currentdump {
1.328     matthew  5981:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5982:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5983:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5984:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5985:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 5986:    my $rep;
                   5987: 
                   5988:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5989:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   5990:                    $courseid)));
                   5991:    } else {
                   5992:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5993:    }
                   5994: 
1.318     matthew  5995:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5996:    #
1.318     matthew  5997:    my %returnhash=();
1.319     matthew  5998:    #
                   5999:    if ($rep eq "unknown_cmd") { 
                   6000:        # an old lond will not know currentdump
                   6001:        # Do a dump and make it look like a currentdump
1.822     albertel 6002:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6003:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6004:        my %hash = @tmp;
                   6005:        @tmp=();
1.424     matthew  6006:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6007:    } else {
                   6008:        my @pairs=split(/\&/,$rep);
1.800     albertel 6009:        foreach my $pair (@pairs) {
                   6010:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6011:            my ($symb,$param) = split(/:/,$key);
                   6012:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6013:                                                         &thaw_unescape($value);
1.319     matthew  6014:        }
1.191     harris41 6015:    }
1.12      www      6016:    return %returnhash;
1.424     matthew  6017: }
                   6018: 
                   6019: sub convert_dump_to_currentdump{
                   6020:     my %hash = %{shift()};
                   6021:     my %returnhash;
                   6022:     # Code ripped from lond, essentially.  The only difference
                   6023:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6024:     # we might run in to problems with parameter names =~ /^v\./
                   6025:     while (my ($key,$value) = each(%hash)) {
                   6026:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6027: 	$symb  = &unescape($symb);
                   6028: 	$param = &unescape($param);
1.424     matthew  6029:         next if ($v eq 'version' || $symb eq 'keys');
                   6030:         next if (exists($returnhash{$symb}) &&
                   6031:                  exists($returnhash{$symb}->{$param}) &&
                   6032:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6033:         $returnhash{$symb}->{$param}=$value;
                   6034:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6035:     }
                   6036:     #
                   6037:     # Remove all of the keys in the hashes which keep track of
                   6038:     # the version of the parameter.
                   6039:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6040:         # use a foreach because we are going to delete from the hash.
                   6041:         foreach my $key (keys(%$param_hash)) {
                   6042:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6043:         }
                   6044:     }
                   6045:     return \%returnhash;
1.12      www      6046: }
                   6047: 
1.627     albertel 6048: # ------------------------------------------------------ critical inc interface
                   6049: 
                   6050: sub cinc {
                   6051:     return &inc(@_,'critical');
                   6052: }
                   6053: 
1.449     matthew  6054: # --------------------------------------------------------------- inc interface
                   6055: 
                   6056: sub inc {
1.627     albertel 6057:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6058:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6059:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6060:     my $uhome=&homeserver($uname,$udomain);
                   6061:     my $items='';
                   6062:     if (! ref($store)) {
                   6063:         # got a single value, so use that instead
                   6064:         $items = &escape($store).'=&';
                   6065:     } elsif (ref($store) eq 'SCALAR') {
                   6066:         $items = &escape($$store).'=&';        
                   6067:     } elsif (ref($store) eq 'ARRAY') {
                   6068:         $items = join('=&',map {&escape($_);} @{$store});
                   6069:     } elsif (ref($store) eq 'HASH') {
                   6070:         while (my($key,$value) = each(%{$store})) {
                   6071:             $items.= &escape($key).'='.&escape($value).'&';
                   6072:         }
                   6073:     }
                   6074:     $items=~s/\&$//;
1.627     albertel 6075:     if ($critical) {
                   6076: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6077:     } else {
                   6078: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6079:     }
1.449     matthew  6080: }
                   6081: 
1.12      www      6082: # --------------------------------------------------------------- put interface
                   6083: 
                   6084: sub put {
1.134     albertel 6085:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6086:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6087:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6088:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6089:    my $items='';
1.800     albertel 6090:    foreach my $item (keys(%$storehash)) {
                   6091:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6092:    }
1.12      www      6093:    $items=~s/\&$//;
1.134     albertel 6094:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6095: }
                   6096: 
1.631     albertel 6097: # ------------------------------------------------------------ newput interface
                   6098: 
                   6099: sub newput {
                   6100:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6101:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6102:    if (!$uname) { $uname=$env{'user.name'}; }
                   6103:    my $uhome=&homeserver($uname,$udomain);
                   6104:    my $items='';
                   6105:    foreach my $key (keys(%$storehash)) {
                   6106:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6107:    }
                   6108:    $items=~s/\&$//;
                   6109:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6110: }
                   6111: 
                   6112: # ---------------------------------------------------------  putstore interface
                   6113: 
1.524     raeburn  6114: sub putstore {
1.1269    raeburn  6115:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6116:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6117:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6118:    my $uhome=&homeserver($uname,$udomain);
                   6119:    my $items='';
1.715     albertel 6120:    foreach my $key (keys(%$storehash)) {
                   6121:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6122:    }
1.715     albertel 6123:    $items=~s/\&$//;
1.716     albertel 6124:    my $esc_symb=&escape($symb);
                   6125:    my $esc_v=&escape($version);
1.715     albertel 6126:    my $reply =
1.716     albertel 6127:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6128: 	      $uhome);
1.1269    raeburn  6129:    if (($tolog) && ($reply eq 'ok')) {
                   6130:        my $namevalue='';
                   6131:        foreach my $key (keys(%{$storehash})) {
                   6132:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6133:        }
                   6134:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6135:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6136:                      '&version='.$esc_v.
                   6137:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6138:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6139:    }
1.715     albertel 6140:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6141:        # gfall back to way things use to be done
1.715     albertel 6142:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6143: 			    $uname);
1.524     raeburn  6144:    }
1.715     albertel 6145:    return $reply;
                   6146: }
                   6147: 
                   6148: sub old_putstore {
1.716     albertel 6149:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6150:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6151:     if (!$uname) { $uname=$env{'user.name'}; }
                   6152:     my $uhome=&homeserver($uname,$udomain);
                   6153:     my %newstorehash;
1.800     albertel 6154:     foreach my $item (keys(%$storehash)) {
                   6155: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6156: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6157:     }
                   6158:     my $items='';
                   6159:     my %allitems = ();
1.800     albertel 6160:     foreach my $item (keys(%newstorehash)) {
                   6161: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6162: 	    my $key = $1.':keys:'.$2;
                   6163: 	    $allitems{$key} .= $3.':';
                   6164: 	}
1.800     albertel 6165: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6166:     }
1.800     albertel 6167:     foreach my $item (keys(%allitems)) {
                   6168: 	$allitems{$item} =~ s/\:$//;
                   6169: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6170:     }
                   6171:     $items=~s/\&$//;
                   6172:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6173: }
                   6174: 
1.47      www      6175: # ------------------------------------------------------ critical put interface
                   6176: 
                   6177: sub cput {
1.134     albertel 6178:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6179:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6180:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6181:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6182:    my $items='';
1.800     albertel 6183:    foreach my $item (keys(%$storehash)) {
                   6184:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6185:    }
1.47      www      6186:    $items=~s/\&$//;
1.134     albertel 6187:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6188: }
                   6189: 
                   6190: # -------------------------------------------------------------- eget interface
                   6191: 
                   6192: sub eget {
1.133     albertel 6193:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6194:    my $items='';
1.800     albertel 6195:    foreach my $item (@$storearr) {
                   6196:        $items.=&escape($item).'&';
1.191     harris41 6197:    }
1.12      www      6198:    $items=~s/\&$//;
1.620     albertel 6199:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6200:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6201:    my $uhome=&homeserver($uname,$udomain);
                   6202:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6203:    my @pairs=split(/\&/,$rep);
                   6204:    my %returnhash=();
1.42      www      6205:    my $i=0;
1.800     albertel 6206:    foreach my $item (@$storearr) {
                   6207:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6208:       $i++;
1.191     harris41 6209:    }
1.12      www      6210:    return %returnhash;
                   6211: }
                   6212: 
1.667     albertel 6213: # ------------------------------------------------------------ tmpput interface
                   6214: sub tmpput {
1.802     raeburn  6215:     my ($storehash,$server,$context)=@_;
1.667     albertel 6216:     my $items='';
1.800     albertel 6217:     foreach my $item (keys(%$storehash)) {
                   6218: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6219:     }
                   6220:     $items=~s/\&$//;
1.802     raeburn  6221:     if (defined($context)) {
                   6222:         $items .= ':'.&escape($context);
                   6223:     }
1.667     albertel 6224:     return &reply("tmpput:$items",$server);
                   6225: }
                   6226: 
                   6227: # ------------------------------------------------------------ tmpget interface
                   6228: sub tmpget {
1.688     albertel 6229:     my ($token,$server)=@_;
                   6230:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6231:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6232:     my %returnhash;
                   6233:     foreach my $item (split(/\&/,$rep)) {
                   6234: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  6235:         next if ($key =~ /^error: 2 /);
1.667     albertel 6236: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6237:     }
                   6238:     return %returnhash;
                   6239: }
                   6240: 
1.1113    raeburn  6241: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6242: sub tmpdel {
                   6243:     my ($token,$server)=@_;
                   6244:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6245:     return &reply("tmpdel:$token",$server);
                   6246: }
                   6247: 
1.1198    raeburn  6248: # ------------------------------------------------------------ get_timebased_id 
                   6249: 
                   6250: sub get_timebased_id {
                   6251:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6252:         $maxtries) = @_;
                   6253:     my ($newid,$error,$dellock);
                   6254:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   6255:         return ('','ok','invalid call to get suffix');
                   6256:     }
                   6257: 
                   6258: # set defaults for any optional args for which values were not supplied
                   6259:     if ($who eq '') {
                   6260:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6261:     }
                   6262:     if (!$locktries) {
                   6263:         $locktries = 3;
                   6264:     }
                   6265:     if (!$maxtries) {
                   6266:         $maxtries = 10;
                   6267:     }
                   6268:     
                   6269:     if (($cdom eq '') || ($cnum eq '')) {
                   6270:         if ($env{'request.course.id'}) {
                   6271:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6272:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6273:         }
                   6274:         if (($cdom eq '') || ($cnum eq '')) {
                   6275:             return ('','ok','call to get suffix not in course context');
                   6276:         }
                   6277:     }
                   6278: 
                   6279: # construct locking item
                   6280:     my $lockhash = {
                   6281:                       $prefix."\0".'locked_'.$keyid => $who,
                   6282:                    };
                   6283:     my $tries = 0;
                   6284: 
                   6285: # attempt to get lock on nohist_$namespace file
                   6286:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6287:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6288:         $tries ++;
                   6289:         sleep 1;
                   6290:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6291:     }
                   6292: 
                   6293: # attempt to get unique identifier, based on current timestamp
                   6294:     if ($gotlock eq 'ok') {
                   6295:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6296:         my $id = time;
                   6297:         $newid = $id;
1.1268    raeburn  6298:         if ($idtype eq 'addcode') {
                   6299:             $newid .= &sixnum_code();
                   6300:         }
1.1198    raeburn  6301:         my $idtries = 0;
                   6302:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6303:             if ($idtype eq 'concat') {
                   6304:                 $newid = $id.$idtries;
1.1268    raeburn  6305:             } elsif ($idtype eq 'addcode') {
                   6306:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6307:             } else {
                   6308:                 $newid ++;
                   6309:             }
                   6310:             $idtries ++;
                   6311:         }
                   6312:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6313:             my %new_item =  (
                   6314:                               $prefix."\0".$newid => $who,
                   6315:                             );
                   6316:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6317:                                                  $cdom,$cnum);
                   6318:             if ($putresult ne 'ok') {
                   6319:                 undef($newid);
                   6320:                 $error = 'error saving new item: '.$putresult;
                   6321:             }
                   6322:         } else {
1.1268    raeburn  6323:              undef($newid);
1.1198    raeburn  6324:              $error = ('error: no unique suffix available for the new item ');
                   6325:         }
                   6326: #  remove lock
                   6327:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6328:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6329:     } else {
                   6330:         $error = "error: could not obtain lockfile\n";
                   6331:         $dellock = 'ok';
1.1276    raeburn  6332:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6333:             $dellock = 'nolock';
                   6334:         }
1.1198    raeburn  6335:     }
                   6336:     return ($newid,$dellock,$error);
                   6337: }
                   6338: 
1.1268    raeburn  6339: sub sixnum_code {
                   6340:     my $code;
                   6341:     for (0..6) {
                   6342:         $code .= int( rand(9) );
                   6343:     }
                   6344:     return $code;
                   6345: }
                   6346: 
1.765     albertel 6347: # -------------------------------------------------- portfolio access checking
                   6348: 
                   6349: sub portfolio_access {
1.1270    raeburn  6350:     my ($requrl,$clientip) = @_;
1.765     albertel 6351:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  6352:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6353:     if ($result) {
                   6354:         my %setters;
                   6355:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6356:             my ($startblock,$endblock) =
                   6357:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6358:             if ($startblock && $endblock) {
                   6359:                 return 'B';
                   6360:             }
                   6361:         } else {
                   6362:             my ($startblock,$endblock) =
                   6363:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6364:             if ($startblock && $endblock) {
                   6365:                 return 'B';
                   6366:             }
                   6367:         }
                   6368:     }
1.765     albertel 6369:     if ($result eq 'ok') {
1.766     albertel 6370:        return 'F';
1.765     albertel 6371:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6372:        return 'A';
1.765     albertel 6373:     }
1.766     albertel 6374:     return '';
1.765     albertel 6375: }
                   6376: 
                   6377: sub get_portfolio_access {
1.1270    raeburn  6378:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6379: 
                   6380:     if (!ref($access_hash)) {
                   6381: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6382: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6383: 						   $file_name);
                   6384: 	$access_hash = $access_controls{$file_name};
                   6385:     }
                   6386: 
1.1270    raeburn  6387:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6388:     my $now = time;
                   6389:     if (ref($access_hash) eq 'HASH') {
                   6390:         foreach my $key (keys(%{$access_hash})) {
                   6391:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6392:             if ($start > $now) {
                   6393:                 next;
                   6394:             }
                   6395:             if ($end && $end<$now) {
                   6396:                 next;
                   6397:             }
                   6398:             if ($scope eq 'public') {
                   6399:                 $public = $key;
                   6400:                 last;
                   6401:             } elsif ($scope eq 'guest') {
                   6402:                 $guest = $key;
                   6403:             } elsif ($scope eq 'domains') {
                   6404:                 push(@domains,$key);
                   6405:             } elsif ($scope eq 'users') {
                   6406:                 push(@users,$key);
                   6407:             } elsif ($scope eq 'course') {
                   6408:                 push(@courses,$key);
                   6409:             } elsif ($scope eq 'group') {
                   6410:                 push(@groups,$key);
1.1270    raeburn  6411:             } elsif ($scope eq 'ip') {
                   6412:                 push(@ips,$key);
1.765     albertel 6413:             }
                   6414:         }
                   6415:         if ($public) {
                   6416:             return 'ok';
1.1270    raeburn  6417:         } elsif (@ips > 0) {
                   6418:             my $allowed;
                   6419:             foreach my $ipkey (@ips) {
                   6420:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6421:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6422:                         $allowed = 1;
                   6423:                         last; 
                   6424:                     }
                   6425:                 }
                   6426:             }
                   6427:             if ($allowed) {
                   6428:                 return 'ok';
                   6429:             }
1.765     albertel 6430:         }
                   6431:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6432:             if ($guest) {
                   6433:                 return $guest;
                   6434:             }
                   6435:         } else {
                   6436:             if (@domains > 0) {
                   6437:                 foreach my $domkey (@domains) {
                   6438:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6439:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6440:                             return 'ok';
                   6441:                         }
                   6442:                     }
                   6443:                 }
                   6444:             }
                   6445:             if (@users > 0) {
                   6446:                 foreach my $userkey (@users) {
1.865     raeburn  6447:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6448:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6449:                             if (ref($item) eq 'HASH') {
                   6450:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6451:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6452:                                     return 'ok';
                   6453:                                 }
                   6454:                             }
                   6455:                         }
                   6456:                     } 
1.765     albertel 6457:                 }
                   6458:             }
                   6459:             my %roleshash;
                   6460:             my @courses_and_groups = @courses;
                   6461:             push(@courses_and_groups,@groups); 
                   6462:             if (@courses_and_groups > 0) {
                   6463:                 my (%allgroups,%allroles); 
                   6464:                 my ($start,$end,$role,$sec,$group);
                   6465:                 foreach my $envkey (%env) {
1.1060    raeburn  6466:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6467:                         my $cid = $2.'_'.$3; 
                   6468:                         if ($1 eq 'gr') {
                   6469:                             $group = $4;
                   6470:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6471:                         } else {
                   6472:                             if ($4 eq '') {
                   6473:                                 $sec = 'none';
                   6474:                             } else {
                   6475:                                 $sec = $4;
                   6476:                             }
                   6477:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6478:                         }
1.811     albertel 6479:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6480:                         my $cid = $2.'_'.$3;
                   6481:                         if ($4 eq '') {
                   6482:                             $sec = 'none';
                   6483:                         } else {
                   6484:                             $sec = $4;
                   6485:                         }
                   6486:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6487:                     }
                   6488:                 }
                   6489:                 if (keys(%allroles) == 0) {
                   6490:                     return;
                   6491:                 }
                   6492:                 foreach my $key (@courses_and_groups) {
                   6493:                     my %content = %{$$access_hash{$key}};
                   6494:                     my $cnum = $content{'number'};
                   6495:                     my $cdom = $content{'domain'};
                   6496:                     my $cid = $cdom.'_'.$cnum;
                   6497:                     if (!exists($allroles{$cid})) {
                   6498:                         next;
                   6499:                     }    
                   6500:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6501:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6502:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6503:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6504:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6505:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6506:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6507:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6508:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6509:                                         if (grep/^all$/,@sections) {
                   6510:                                             return 'ok';
                   6511:                                         } else {
                   6512:                                             if (grep/^$sec$/,@sections) {
                   6513:                                                 return 'ok';
                   6514:                                             }
                   6515:                                         }
                   6516:                                     }
                   6517:                                 }
                   6518:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6519:                                     if (grep/^none$/,@groups) {
                   6520:                                         return 'ok';
                   6521:                                     }
                   6522:                                 } else {
                   6523:                                     if (grep/^all$/,@groups) {
                   6524:                                         return 'ok';
                   6525:                                     } 
                   6526:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6527:                                         if (grep/^$group$/,@groups) {
                   6528:                                             return 'ok';
                   6529:                                         }
                   6530:                                     }
                   6531:                                 } 
                   6532:                             }
                   6533:                         }
                   6534:                     }
                   6535:                 }
                   6536:             }
                   6537:             if ($guest) {
                   6538:                 return $guest;
                   6539:             }
                   6540:         }
                   6541:     }
                   6542:     return;
                   6543: }
                   6544: 
                   6545: sub course_group_datechecker {
                   6546:     my ($dates,$now,$status) = @_;
                   6547:     my ($start,$end) = split(/\./,$dates);
                   6548:     if (!$start && !$end) {
                   6549:         return 'ok';
                   6550:     }
                   6551:     if (grep/^active$/,@{$status}) {
                   6552:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6553:             return 'ok';
                   6554:         }
                   6555:     }
                   6556:     if (grep/^previous$/,@{$status}) {
                   6557:         if ($end > $now ) {
                   6558:             return 'ok';
                   6559:         }
                   6560:     }
                   6561:     if (grep/^future$/,@{$status}) {
                   6562:         if ($start > $now) {
                   6563:             return 'ok';
                   6564:         }
                   6565:     }
                   6566:     return; 
                   6567: }
                   6568: 
                   6569: sub parse_portfolio_url {
                   6570:     my ($url) = @_;
                   6571: 
                   6572:     my ($type,$udom,$unum,$group,$file_name);
                   6573:     
1.823     albertel 6574:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6575: 	$type = 1;
                   6576:         $udom = $1;
                   6577:         $unum = $2;
                   6578:         $file_name = $3;
1.823     albertel 6579:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6580: 	$type = 2;
                   6581:         $udom = $1;
                   6582:         $unum = $2;
                   6583:         $group = $3;
                   6584:         $file_name = $3.'/'.$4;
                   6585:     }
                   6586:     if (wantarray) {
                   6587: 	return ($type,$udom,$unum,$file_name,$group);
                   6588:     }
                   6589:     return $type;
                   6590: }
                   6591: 
                   6592: sub is_portfolio_url {
                   6593:     my ($url) = @_;
                   6594:     return scalar(&parse_portfolio_url($url));
                   6595: }
                   6596: 
1.798     raeburn  6597: sub is_portfolio_file {
                   6598:     my ($file) = @_;
1.820     raeburn  6599:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6600:         return 1;
                   6601:     }
                   6602:     return;
                   6603: }
                   6604: 
1.976     raeburn  6605: sub usertools_access {
1.1084    raeburn  6606:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6607:     my ($access,%tools);
                   6608:     if ($context eq '') {
                   6609:         $context = 'tools';
                   6610:     }
                   6611:     if ($context eq 'requestcourses') {
                   6612:         %tools = (
                   6613:                       official   => 1,
                   6614:                       unofficial => 1,
1.1006    raeburn  6615:                       community  => 1,
1.1246    raeburn  6616:                       textbook   => 1,
1.1305    raeburn  6617:                       placement  => 1,
1.985     raeburn  6618:                  );
1.1183    raeburn  6619:     } elsif ($context eq 'requestauthor') {
                   6620:         %tools = (
                   6621:                       requestauthor => 1,
                   6622:                  );
1.985     raeburn  6623:     } else {
                   6624:         %tools = (
                   6625:                       aboutme   => 1,
                   6626:                       blog      => 1,
1.1177    raeburn  6627:                       webdav    => 1,
1.985     raeburn  6628:                       portfolio => 1,
                   6629:                  );
                   6630:     }
1.976     raeburn  6631:     return if (!defined($tools{$tool}));
                   6632: 
1.1242    raeburn  6633:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6634:         $udom = $env{'user.domain'};
                   6635:         $uname = $env{'user.name'};
                   6636:     }
                   6637: 
1.978     raeburn  6638:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6639:         if ($action ne 'reload') {
1.985     raeburn  6640:             if ($context eq 'requestcourses') {
                   6641:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  6642:             } elsif ($context eq 'requestauthor') {
                   6643:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6644:             } else {
                   6645:                 return $env{'environment.availabletools.'.$tool};
                   6646:             }
                   6647:         }
1.976     raeburn  6648:     }
                   6649: 
1.1183    raeburn  6650:     my ($toolstatus,$inststatus,$envkey);
                   6651:     if ($context eq 'requestauthor') {
                   6652:         $envkey = $context; 
                   6653:     } else {
                   6654:         $envkey = $context.'.'.$tool;
                   6655:     }
1.976     raeburn  6656: 
1.985     raeburn  6657:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6658:          ($action ne 'reload')) {
1.1183    raeburn  6659:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6660:         $inststatus = $env{'environment.inststatus'};
                   6661:     } else {
1.1084    raeburn  6662:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  6663:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6664:             $inststatus = $userenvref->{'inststatus'};
                   6665:         } else {
1.1183    raeburn  6666:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6667:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6668:             $inststatus = $userenv{'inststatus'};
                   6669:         }
1.976     raeburn  6670:     }
                   6671: 
                   6672:     if ($toolstatus ne '') {
                   6673:         if ($toolstatus) {
                   6674:             $access = 1;
                   6675:         } else {
                   6676:             $access = 0;
                   6677:         }
                   6678:         return $access;
                   6679:     }
                   6680: 
1.1084    raeburn  6681:     my ($is_adv,%domdef);
                   6682:     if (ref($is_advref) eq 'HASH') {
                   6683:         $is_adv = $is_advref->{'is_adv'};
                   6684:     } else {
                   6685:         $is_adv = &is_advanced_user($udom,$uname);
                   6686:     }
                   6687:     if (ref($domdefref) eq 'HASH') {
                   6688:         %domdef = %{$domdefref};
                   6689:     } else {
                   6690:         %domdef = &get_domain_defaults($udom);
                   6691:     }
1.976     raeburn  6692:     if (ref($domdef{$tool}) eq 'HASH') {
                   6693:         if ($is_adv) {
                   6694:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6695:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6696:                     $access = 1;
                   6697:                 } else {
                   6698:                     $access = 0;
                   6699:                 }
                   6700:                 return $access;
                   6701:             }
                   6702:         }
                   6703:         if ($inststatus ne '') {
                   6704:             my ($hasaccess,$hasnoaccess);
                   6705:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6706:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6707:                     if ($domdef{$tool}{$affiliation}) {
                   6708:                         $hasaccess = 1;
                   6709:                     } else {
                   6710:                         $hasnoaccess = 1;
                   6711:                     }
                   6712:                 }
                   6713:             }
                   6714:             if ($hasaccess || $hasnoaccess) {
                   6715:                 if ($hasaccess) {
                   6716:                     $access = 1;
                   6717:                 } elsif ($hasnoaccess) {
                   6718:                     $access = 0; 
                   6719:                 }
                   6720:                 return $access;
                   6721:             }
                   6722:         } else {
                   6723:             if ($domdef{$tool}{'default'} ne '') {
                   6724:                 if ($domdef{$tool}{'default'}) {
                   6725:                     $access = 1;
                   6726:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6727:                     $access = 0;
                   6728:                 }
                   6729:                 return $access;
                   6730:             }
                   6731:         }
                   6732:     } else {
1.1177    raeburn  6733:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6734:             $access = 1;
                   6735:         } else {
                   6736:             $access = 0;
                   6737:         }
1.976     raeburn  6738:         return $access;
                   6739:     }
                   6740: }
                   6741: 
1.1050    raeburn  6742: sub is_course_owner {
                   6743:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6744:     if (($udom eq '') || ($uname eq '')) {
                   6745:         $udom = $env{'user.domain'};
                   6746:         $uname = $env{'user.name'};
                   6747:     }
                   6748:     unless (($udom eq '') || ($uname eq '')) {
                   6749:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6750:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6751:                 return 1;
                   6752:             } else {
                   6753:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6754:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6755:                     return 1;
                   6756:                 }
                   6757:             }
                   6758:         }
                   6759:     }
                   6760:     return;
                   6761: }
                   6762: 
1.976     raeburn  6763: sub is_advanced_user {
                   6764:     my ($udom,$uname) = @_;
1.1085    raeburn  6765:     if ($udom ne '' && $uname ne '') {
                   6766:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6767:             if (wantarray) {
                   6768:                 return ($env{'user.adv'},$env{'user.author'});
                   6769:             } else {
                   6770:                 return $env{'user.adv'};
                   6771:             }
1.1085    raeburn  6772:         }
                   6773:     }
1.976     raeburn  6774:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6775:     my %allroles;
1.1128    raeburn  6776:     my ($is_adv,$is_author);
1.976     raeburn  6777:     foreach my $role (keys(%roleshash)) {
                   6778:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6779:         my $area = '/'.$tdomain.'/'.$trest;
                   6780:         if ($sec ne '') {
                   6781:             $area .= '/'.$sec;
                   6782:         }
                   6783:         if (($area ne '') && ($trole ne '')) {
                   6784:             my $spec=$trole.'.'.$area;
                   6785:             if ($trole =~ /^cr\//) {
                   6786:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6787:             } elsif ($trole ne 'gr') {
                   6788:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6789:             }
1.1128    raeburn  6790:             if ($trole eq 'au') {
                   6791:                 $is_author = 1;
                   6792:             }
1.976     raeburn  6793:         }
                   6794:     }
                   6795:     foreach my $role (keys(%allroles)) {
                   6796:         last if ($is_adv);
                   6797:         foreach my $item (split(/:/,$allroles{$role})) {
                   6798:             if ($item ne '') {
                   6799:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6800:                 if ($privilege eq 'adv') {
                   6801:                     $is_adv = 1;
                   6802:                     last;
                   6803:                 }
                   6804:             }
                   6805:         }
                   6806:     }
1.1128    raeburn  6807:     if (wantarray) {
                   6808:         return ($is_adv,$is_author);
                   6809:     }
1.976     raeburn  6810:     return $is_adv;
                   6811: }
1.798     raeburn  6812: 
1.1035    raeburn  6813: sub check_can_request {
1.1036    raeburn  6814:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6815:     my $canreq = 0;
                   6816:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6817:     my @options = ('approval','validate','autolimit');
                   6818:     my $optregex = join('|',@options);
                   6819:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6820:         foreach my $type (@{$types}) {
                   6821:             if (&usertools_access($env{'user.name'},
                   6822:                                   $env{'user.domain'},
                   6823:                                   $type,undef,'requestcourses')) {
                   6824:                 $canreq ++;
1.1036    raeburn  6825:                 if (ref($request_domains) eq 'HASH') {
                   6826:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6827:                 }
1.1035    raeburn  6828:                 if ($dom eq $env{'user.domain'}) {
                   6829:                     $can_request->{$type} = 1;
                   6830:                 }
                   6831:             }
                   6832:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6833:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6834:                 if (@curr > 0) {
1.1036    raeburn  6835:                     foreach my $item (@curr) {
                   6836:                         if (ref($request_domains) eq 'HASH') {
                   6837:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6838:                             if ($otherdom ne '') {
                   6839:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6840:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6841:                                         push(@{$request_domains->{$type}},$otherdom);
                   6842:                                     }
                   6843:                                 } else {
                   6844:                                     push(@{$request_domains->{$type}},$otherdom);
                   6845:                                 }
                   6846:                             }
                   6847:                         }
                   6848:                     }
                   6849:                     unless($dom eq $env{'user.domain'}) {
                   6850:                         $canreq ++;
1.1035    raeburn  6851:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6852:                             $can_request->{$type} = 1;
                   6853:                         }
                   6854:                     }
                   6855:                 }
                   6856:             }
                   6857:         }
                   6858:     }
                   6859:     return $canreq;
                   6860: }
                   6861: 
1.341     www      6862: # ---------------------------------------------- Custom access rule evaluation
                   6863: 
                   6864: sub customaccess {
                   6865:     my ($priv,$uri)=@_;
1.807     albertel 6866:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6867:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6868:     $udom = &LONCAPA::clean_domain($udom);
                   6869:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6870:     my $access=0;
1.800     albertel 6871:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6872: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6873: 	if ($type eq 'user') {
                   6874: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6875: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6876: 		if ($tdom) {
                   6877: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6878: 		}
1.896     albertel 6879: 		if ($tuname) {
                   6880: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6881: 		}
                   6882: 		$access=($effect eq 'allow');
                   6883: 		last;
                   6884: 	    }
                   6885: 	} else {
                   6886: 	    if ($role) {
                   6887: 		if ($role ne $urole) { next; }
                   6888: 	    }
                   6889: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6890: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6891: 		if ($tdom) {
                   6892: 		    if ($tdom ne $udom) { next; }
                   6893: 		}
                   6894: 		if ($tcrs) {
                   6895: 		    if ($tcrs ne $ucrs) { next; }
                   6896: 		}
                   6897: 		if ($tsec) {
                   6898: 		    if ($tsec ne $usec) { next; }
                   6899: 		}
                   6900: 		$access=($effect eq 'allow');
                   6901: 		last;
                   6902: 	    }
                   6903: 	    if ($realm eq '' && $role eq '') {
                   6904: 		$access=($effect eq 'allow');
                   6905: 	    }
1.402     bowersj2 6906: 	}
1.341     www      6907:     }
                   6908:     return $access;
                   6909: }
                   6910: 
1.103     harris41 6911: # ------------------------------------------------- Check for a user privilege
1.12      www      6912: 
                   6913: sub allowed {
1.1281    raeburn  6914:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 6915:     my $ver_orguri=$uri;
1.439     www      6916:     $uri=&deversion($uri);
1.152     www      6917:     my $orguri=$uri;
1.52      www      6918:     $uri=&declutter($uri);
1.809     raeburn  6919: 
1.810     raeburn  6920:     if ($priv eq 'evb') {
                   6921: # Evade communication block restrictions for specified role in a course
                   6922:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6923:             return $1;
                   6924:         } else {
                   6925:             return;
                   6926:         }
                   6927:     }
                   6928: 
1.620     albertel 6929:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6930: # Free bre access to adm and meta resources
1.775     albertel 6931:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6932: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6933: 	&& ($priv eq 'bre')) {
1.14      www      6934: 	return 'F';
1.159     www      6935:     }
                   6936: 
1.545     banghart 6937: # Free bre access to user's own portfolio contents
1.714     raeburn  6938:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6939:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6940: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6941:         my %setters;
                   6942:         my ($startblock,$endblock) = 
                   6943:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6944:         if ($startblock && $endblock) {
                   6945:             return 'B';
                   6946:         } else {
                   6947:             return 'F';
                   6948:         }
1.545     banghart 6949:     }
                   6950: 
1.762     raeburn  6951: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6952:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6953:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6954:         if (exists($env{'request.course.id'})) {
                   6955:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6956:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6957:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6958:                 my $courseprivid=$env{'request.course.id'};
                   6959:                 $courseprivid=~s/\_/\//;
                   6960:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6961:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6962:                     return $1; 
1.762     raeburn  6963:                 } else {
                   6964:                     if ($env{'request.course.sec'}) {
                   6965:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6966:                     }
                   6967:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6968:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6969:                         return $2;
                   6970:                     }
1.714     raeburn  6971:                 }
                   6972:             }
                   6973:         }
                   6974:     }
                   6975: 
1.159     www      6976: # Free bre to public access
                   6977: 
                   6978:     if ($priv eq 'bre') {
1.238     www      6979:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6980: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6981:            return 'F'; 
                   6982:         }
1.238     www      6983:         if ($copyright eq 'priv') {
                   6984:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6985: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6986: 		return '';
                   6987:             }
                   6988:         }
                   6989:         if ($copyright eq 'domain') {
                   6990:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6991: 	    unless (($env{'user.domain'} eq $1) ||
                   6992:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6993: 		return '';
                   6994:             }
1.262     matthew  6995:         }
1.620     albertel 6996:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6997:             # Library role, so allow browsing of resources in this domain.
                   6998:             return 'F';
1.238     www      6999:         }
1.341     www      7000:         if ($copyright eq 'custom') {
                   7001: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7002:         }
1.14      www      7003:     }
1.264     matthew  7004:     # Domain coordinator is trying to create a course
1.620     albertel 7005:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7006:         # uri is the requested domain in this case.
                   7007:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7008:         # a role of dc for the domain in question.
1.620     albertel 7009:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7010:     }
1.29      www      7011: 
1.52      www      7012:     my $thisallowed='';
                   7013:     my $statecond=0;
                   7014:     my $courseprivid='';
                   7015: 
1.1039    raeburn  7016:     my $ownaccess;
1.1043    raeburn  7017:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7018:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7019:         if ($uri eq '') {
                   7020:             $ownaccess = 1;
                   7021:         } else {
                   7022:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7023:                 my $udom = $env{'user.domain'};
                   7024:                 my $uname = $env{'user.name'};
                   7025:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7026:                     $ownaccess = 1;
1.1040    raeburn  7027:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7028:                     unless ($uri =~ m{\.\./}) {
                   7029:                         $ownaccess = 1;
                   7030:                     }
                   7031:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7032:                     my $now = time;
                   7033:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7034:                         my $adom = $1;
                   7035:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7036:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7037:                                 my ($start,$end) = split('.',$env{$key});
                   7038:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7039:                                     $ownaccess = 1;
                   7040:                                     last;
                   7041:                                 }
                   7042:                             }
                   7043:                         }
                   7044:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7045:                         my $adom = $1;
                   7046:                         my $aname = $2;
1.1042    raeburn  7047:                         foreach my $role ('ca','aa') { 
                   7048:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7049:                                 my ($start,$end) =
                   7050:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7051:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7052:                                     $ownaccess = 1;
                   7053:                                     last;
                   7054:                                 }
1.1039    raeburn  7055:                             }
                   7056:                         }
                   7057:                     }
                   7058:                 }
                   7059:             }
                   7060:         }
                   7061:     }
                   7062: 
1.52      www      7063: # Course
                   7064: 
1.620     albertel 7065:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7066:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7067:             $thisallowed.=$1;
                   7068:         }
1.52      www      7069:     }
1.29      www      7070: 
1.52      www      7071: # Domain
                   7072: 
1.620     albertel 7073:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7074:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7075:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7076:             $thisallowed.=$1;
                   7077:         }
1.12      www      7078:     }
1.52      www      7079: 
1.1141    raeburn  7080: # User who is not author or co-author might still be able to edit
                   7081: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7082:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7083:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7084:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7085:             $thisallowed.=$1;
                   7086:         }
                   7087:     }
                   7088: 
1.52      www      7089: # Course: uri itself is a course
1.66      www      7090:     my $courseuri=$uri;
                   7091:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7092:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7093: 
1.620     albertel 7094:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7095:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7096:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7097:             $thisallowed.=$1;
                   7098:         }
1.12      www      7099:     }
1.29      www      7100: 
1.665     albertel 7101: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7102: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7103:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7104: 	$thisallowed='';
1.671     raeburn  7105:         my ($match)=&is_on_map($uri);
                   7106:         if ($match) {
                   7107:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7108:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  7109:                 my $value = $1;
                   7110:                 if ($noblockcheck) {
                   7111:                     $thisallowed.=$value;
1.1162    raeburn  7112:                 } else {
1.1281    raeburn  7113:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7114:                     if (@blockers > 0) {
                   7115:                         $thisallowed = 'B';
                   7116:                     } else {
                   7117:                         $thisallowed.=$value;
                   7118:                     }
1.1162    raeburn  7119:                 }
1.671     raeburn  7120:             }
                   7121:         } else {
1.705     albertel 7122:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7123:             if ($refuri) {
                   7124:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7125:                     $thisallowed='F';
1.671     raeburn  7126:                 } else {
                   7127:                     $refuri=&declutter($refuri);
                   7128:                     my ($match) = &is_on_map($refuri);
                   7129:                     if ($match) {
1.1281    raeburn  7130:                         if ($noblockcheck) {
                   7131:                             $thisallowed='F';
1.1162    raeburn  7132:                         } else {
1.1281    raeburn  7133:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7134:                             if (@blockers > 0) {
                   7135:                                 $thisallowed = 'B';
                   7136:                             } else {
                   7137:                                 $thisallowed='F';
                   7138:                             }
1.1162    raeburn  7139:                         }
1.671     raeburn  7140:                     }
1.669     raeburn  7141:                 }
1.671     raeburn  7142:             }
                   7143:         }
1.314     www      7144:     }
1.492     albertel 7145: 
1.766     albertel 7146:     if ($priv eq 'bre'
                   7147: 	&& $thisallowed ne 'F' 
                   7148: 	&& $thisallowed ne '2'
                   7149: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  7150: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7151:     }
1.1250    raeburn  7152: 
1.52      www      7153: # Full access at system, domain or course-wide level? Exit.
1.29      www      7154:     if ($thisallowed=~/F/) {
                   7155: 	return 'F';
                   7156:     }
                   7157: 
1.52      www      7158: # If this is generating or modifying users, exit with special codes
1.29      www      7159: 
1.643     www      7160:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7161: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7162: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7163: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7164: 	    unless ($auname) { return $thisallowed; }
                   7165: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7166: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7167: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7168: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7169: 	}
1.52      www      7170: 	return $thisallowed;
                   7171:     }
                   7172: #
1.103     harris41 7173: # Gathered so far: system, domain and course wide privileges
1.52      www      7174: #
                   7175: # Course: See if uri or referer is an individual resource that is part of 
                   7176: # the course
                   7177: 
1.620     albertel 7178:     if ($env{'request.course.id'}) {
1.232     www      7179: 
1.620     albertel 7180:        $courseprivid=$env{'request.course.id'};
                   7181:        if ($env{'request.course.sec'}) {
                   7182:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7183:        }
                   7184:        $courseprivid=~s/\_/\//;
                   7185:        my $checkreferer=1;
1.232     www      7186:        my ($match,$cond)=&is_on_map($uri);
                   7187:        if ($match) {
                   7188:            $statecond=$cond;
1.620     albertel 7189:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7190:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7191:                my $value = $1;
                   7192:                if ($priv eq 'bre') {
1.1281    raeburn  7193:                    if ($noblockcheck) {
                   7194:                        $thisallowed.=$value;
1.1162    raeburn  7195:                    } else {
1.1281    raeburn  7196:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7197:                        if (@blockers > 0) {
                   7198:                            $thisallowed = 'B';
                   7199:                        } else {
                   7200:                            $thisallowed.=$value;
                   7201:                        }
1.1162    raeburn  7202:                    }
                   7203:                } else {
                   7204:                    $thisallowed.=$value;
                   7205:                }
1.52      www      7206:                $checkreferer=0;
                   7207:            }
1.29      www      7208:        }
1.83      www      7209:        
1.148     www      7210:        if ($checkreferer) {
1.620     albertel 7211: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7212:             unless ($refuri) {
1.800     albertel 7213:                 foreach my $key (keys(%env)) {
                   7214: 		    if ($key=~/^httpref\..*\*/) {
                   7215: 			my $pattern=$key;
1.156     www      7216:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7217:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7218:                         $pattern=~s/\//\\\//g;
1.152     www      7219:                         if ($orguri=~/$pattern/) {
1.800     albertel 7220: 			    $refuri=$env{$key};
1.148     www      7221:                         }
                   7222:                     }
1.191     harris41 7223:                 }
1.148     www      7224:             }
1.232     www      7225: 
1.148     www      7226:          if ($refuri) { 
1.152     www      7227: 	  $refuri=&declutter($refuri);
1.232     www      7228:           my ($match,$cond)=&is_on_map($refuri);
                   7229:             if ($match) {
                   7230:               my $refstatecond=$cond;
1.620     albertel 7231:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7232:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7233:                   my $value = $1;
                   7234:                   if ($priv eq 'bre') {
1.1281    raeburn  7235:                       if ($noblockcheck) {
                   7236:                           $thisallowed.=$value;
1.1162    raeburn  7237:                       } else {
1.1281    raeburn  7238:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7239:                           if (@blockers > 0) {
                   7240:                               $thisallowed = 'B';
                   7241:                           } else {
                   7242:                               $thisallowed.=$value;
                   7243:                           }
1.1162    raeburn  7244:                       }
                   7245:                   } else {
                   7246:                       $thisallowed.=$value;
                   7247:                   }
1.53      www      7248:                   $uri=$refuri;
                   7249:                   $statecond=$refstatecond;
1.52      www      7250:               }
                   7251:           }
1.148     www      7252:         }
1.29      www      7253:        }
1.52      www      7254:    }
1.29      www      7255: 
1.52      www      7256: #
1.103     harris41 7257: # Gathered now: all privileges that could apply, and condition number
1.52      www      7258: # 
                   7259: #
                   7260: # Full or no access?
                   7261: #
1.29      www      7262: 
1.52      www      7263:     if ($thisallowed=~/F/) {
                   7264: 	return 'F';
                   7265:     }
1.29      www      7266: 
1.52      www      7267:     unless ($thisallowed) {
                   7268:         return '';
                   7269:     }
1.29      www      7270: 
1.52      www      7271: # Restrictions exist, deal with them
                   7272: #
                   7273: #   C:according to course preferences
                   7274: #   R:according to resource settings
                   7275: #   L:unless locked
                   7276: #   X:according to user session state
                   7277: #
                   7278: 
                   7279: # Possibly locked functionality, check all courses
1.54      www      7280: # Locks might take effect only after 10 minutes cache expiration for other
                   7281: # courses, and 2 minutes for current course
1.52      www      7282: 
                   7283:     my $envkey;
                   7284:     if ($thisallowed=~/L/) {
1.1000    raeburn  7285:         foreach $envkey (keys(%env)) {
1.54      www      7286:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7287:                my $courseid=$2;
                   7288:                my $roleid=$1.'.'.$2;
1.92      www      7289:                $courseid=~s/^\///;
1.54      www      7290:                my $expiretime=600;
1.620     albertel 7291:                if ($env{'request.role'} eq $roleid) {
1.54      www      7292: 		  $expiretime=120;
                   7293:                }
                   7294: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7295:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7296:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7297: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7298:                }
1.620     albertel 7299:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7300:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7301: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7302:                        &log($env{'user.domain'},$env{'user.name'},
                   7303:                             $env{'user.home'},
1.57      www      7304:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7305:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7306:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7307: 		       return '';
                   7308:                    }
                   7309:                }
1.620     albertel 7310:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7311:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7312: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7313:                        &log($env{'user.domain'},$env{'user.name'},
                   7314:                             $env{'user.home'},
1.57      www      7315:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7316:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7317:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7318: 		       return '';
                   7319:                    }
                   7320:                }
                   7321: 	   }
1.29      www      7322:        }
1.52      www      7323:     }
                   7324:    
                   7325: #
                   7326: # Rest of the restrictions depend on selected course
                   7327: #
                   7328: 
1.620     albertel 7329:     unless ($env{'request.course.id'}) {
1.766     albertel 7330: 	if ($thisallowed eq 'A') {
                   7331: 	    return 'A';
1.814     raeburn  7332:         } elsif ($thisallowed eq 'B') {
                   7333:             return 'B';
1.766     albertel 7334: 	} else {
                   7335: 	    return '1';
                   7336: 	}
1.52      www      7337:     }
1.29      www      7338: 
1.52      www      7339: #
                   7340: # Now user is definitely in a course
                   7341: #
1.53      www      7342: 
                   7343: 
                   7344: # Course preferences
                   7345: 
                   7346:    if ($thisallowed=~/C/) {
1.620     albertel 7347:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7348:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7349:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7350: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  7351: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7352: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7353: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7354: 			$env{'request.course.id'});
                   7355: 	   }
1.237     www      7356:            return '';
                   7357:        }
                   7358: 
1.620     albertel 7359:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7360: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  7361: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7362: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7363: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7364: 			$env{'request.course.id'});
                   7365: 	   }
1.54      www      7366:            return '';
                   7367:        }
1.53      www      7368:    }
                   7369: 
                   7370: # Resource preferences
                   7371: 
                   7372:    if ($thisallowed=~/R/) {
1.620     albertel 7373:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7374:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7375: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7376: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7377: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7378: 	   }
                   7379: 	   return '';
1.54      www      7380:        }
1.53      www      7381:    }
1.30      www      7382: 
1.246     www      7383: # Restricted by state or randomout?
1.30      www      7384: 
1.52      www      7385:    if ($thisallowed=~/X/) {
1.620     albertel 7386:       if ($env{'acc.randomout'}) {
1.579     albertel 7387: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7388:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7389:             return ''; 
                   7390:          }
1.247     www      7391:       }
                   7392:       if (&condval($statecond)) {
1.52      www      7393: 	 return '2';
                   7394:       } else {
                   7395:          return '';
                   7396:       }
                   7397:    }
1.30      www      7398: 
1.766     albertel 7399:     if ($thisallowed eq 'A') {
                   7400: 	return 'A';
1.814     raeburn  7401:     } elsif ($thisallowed eq 'B') {
                   7402:         return 'B';
1.766     albertel 7403:     }
1.52      www      7404:    return 'F';
1.232     www      7405: }
1.1162    raeburn  7406: 
1.1192    raeburn  7407: # ------------------------------------------- Check construction space access
                   7408: 
                   7409: sub constructaccess {
                   7410:     my ($url,$setpriv)=@_;
                   7411: 
                   7412: # We do not allow editing of previous versions of files
                   7413:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7414: 
                   7415: # Get username and domain from URL
                   7416:     my ($ownername,$ownerdomain,$ownerhome);
                   7417: 
                   7418:     ($ownerdomain,$ownername) =
1.1297    damieng  7419:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)/});
1.1192    raeburn  7420: 
                   7421: # The URL does not really point to any authorspace, forget it
                   7422:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7423: 
                   7424: # Now we need to see if the user has access to the authorspace of
                   7425: # $ownername at $ownerdomain
                   7426: 
                   7427:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7428: # Real author for this?
                   7429:        $ownerhome = $env{'user.home'};
                   7430:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7431:           return ($ownername,$ownerdomain,$ownerhome);
                   7432:        }
                   7433:     } else {
                   7434: # Co-author for this?
                   7435:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7436:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7437:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7438:             return ($ownername,$ownerdomain,$ownerhome);
                   7439:         }
1.1312    raeburn  7440:         if ($env{'request.course.id'}) {
                   7441:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   7442:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   7443:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   7444:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   7445:                     return ($ownername,$ownerdomain,$ownerhome);
                   7446:                 }
                   7447:             }
                   7448:         }
1.1192    raeburn  7449:     }
                   7450: 
                   7451: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7452: # we might as well leave
                   7453:    unless ($setpriv) { return ''; }
                   7454: 
                   7455: # Backdoor access?
                   7456:     my $allowed=&allowed('eco',$ownerdomain);
                   7457: # Nope
                   7458:     unless ($allowed) { return ''; }
                   7459: # Looks like we may have access, but could be locked by the owner of the construction space
                   7460:     if ($allowed eq 'U') {
                   7461:         my %blocked=&get('environment',['domcoord.author'],
                   7462:                          $ownerdomain,$ownername);
                   7463: # Is blocked by owner
                   7464:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7465:     }
                   7466:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7467: # Grant temporary access
                   7468:         my $then=$env{'user.login.time'};
1.1209    raeburn  7469:         my $update=$env{'user.update.time'};
1.1192    raeburn  7470:         if (!$update) { $update = $then; }
                   7471:         my $refresh=$env{'user.refresh.time'};
                   7472:         if (!$refresh) { $refresh = $update; }
                   7473:         my $now = time;
                   7474:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7475:                            $now,'ca','constructaccess');
                   7476:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7477:         return($ownername,$ownerdomain,$ownerhome);
                   7478:     }
                   7479: # No business here
                   7480:     return '';
                   7481: }
                   7482: 
1.1282    raeburn  7483: # ----------------------------------------------------------- Content Blocking
                   7484: 
                   7485: {
                   7486: # Caches for faster Course Contents display where content blocking
                   7487: # is in operation (i.e., interval param set) for timed quiz.
                   7488: #
                   7489: # User for whom data are being temporarily cached.
                   7490: my $cacheduser='';
                   7491: # Cached blockers for this user (a hash of blocking items). 
                   7492: my %cachedblockers=();
                   7493: # When the data were last cached.
                   7494: my $cachedlast='';
                   7495: 
                   7496: sub load_all_blockers {
                   7497:     my ($uname,$udom,$blocks)=@_;
                   7498:     if (($uname ne '') && ($udom ne '')) { 
                   7499:         if (($cacheduser eq $uname.':'.$udom) &&
                   7500:             (abs($cachedlast-time)<5)) {
                   7501:             return;
                   7502:         }
                   7503:     }
                   7504:     $cachedlast=time;
                   7505:     $cacheduser=$uname.':'.$udom;
                   7506:     %cachedblockers = &get_commblock_resources($blocks);
                   7507: }
                   7508: 
1.1162    raeburn  7509: sub get_comm_blocks {
                   7510:     my ($cdom,$cnum) = @_;
                   7511:     if ($cdom eq '' || $cnum eq '') {
                   7512:         return unless ($env{'request.course.id'});
                   7513:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7514:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7515:     }
                   7516:     my %commblocks;
                   7517:     my $hashid=$cdom.'_'.$cnum;
                   7518:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7519:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7520:         %commblocks = %{$blocksref};
                   7521:     } else {
                   7522:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7523:         my $cachetime = 600;
                   7524:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7525:     }
                   7526:     return %commblocks;
                   7527: }
                   7528: 
1.1282    raeburn  7529: sub get_commblock_resources {
                   7530:     my ($blocks) = @_;
                   7531:     my %blockers = ();
                   7532:     return %blockers unless ($env{'request.course.id'});
                   7533:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7534:     my %commblocks;
                   7535:     if (ref($blocks) eq 'HASH') {
                   7536:         %commblocks = %{$blocks};
                   7537:     } else {
                   7538:         %commblocks = &get_comm_blocks();
                   7539:     }
1.1282    raeburn  7540:     return %blockers unless (keys(%commblocks) > 0); 
                   7541:     my $navmap = Apache::lonnavmaps::navmap->new();
                   7542:     return %blockers unless (ref($navmap));
1.1162    raeburn  7543:     my $now = time;
                   7544:     foreach my $block (keys(%commblocks)) {
                   7545:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7546:             my ($start,$end) = ($1,$2);
                   7547:             if ($start <= $now && $end >= $now) {
                   7548:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7549:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7550:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  7551:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7552:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  7553:                             }
                   7554:                         }
                   7555:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  7556:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7557:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  7558:                             }
                   7559:                         }
                   7560:                     }
                   7561:                 }
                   7562:             }
                   7563:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7564:             my $item = $1;
1.1163    raeburn  7565:             my @to_test;
1.1162    raeburn  7566:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7567:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  7568:                     my @interval;
                   7569:                     my $type = 'map';
                   7570:                     if ($item eq 'course') {
                   7571:                         $type = 'course';
                   7572:                         @interval=&EXT("resource.0.interval");
                   7573:                     } else {
                   7574:                         if ($item =~ /___\d+___/) {
                   7575:                             $type = 'resource';
                   7576:                             @interval=&EXT("resource.0.interval",$item);
                   7577:                             if (ref($navmap)) {                        
                   7578:                                 my $res = $navmap->getBySymb($item); 
                   7579:                                 push(@to_test,$res);
                   7580:                             }
1.1162    raeburn  7581:                         } else {
1.1282    raeburn  7582:                             my $mapsymb = &symbread($item,1);
                   7583:                             if ($mapsymb) {
                   7584:                                 if (ref($navmap)) {
                   7585:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   7586:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   7587:                                     foreach my $res (@to_test) {
                   7588:                                         my $symb = $res->symb();
                   7589:                                         next if ($symb eq $mapsymb);
                   7590:                                         if ($symb ne '') {
                   7591:                                             @interval=&EXT("resource.0.interval",$symb);
                   7592:                                             if ($interval[1] eq 'map') {
                   7593:                                                 last;
1.1162    raeburn  7594:                                             }
                   7595:                                         }
                   7596:                                     }
                   7597:                                 }
                   7598:                             }
                   7599:                         }
1.1282    raeburn  7600:                     }
1.1310    raeburn  7601:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  7602:                         my $timelimit = $1; 
1.1282    raeburn  7603:                         my $first_access;
                   7604:                         if ($type eq 'resource') {
                   7605:                             $first_access=&get_first_access($interval[1],$item);
                   7606:                         } elsif ($type eq 'map') {
                   7607:                             $first_access=&get_first_access($interval[1],undef,$item);
                   7608:                         } else {
                   7609:                             $first_access=&get_first_access($interval[1]);
                   7610:                         }
                   7611:                         if ($first_access) {
1.1292    raeburn  7612:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  7613:                             if ($timesup > $now) {
                   7614:                                 my $activeblock;
                   7615:                                 foreach my $res (@to_test) {
1.1283    raeburn  7616:                                     if ($res->answerable()) {
1.1282    raeburn  7617:                                         $activeblock = 1;
                   7618:                                         last;
                   7619:                                     }
                   7620:                                 }
                   7621:                                 if ($activeblock) {
                   7622:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7623:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7624:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   7625:                                          }
                   7626:                                     }
                   7627:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7628:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7629:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  7630:                                         }
1.1162    raeburn  7631:                                     }
                   7632:                                 }
                   7633:                             }
                   7634:                         }
                   7635:                     }
                   7636:                 }
                   7637:             }
                   7638:         }
                   7639:     }
1.1282    raeburn  7640:     return %blockers;
1.1162    raeburn  7641: }
                   7642: 
1.1282    raeburn  7643: sub has_comm_blocking {
                   7644:     my ($priv,$symb,$uri,$blocks) = @_;
                   7645:     my @blockers;
                   7646:     return unless ($env{'request.course.id'});
                   7647:     return unless ($priv eq 'bre');
                   7648:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7649:     return if ($env{'request.state'} eq 'construct');
                   7650:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   7651:     return unless (keys(%cachedblockers) > 0);
                   7652:     my (%possibles,@symbs);
                   7653:     if (!$symb) {
                   7654:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  7655:     }
1.1282    raeburn  7656:     if ($symb) {
                   7657:         @symbs = ($symb);
                   7658:     } elsif (keys(%possibles)) { 
                   7659:         @symbs = keys(%possibles);
                   7660:     }
                   7661:     my $noblock;
                   7662:     foreach my $symb (@symbs) {
                   7663:         last if ($noblock);
                   7664:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   7665:         foreach my $block (keys(%cachedblockers)) {
                   7666:             if ($block =~ /^firstaccess____(.+)$/) {
                   7667:                 my $item = $1;
                   7668:                 if (($item eq $map) || ($item eq $symb)) {
                   7669:                     $noblock = 1;
                   7670:                     last;
                   7671:                 }
                   7672:             }
                   7673:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   7674:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   7675:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   7676:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   7677:                             push(@blockers,$block);
                   7678:                         }
                   7679:                     }
                   7680:                 }
1.1162    raeburn  7681:             }
1.1282    raeburn  7682:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   7683:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   7684:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   7685:                         push(@blockers,$block);
                   7686:                     }
                   7687:                 }
1.1162    raeburn  7688:             }
                   7689:         }
                   7690:     }
1.1282    raeburn  7691:     return if ($noblock);
                   7692:     return @blockers;
                   7693: }
1.1162    raeburn  7694: }
                   7695: 
1.1282    raeburn  7696: # -------------------------------- Deversion and split uri into path an filename   
                   7697: 
1.1133    foxr     7698: #
1.1282    raeburn  7699: #   Removes the version from a URI and
1.1133    foxr     7700: #   splits it in to its filename and path to the filename.
                   7701: #   Seems like File::Basename could have done this more clearly.
                   7702: #   Parameters:
                   7703: #      $uri   - input URI
                   7704: #   Returns:
                   7705: #     Two element list consisting of 
                   7706: #     $pathname  - the URI up to and excluding the trailing /
                   7707: #     $filename  - The part of the URI following the last /
                   7708: #  NOTE:
                   7709: #    Another realization of this is simply:
                   7710: #    use File::Basename;
                   7711: #    ...
                   7712: #    $uri = shift;
                   7713: #    $filename = basename($uri);
                   7714: #    $path     = dirname($uri);
                   7715: #    return ($filename, $path);
                   7716: #
                   7717: #     The implementation below is probably faster however.
                   7718: #
1.710     albertel 7719: sub split_uri_for_cond {
                   7720:     my $uri=&deversion(&declutter(shift));
                   7721:     my @uriparts=split(/\//,$uri);
                   7722:     my $filename=pop(@uriparts);
                   7723:     my $pathname=join('/',@uriparts);
                   7724:     return ($pathname,$filename);
                   7725: }
1.232     www      7726: # --------------------------------------------------- Is a resource on the map?
                   7727: 
                   7728: sub is_on_map {
1.710     albertel 7729:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7730:     #Trying to find the conditional for the file
1.620     albertel 7731:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7732: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7733:     if ($match) {
1.289     bowersj2 7734: 	return (1,$1);
                   7735:     } else {
1.434     www      7736: 	return (0,0);
1.289     bowersj2 7737:     }
1.12      www      7738: }
                   7739: 
1.427     www      7740: # --------------------------------------------------------- Get symb from alias
                   7741: 
                   7742: sub get_symb_from_alias {
                   7743:     my $symb=shift;
                   7744:     my ($map,$resid,$url)=&decode_symb($symb);
                   7745: # Already is a symb
                   7746:     if ($url) { return $symb; }
                   7747: # Must be an alias
                   7748:     my $aliassymb='';
                   7749:     my %bighash;
1.620     albertel 7750:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7751:                             &GDBM_READER(),0640)) {
                   7752:         my $rid=$bighash{'mapalias_'.$symb};
                   7753: 	if ($rid) {
                   7754: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7755: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7756: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7757: 	}
                   7758:         untie %bighash;
                   7759:     }
                   7760:     return $aliassymb;
                   7761: }
                   7762: 
1.12      www      7763: # ----------------------------------------------------------------- Define Role
                   7764: 
                   7765: sub definerole {
                   7766:   if (allowed('mcr','/')) {
                   7767:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7768:     foreach my $role (split(':',$sysrole)) {
                   7769: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7770:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7771:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7772: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7773:                return "refused:s:$crole&$cqual"; 
                   7774:             }
                   7775:         }
1.191     harris41 7776:     }
1.800     albertel 7777:     foreach my $role (split(':',$domrole)) {
                   7778: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7779:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7780:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7781: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7782:                return "refused:d:$crole&$cqual"; 
                   7783:             }
                   7784:         }
1.191     harris41 7785:     }
1.800     albertel 7786:     foreach my $role (split(':',$courole)) {
                   7787: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7788:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7789:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7790: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7791:                return "refused:c:$crole&$cqual"; 
                   7792:             }
                   7793:         }
1.191     harris41 7794:     }
1.620     albertel 7795:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7796:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7797: 	        "rolesdef_$rolename=".
                   7798:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7799:     return reply($command,$env{'user.home'});
1.12      www      7800:   } else {
                   7801:     return 'refused';
                   7802:   }
1.105     harris41 7803: }
                   7804: 
                   7805: # ---------------- Make a metadata query against the network of library servers
                   7806: 
                   7807: sub metadata_query {
1.1237    raeburn  7808:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7809:     my %rhash;
1.845     albertel 7810:     my %libserv = &all_library();
1.244     matthew  7811:     my @server_list = (defined($server_array) ? @$server_array
                   7812:                                               : keys(%libserv) );
                   7813:     for my $server (@server_list) {
1.1237    raeburn  7814:         my $domains = ''; 
                   7815:         if (ref($domains_hash) eq 'HASH') {
                   7816:             $domains = $domains_hash->{$server}; 
                   7817:         }
1.118     harris41 7818: 	unless ($custom or $customshow) {
1.1237    raeburn  7819: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7820: 	    $rhash{$server}=$reply;
                   7821: 	}
                   7822: 	else {
                   7823: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  7824: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7825: 			     $server);
                   7826: 	    $rhash{$server}=$reply;
                   7827: 	}
1.112     harris41 7828:     }
1.118     harris41 7829:     return \%rhash;
1.240     www      7830: }
                   7831: 
                   7832: # ----------------------------------------- Send log queries and wait for reply
                   7833: 
                   7834: sub log_query {
                   7835:     my ($uname,$udom,$query,%filters)=@_;
                   7836:     my $uhome=&homeserver($uname,$udom);
                   7837:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7838:     my $uhost=&hostname($uhome);
1.800     albertel 7839:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7840:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7841:                        $uhome);
1.479     albertel 7842:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7843:     return get_query_reply($queryid);
                   7844: }
                   7845: 
1.818     raeburn  7846: # -------------------------- Update MySQL table for portfolio file
                   7847: 
                   7848: sub update_portfolio_table {
1.821     raeburn  7849:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7850:     if ($group ne '') {
                   7851:         $file_name =~s /^\Q$group\E//;
                   7852:     }
1.818     raeburn  7853:     my $homeserver = &homeserver($uname,$udom);
                   7854:     my $queryid=
1.821     raeburn  7855:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7856:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7857:     my $reply = &get_query_reply($queryid);
                   7858:     return $reply;
                   7859: }
                   7860: 
1.899     raeburn  7861: # -------------------------- Update MySQL allusers table
                   7862: 
                   7863: sub update_allusers_table {
                   7864:     my ($uname,$udom,$names) = @_;
                   7865:     my $homeserver = &homeserver($uname,$udom);
                   7866:     my $queryid=
                   7867:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7868:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7869:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7870:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7871:                'generation='.&escape($names->{'generation'}).'%%'.
                   7872:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7873:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7874:     return;
1.899     raeburn  7875: }
                   7876: 
1.508     raeburn  7877: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7878: 
                   7879: sub fetch_enrollment_query {
1.511     raeburn  7880:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  7881:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  7882:     my $maxtries = 1;
1.508     raeburn  7883:     if ($context eq 'automated') {
                   7884:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  7885:         $sleep = 2;
                   7886:         $loopmax = 100;
1.547     raeburn  7887:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7888:     } else {
                   7889:         $homeserver = &homeserver($cnum,$dom);
                   7890:     }
1.838     albertel 7891:     my $host=&hostname($homeserver);
1.506     raeburn  7892:     my $cmd = '';
1.1000    raeburn  7893:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7894:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7895:     }
                   7896:     $cmd =~ s/%%$//;
                   7897:     $cmd = &escape($cmd);
                   7898:     my $query = 'fetchenrollment';
1.620     albertel 7899:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7900:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7901:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7902:         return 'error: '.$queryid;
                   7903:     }
1.1317    raeburn  7904:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  7905:     my $tries = 1;
                   7906:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  7907:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  7908:         $tries ++;
                   7909:     }
1.526     raeburn  7910:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7911:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7912:     } else {
1.901     albertel 7913:         my @responses = split(/:/,$reply);
1.515     raeburn  7914:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7915:             foreach my $line (@responses) {
                   7916:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7917:                 $$replyref{$key} = $value;
                   7918:             }
                   7919:         } else {
1.1117    foxr     7920:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7921:             foreach my $line (@responses) {
                   7922:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7923:                 $$replyref{$key} = $value;
                   7924:                 if ($value > 0) {
1.800     albertel 7925:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7926:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7927:                         my $destname = $pathname.'/'.$filename;
                   7928:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7929:                         if ($xml_classlist =~ /^error/) {
                   7930:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7931:                         } else {
1.506     raeburn  7932:                             if ( open(FILE,">$destname") ) {
                   7933:                                 print FILE &unescape($xml_classlist);
                   7934:                                 close(FILE);
1.526     raeburn  7935:                             } else {
                   7936:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7937:                             }
                   7938:                         }
                   7939:                     }
                   7940:                 }
                   7941:             }
                   7942:         }
                   7943:         return 'ok';
                   7944:     }
                   7945:     return 'error';
                   7946: }
                   7947: 
1.242     www      7948: sub get_query_reply {
1.1317    raeburn  7949:     my ($queryid,$sleep,$loopmax) = @_;;
                   7950:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   7951:         $sleep = 0.2;
                   7952:     }
                   7953:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   7954:         $loopmax = 100;
                   7955:     }
1.1117    foxr     7956:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7957:     my $reply='';
1.1317    raeburn  7958:     for (1..$loopmax) {
                   7959: 	sleep($sleep);
1.240     www      7960:         if (-e $replyfile.'.end') {
1.448     albertel 7961: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7962: 		$reply = join('',<$fh>);
                   7963: 		close($fh);
1.240     www      7964: 	   } else { return 'error: reply_file_error'; }
1.242     www      7965:            return &unescape($reply);
                   7966: 	}
1.240     www      7967:     }
1.242     www      7968:     return 'timeout:'.$queryid;
1.240     www      7969: }
                   7970: 
                   7971: sub courselog_query {
1.241     www      7972: #
                   7973: # possible filters:
                   7974: # url: url or symb
                   7975: # username
                   7976: # domain
                   7977: # action: view, submit, grade
                   7978: # start: timestamp
                   7979: # end: timestamp
                   7980: #
1.240     www      7981:     my (%filters)=@_;
1.620     albertel 7982:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7983:     if ($filters{'url'}) {
                   7984: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7985:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7986:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7987:     }
1.620     albertel 7988:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7989:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7990:     return &log_query($cname,$cdom,'courselog',%filters);
                   7991: }
                   7992: 
                   7993: sub userlog_query {
1.858     raeburn  7994: #
                   7995: # possible filters:
                   7996: # action: log check role
                   7997: # start: timestamp
                   7998: # end: timestamp
                   7999: #
1.240     www      8000:     my ($uname,$udom,%filters)=@_;
                   8001:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8002: }
                   8003: 
1.506     raeburn  8004: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8005: 
                   8006: sub auto_run {
1.508     raeburn  8007:     my ($cnum,$cdom) = @_;
1.876     raeburn  8008:     my $response = 0;
                   8009:     my $settings;
                   8010:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8011:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8012:         $settings = $domconfig{'autoenroll'};
                   8013:         if ($settings->{'run'} eq '1') {
                   8014:             $response = 1;
                   8015:         }
                   8016:     } else {
1.934     raeburn  8017:         my $homeserver;
                   8018:         if (&is_course($cdom,$cnum)) {
                   8019:             $homeserver = &homeserver($cnum,$cdom);
                   8020:         } else {
                   8021:             $homeserver = &domain($cdom,'primary');
                   8022:         }
                   8023:         if ($homeserver ne 'no_host') {
                   8024:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8025:         }
1.876     raeburn  8026:     }
1.506     raeburn  8027:     return $response;
                   8028: }
1.776     albertel 8029: 
1.506     raeburn  8030: sub auto_get_sections {
1.508     raeburn  8031:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8032:     my $homeserver;
                   8033:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8034:         $homeserver = &homeserver($cnum,$cdom);
                   8035:     }
                   8036:     if (!defined($homeserver)) { 
                   8037:         if ($cdom =~ /^$match_domain$/) {
                   8038:             $homeserver = &domain($cdom,'primary');
                   8039:         }
                   8040:     }
                   8041:     my @secs;
                   8042:     if (defined($homeserver)) {
                   8043:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8044:         unless ($response eq 'refused') {
                   8045:             @secs = split(/:/,$response);
                   8046:         }
1.506     raeburn  8047:     }
                   8048:     return @secs;
                   8049: }
1.776     albertel 8050: 
1.506     raeburn  8051: sub auto_new_course {
1.1099    raeburn  8052:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8053:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8054:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8055:     return $response;
                   8056: }
1.776     albertel 8057: 
1.506     raeburn  8058: sub auto_validate_courseID {
1.508     raeburn  8059:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8060:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8061:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8062:     return $response;
                   8063: }
1.776     albertel 8064: 
1.1007    raeburn  8065: sub auto_validate_instcode {
1.1020    raeburn  8066:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8067:     my ($homeserver,$response);
                   8068:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8069:         $homeserver = &homeserver($cnum,$cdom);
                   8070:     }
                   8071:     if (!defined($homeserver)) {
                   8072:         if ($cdom =~ /^$match_domain$/) {
                   8073:             $homeserver = &domain($cdom,'primary');
                   8074:         }
                   8075:     }
1.1065    raeburn  8076:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8077:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  8078:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8079:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8080: }
                   8081: 
1.506     raeburn  8082: sub auto_create_password {
1.873     raeburn  8083:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8084:     my ($homeserver,$response);
1.506     raeburn  8085:     my $create_passwd = 0;
                   8086:     my $authchk = '';
1.873     raeburn  8087:     if ($udom =~ /^$match_domain$/) {
                   8088:         $homeserver = &domain($udom,'primary');
                   8089:     }
                   8090:     if ($homeserver eq '') {
                   8091:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8092:             $homeserver = &homeserver($cnum,$cdom);
                   8093:         }
                   8094:     }
                   8095:     if ($homeserver eq '') {
                   8096:         $authchk = 'nodomain';
1.506     raeburn  8097:     } else {
1.873     raeburn  8098:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8099:         if ($response eq 'refused') {
                   8100:             $authchk = 'refused';
                   8101:         } else {
1.901     albertel 8102:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8103:         }
1.506     raeburn  8104:     }
                   8105:     return ($authparam,$create_passwd,$authchk);
                   8106: }
                   8107: 
1.706     raeburn  8108: sub auto_photo_permission {
                   8109:     my ($cnum,$cdom,$students) = @_;
                   8110:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8111:     my ($outcome,$perm_reqd,$conditions) = 
                   8112: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8113:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8114: 	return (undef,undef);
                   8115:     }
1.706     raeburn  8116:     return ($outcome,$perm_reqd,$conditions);
                   8117: }
                   8118: 
                   8119: sub auto_checkphotos {
                   8120:     my ($uname,$udom,$pid) = @_;
                   8121:     my $homeserver = &homeserver($uname,$udom);
                   8122:     my ($result,$resulttype);
                   8123:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8124: 				   &escape($uname).':'.&escape($pid),
                   8125: 				   $homeserver));
1.709     albertel 8126:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8127: 	return (undef,undef);
                   8128:     }
1.706     raeburn  8129:     if ($outcome) {
                   8130:         ($result,$resulttype) = split(/:/,$outcome);
                   8131:     } 
                   8132:     return ($result,$resulttype);
                   8133: }
                   8134: 
                   8135: sub auto_photochoice {
                   8136:     my ($cnum,$cdom) = @_;
                   8137:     my $homeserver = &homeserver($cnum,$cdom);
                   8138:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8139: 						       &escape($cdom),
                   8140: 						       $homeserver)));
1.709     albertel 8141:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8142: 	return (undef,undef);
                   8143:     }
1.706     raeburn  8144:     return ($update,$comment);
                   8145: }
                   8146: 
                   8147: sub auto_photoupdate {
                   8148:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8149:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8150:     my $host=&hostname($homeserver);
1.706     raeburn  8151:     my $cmd = '';
                   8152:     my $maxtries = 1;
1.800     albertel 8153:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8154:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8155:     }
                   8156:     $cmd =~ s/%%$//;
                   8157:     $cmd = &escape($cmd);
                   8158:     my $query = 'institutionalphotos';
                   8159:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8160:     unless ($queryid=~/^\Q$host\E\_/) {
                   8161:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8162:         return 'error: '.$queryid;
                   8163:     }
                   8164:     my $reply = &get_query_reply($queryid);
                   8165:     my $tries = 1;
                   8166:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8167:         $reply = &get_query_reply($queryid);
                   8168:         $tries ++;
                   8169:     }
                   8170:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8171:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8172:     } else {
                   8173:         my @responses = split(/:/,$reply);
                   8174:         my $outcome = shift(@responses); 
                   8175:         foreach my $item (@responses) {
                   8176:             my ($key,$value) = split(/=/,$item);
                   8177:             $$photo{$key} = $value;
                   8178:         }
                   8179:         return $outcome;
                   8180:     }
                   8181:     return 'error';
                   8182: }
                   8183: 
1.521     raeburn  8184: sub auto_instcode_format {
1.793     albertel 8185:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8186: 	$cat_order) = @_;
1.521     raeburn  8187:     my $courses = '';
1.772     raeburn  8188:     my @homeservers;
1.521     raeburn  8189:     if ($caller eq 'global') {
1.841     albertel 8190: 	my %servers = &get_servers($codedom,'library');
                   8191: 	foreach my $tryserver (keys(%servers)) {
                   8192: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8193: 		push(@homeservers,$tryserver);
                   8194: 	    }
1.584     raeburn  8195:         }
1.1022    raeburn  8196:     } elsif ($caller eq 'requests') {
                   8197:         if ($codedom =~ /^$match_domain$/) {
                   8198:             my $chome = &domain($codedom,'primary');
                   8199:             unless ($chome eq 'no_host') {
                   8200:                 push(@homeservers,$chome);
                   8201:             }
                   8202:         }
1.521     raeburn  8203:     } else {
1.772     raeburn  8204:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8205:     }
1.793     albertel 8206:     foreach my $code (keys(%{$instcodes})) {
                   8207:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8208:     }
                   8209:     chop($courses);
1.772     raeburn  8210:     my $ok_response = 0;
                   8211:     my $response;
                   8212:     while (@homeservers > 0 && $ok_response == 0) {
                   8213:         my $server = shift(@homeservers); 
                   8214:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8215:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8216:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8217: 		split(/:/,$response);
1.772     raeburn  8218:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8219:             push(@{$codetitles},&str2array($codetitles_str));
                   8220:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8221:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8222:             $ok_response = 1;
                   8223:         }
                   8224:     }
                   8225:     if ($ok_response) {
1.521     raeburn  8226:         return 'ok';
1.772     raeburn  8227:     } else {
                   8228:         return $response;
1.521     raeburn  8229:     }
                   8230: }
                   8231: 
1.792     raeburn  8232: sub auto_instcode_defaults {
                   8233:     my ($domain,$returnhash,$code_order) = @_;
                   8234:     my @homeservers;
1.841     albertel 8235: 
                   8236:     my %servers = &get_servers($domain,'library');
                   8237:     foreach my $tryserver (keys(%servers)) {
                   8238: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8239: 	    push(@homeservers,$tryserver);
                   8240: 	}
1.792     raeburn  8241:     }
1.841     albertel 8242: 
1.792     raeburn  8243:     my $response;
1.841     albertel 8244:     foreach my $server (@homeservers) {
1.792     raeburn  8245:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8246:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8247: 	
                   8248: 	foreach my $pair (split(/\&/,$response)) {
                   8249: 	    my ($name,$value)=split(/\=/,$pair);
                   8250: 	    if ($name eq 'code_order') {
                   8251: 		@{$code_order} = split(/\&/,&unescape($value));
                   8252: 	    } else {
                   8253: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8254: 	    }
                   8255: 	}
                   8256: 	return 'ok';
1.792     raeburn  8257:     }
1.841     albertel 8258: 
                   8259:     return $response;
1.1003    raeburn  8260: }
                   8261: 
                   8262: sub auto_possible_instcodes {
1.1007    raeburn  8263:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8264:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8265:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8266:         return;
                   8267:     }
1.1003    raeburn  8268:     my (@homeservers,$uhome);
                   8269:     if (defined(&domain($domain,'primary'))) {
                   8270:         $uhome=&domain($domain,'primary');
                   8271:         push(@homeservers,&domain($domain,'primary'));
                   8272:     } else {
                   8273:         my %servers = &get_servers($domain,'library');
                   8274:         foreach my $tryserver (keys(%servers)) {
                   8275:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8276:                 push(@homeservers,$tryserver);
                   8277:             }
                   8278:         }
                   8279:     }
                   8280:     my $response;
                   8281:     foreach my $server (@homeservers) {
                   8282:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8283:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8284:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8285:             split(':',$response);
                   8286:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8287:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8288:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8289:             my ($name,$value)=split('=',$item);
                   8290:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8291:         }
                   8292:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8293:             my ($name,$value)=split('=',$item);
                   8294:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8295:         }
                   8296:         return 'ok';
                   8297:     }
                   8298:     return $response;
                   8299: }
1.792     raeburn  8300: 
1.1010    raeburn  8301: sub auto_courserequest_checks {
                   8302:     my ($dom) = @_;
1.1020    raeburn  8303:     my ($homeserver,%validations);
                   8304:     if ($dom =~ /^$match_domain$/) {
                   8305:         $homeserver = &domain($dom,'primary');
                   8306:     }
                   8307:     unless ($homeserver eq 'no_host') {
                   8308:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8309:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8310:             my @items = split(/&/,$response);
                   8311:             foreach my $item (@items) {
                   8312:                 my ($key,$value) = split('=',$item);
                   8313:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8314:             }
                   8315:         }
                   8316:     }
1.1010    raeburn  8317:     return %validations; 
                   8318: }
                   8319: 
1.1020    raeburn  8320: sub auto_courserequest_validation {
1.1255    raeburn  8321:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8322:     my ($homeserver,$response);
                   8323:     if ($dom =~ /^$match_domain$/) {
                   8324:         $homeserver = &domain($dom,'primary');
                   8325:     }
1.1255    raeburn  8326:     unless ($homeserver eq 'no_host') {
                   8327:         my $customdata;
                   8328:         if (ref($custominfo) eq 'HASH') {
                   8329:             $customdata = &freeze_escape($custominfo);
                   8330:         }
1.1020    raeburn  8331:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8332:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  8333:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8334:                                     $customdata,$homeserver));
1.1020    raeburn  8335:     }
                   8336:     return $response;
                   8337: }
                   8338: 
1.777     albertel 8339: sub auto_validate_class_sec {
1.918     raeburn  8340:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8341:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8342:     my $ownerlist;
                   8343:     if (ref($owners) eq 'ARRAY') {
                   8344:         $ownerlist = join(',',@{$owners});
                   8345:     } else {
                   8346:         $ownerlist = $owners;
                   8347:     }
1.773     raeburn  8348:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8349:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8350:     return $response;
                   8351: }
                   8352: 
1.1248    raeburn  8353: sub auto_crsreq_update {
                   8354:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  8355:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  8356:     my ($homeserver,%crsreqresponse);
                   8357:     if ($cdom =~ /^$match_domain$/) {
                   8358:         $homeserver = &domain($cdom,'primary');
                   8359:     }
                   8360:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8361:         my $info;
                   8362:         if (ref($inbound) eq 'HASH') {
                   8363:             $info = &freeze_escape($inbound);
                   8364:         }
                   8365:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8366:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8367:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  8368:                             &escape($title).':'.&escape($code).':'.
                   8369:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   8370:                             $homeserver);
1.1248    raeburn  8371:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8372:             my @items = split(/&/,$response);
                   8373:             foreach my $item (@items) {
                   8374:                 my ($key,$value) = split('=',$item);
                   8375:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8376:             }
                   8377:         }
                   8378:     }
                   8379:     return \%crsreqresponse;
                   8380: }
                   8381: 
1.1305    raeburn  8382: sub auto_export_grades {
1.1309    raeburn  8383:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8384:     my ($homeserver,%exportresponse);
                   8385:     if ($cdom =~ /^$match_domain$/) {
                   8386:         $homeserver = &domain($cdom,'primary');
                   8387:     }
                   8388:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8389:         my $info;
                   8390:         if (ref($inforef) eq 'HASH') {
                   8391:             $info = &freeze_escape($inforef);
                   8392:         }
                   8393:         if (ref($gradesref) eq 'HASH') {
                   8394:             my $grades = &freeze_escape($gradesref);
                   8395:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   8396:                                 $info.':'.$grades,$homeserver);
                   8397:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   8398:                 my @items = split(/&/,$response);
                   8399:                 foreach my $item (@items) {
                   8400:                     my ($key,$value) = split('=',$item);
                   8401:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   8402:                 }
                   8403:             }
                   8404:         }
                   8405:     }
                   8406:     return \%exportresponse;
1.1305    raeburn  8407: }
                   8408: 
1.1287    raeburn  8409: sub check_instcode_cloning {
                   8410:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8411:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8412:         return;
                   8413:     }
                   8414:     my $canclone;
                   8415:     if (@{$code_order} > 0) {
                   8416:         my $instcoderegexp ='^';
                   8417:         my @clonecodes = split(/\&/,$cloner);
                   8418:         foreach my $item (@{$code_order}) {
                   8419:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8420:                 foreach my $pair (@clonecodes) {
                   8421:                     my ($key,$val) = split(/\=/,$pair,2);
                   8422:                     $val = &unescape($val);
                   8423:                     if ($key eq $item) {
                   8424:                         $instcoderegexp .= '('.$val.')';
                   8425:                         last;
                   8426:                     }
                   8427:                 }
                   8428:             } else {
                   8429:                 $instcoderegexp .= $codedefaults->{$item};
                   8430:             }
                   8431:         }
                   8432:         $instcoderegexp .= '$';
                   8433:         my (@from,@to);
                   8434:         eval {
                   8435:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8436:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8437:         };
                   8438:         if ((@from > 0) && (@to > 0)) {
                   8439:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8440:             if (!@diffs) {
                   8441:                 $canclone = 1;
                   8442:             }
                   8443:         }
                   8444:     }
                   8445:     return $canclone;
                   8446: }
                   8447: 
                   8448: sub default_instcode_cloning {
                   8449:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8450:     my (%codedefaults,@code_order,$canclone);
                   8451:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8452:         %codedefaults = %{$codedefaultsref};
                   8453:         @code_order = @{$codeorderref};
                   8454:     } elsif ($clonedom) {
                   8455:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8456:     }
                   8457:     if (($domdefclone) && (@code_order)) {
                   8458:         my @clonecodes = split(/\+/,$domdefclone);
                   8459:         my $instcoderegexp ='^';
                   8460:         foreach my $item (@code_order) {
                   8461:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8462:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8463:             } else {
                   8464:                 $instcoderegexp .= $codedefaults{$item};
                   8465:             }
                   8466:         }
                   8467:         $instcoderegexp .= '$';
                   8468:         my (@from,@to);
                   8469:         eval {
                   8470:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8471:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8472:         };
                   8473:         if ((@from > 0) && (@to > 0)) {
                   8474:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8475:             if (!@diffs) {
                   8476:                 $canclone = 1;
                   8477:             }
                   8478:         }
                   8479:     }
                   8480:     return $canclone;
                   8481: }
                   8482: 
1.679     raeburn  8483: # ------------------------------------------------------- Course Group routines
                   8484: 
                   8485: sub get_coursegroups {
1.809     raeburn  8486:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8487:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8488: }
                   8489: 
1.679     raeburn  8490: sub modify_coursegroup {
                   8491:     my ($cdom,$cnum,$groupsettings) = @_;
                   8492:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8493: }
                   8494: 
1.809     raeburn  8495: sub toggle_coursegroup_status {
                   8496:     my ($cdom,$cnum,$group,$action) = @_;
                   8497:     my ($from_namespace,$to_namespace);
                   8498:     if ($action eq 'delete') {
                   8499:         $from_namespace = 'coursegroups';
                   8500:         $to_namespace = 'deleted_groups';
                   8501:     } else {
                   8502:         $from_namespace = 'deleted_groups';
                   8503:         $to_namespace = 'coursegroups';
                   8504:     }
                   8505:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8506:     if (my $tmp = &error(%curr_group)) {
                   8507:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8508:         return ('read error',$tmp);
                   8509:     } else {
                   8510:         my %savedsettings = %curr_group; 
1.809     raeburn  8511:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8512:         my $deloutcome;
                   8513:         if ($result eq 'ok') {
1.809     raeburn  8514:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8515:         } else {
                   8516:             return ('write error',$result);
                   8517:         }
                   8518:         if ($deloutcome eq 'ok') {
                   8519:             return 'ok';
                   8520:         } else {
                   8521:             return ('delete error',$deloutcome);
                   8522:         }
                   8523:     }
                   8524: }
                   8525: 
1.679     raeburn  8526: sub modify_group_roles {
1.957     raeburn  8527:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8528:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8529:     my $role = 'gr/'.&escape($userprivs);
                   8530:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8531:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8532:     if ($result eq 'ok') {
                   8533:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8534:     }
1.679     raeburn  8535:     return $result;
                   8536: }
                   8537: 
                   8538: sub modify_coursegroup_membership {
                   8539:     my ($cdom,$cnum,$membership) = @_;
                   8540:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8541:     return $result;
                   8542: }
                   8543: 
1.682     raeburn  8544: sub get_active_groups {
                   8545:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8546:     my $now = time;
                   8547:     my %groups = ();
                   8548:     foreach my $key (keys(%env)) {
1.811     albertel 8549:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8550:             my ($start,$end) = split(/\./,$env{$key});
                   8551:             if (($end!=0) && ($end<$now)) { next; }
                   8552:             if (($start!=0) && ($start>$now)) { next; }
                   8553:             if ($1 eq $cdom && $2 eq $cnum) {
                   8554:                 $groups{$3} = $env{$key} ;
                   8555:             }
                   8556:         }
                   8557:     }
                   8558:     return %groups;
                   8559: }
                   8560: 
1.683     raeburn  8561: sub get_group_membership {
                   8562:     my ($cdom,$cnum,$group) = @_;
                   8563:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8564: }
                   8565: 
                   8566: sub get_users_groups {
                   8567:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8568:     my @usersgroups;
1.683     raeburn  8569:     my $cachetime=1800;
                   8570: 
                   8571:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8572:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8573:     if (defined($cached)) {
1.734     albertel 8574:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8575:     } else {  
                   8576:         $grouplist = '';
1.816     raeburn  8577:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8578:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8579:         my $access_end = $env{'course.'.$courseid.
                   8580:                               '.default_enrollment_end_date'};
                   8581:         my $now = time;
                   8582:         foreach my $key (keys(%roleshash)) {
                   8583:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8584:                 my $group = $1;
                   8585:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8586:                     my $start = $2;
                   8587:                     my $end = $1;
                   8588:                     if ($start == -1) { next; } # deleted from group
                   8589:                     if (($start!=0) && ($start>$now)) { next; }
                   8590:                     if (($end!=0) && ($end<$now)) {
                   8591:                         if ($access_end && $access_end < $now) {
                   8592:                             if ($access_end - $end < 86400) {
                   8593:                                 push(@usersgroups,$group);
1.733     raeburn  8594:                             }
                   8595:                         }
1.817     raeburn  8596:                         next;
1.733     raeburn  8597:                     }
1.817     raeburn  8598:                     push(@usersgroups,$group);
1.683     raeburn  8599:                 }
                   8600:             }
                   8601:         }
1.817     raeburn  8602:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8603:         $grouplist = join(':',@usersgroups);
                   8604:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8605:     }
1.733     raeburn  8606:     return @usersgroups;
1.683     raeburn  8607: }
                   8608: 
                   8609: sub devalidate_getgroups_cache {
                   8610:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8611:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8612: 
1.683     raeburn  8613:     my $hashid="$udom:$uname:$courseid";
                   8614:     &devalidate_cache_new('getgroups',$hashid);
                   8615: }
                   8616: 
1.12      www      8617: # ------------------------------------------------------------------ Plain Text
                   8618: 
                   8619: sub plaintext {
1.988     raeburn  8620:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8621:     if ($short =~ m{^cr/}) {
1.758     albertel 8622: 	return (split('/',$short))[-1];
                   8623:     }
1.742     raeburn  8624:     if (!defined($cid)) {
                   8625:         $cid = $env{'request.course.id'};
                   8626:     }
                   8627:     my %rolenames = (
1.1008    raeburn  8628:                       Course    => 'std',
                   8629:                       Community => 'alt1',
1.1305    raeburn  8630:                       Placement => 'std',
1.742     raeburn  8631:                     );
1.1037    raeburn  8632:     if ($cid ne '') {
                   8633:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8634:             unless ($forcedefault) {
                   8635:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8636:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8637:                 return &Apache::lonlocal::mt($roletext);
                   8638:             }
                   8639:         }
                   8640:     }
                   8641:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8642:         (defined($rolenames{$type})) && 
                   8643:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8644:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8645:     } elsif ($cid ne '') {
                   8646:         my $crstype = $env{'course.'.$cid.'.type'};
                   8647:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8648:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8649:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8650:         }
1.742     raeburn  8651:     }
1.1037    raeburn  8652:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8653: }
                   8654: 
                   8655: # ----------------------------------------------------------------- Assign Role
                   8656: 
                   8657: sub assignrole {
1.957     raeburn  8658:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8659:         $context)=@_;
1.21      www      8660:     my $mrole;
                   8661:     if ($role =~ /^cr\//) {
1.393     www      8662:         my $cwosec=$url;
1.811     albertel 8663:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8664: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8665:            my $refused = 1;
                   8666:            if ($context eq 'requestcourses') {
                   8667:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8668:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8669:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8670:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8671:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8672:                            if ($crsenv{'internal.courseowner'} eq
                   8673:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8674:                                $refused = '';
                   8675:                            }
                   8676:                        }
                   8677:                    }
                   8678:                }
                   8679:            }
                   8680:            if ($refused) {
                   8681:                &logthis('Refused custom assignrole: '.
                   8682:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8683:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8684:                return 'refused';
                   8685:            }
1.104     www      8686:         }
1.21      www      8687:         $mrole='cr';
1.678     raeburn  8688:     } elsif ($role =~ /^gr\//) {
                   8689:         my $cwogrp=$url;
1.811     albertel 8690:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8691:         unless (&allowed('mdg',$cwogrp)) {
                   8692:             &logthis('Refused group assignrole: '.
                   8693:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8694:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8695:             return 'refused';
                   8696:         }
                   8697:         $mrole='gr';
1.21      www      8698:     } else {
1.82      www      8699:         my $cwosec=$url;
1.811     albertel 8700:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8701:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8702:             my $refused;
                   8703:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8704:                 if (!(&allowed('c'.$role,$url))) {
                   8705:                     $refused = 1;
                   8706:                 }
                   8707:             } else {
                   8708:                 $refused = 1;
                   8709:             }
1.947     raeburn  8710:             if ($refused) {
1.1045    raeburn  8711:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8712:                 if (!$selfenroll && $context eq 'course') {
                   8713:                     my %crsenv;
                   8714:                     if ($role eq 'cc' || $role eq 'co') {
                   8715:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8716:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8717:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8718:                                 if ($crsenv{'internal.courseowner'} eq 
                   8719:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8720:                                     $refused = '';
                   8721:                                 }
                   8722:                             }
                   8723:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8724:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8725:                                 if ($crsenv{'internal.courseowner'} eq 
                   8726:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8727:                                     $refused = '';
                   8728:                                 }
                   8729:                             }
                   8730:                         }
                   8731:                     }
                   8732:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8733:                     $refused = '';
1.1017    raeburn  8734:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8735:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8736:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8737:                         my $wrongcc;
                   8738:                         if ($cnum =~ /^$match_community$/) {
                   8739:                             $wrongcc = 1 if ($role eq 'cc');
                   8740:                         } else {
                   8741:                             $wrongcc = 1 if ($role eq 'co');
                   8742:                         }
                   8743:                         unless ($wrongcc) {
                   8744:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8745:                             if ($crsenv{'internal.courseowner'} eq 
                   8746:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8747:                                 $refused = '';
                   8748:                             }
1.1017    raeburn  8749:                         }
                   8750:                     }
1.1183    raeburn  8751:                 } elsif ($context eq 'requestauthor') {
                   8752:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   8753:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8754:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8755:                             $refused = '';
                   8756:                         } else {
                   8757:                             my %domdefaults = &get_domain_defaults($udom);
                   8758:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8759:                                 my $checkbystatus;
                   8760:                                 if ($env{'user.adv'}) { 
                   8761:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8762:                                     if ($disposition eq 'automatic') {
                   8763:                                         $refused = '';
                   8764:                                     } elsif ($disposition eq '') {
                   8765:                                         $checkbystatus = 1;
                   8766:                                     } 
                   8767:                                 } else {
                   8768:                                     $checkbystatus = 1;
                   8769:                                 }
                   8770:                                 if ($checkbystatus) {
                   8771:                                     if ($env{'environment.inststatus'}) {
                   8772:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8773:                                         foreach my $type (@inststatuses) {
                   8774:                                             if (($type ne '') &&
                   8775:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8776:                                                 $refused = '';
                   8777:                                             }
                   8778:                                         }
                   8779:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8780:                                         $refused = '';
                   8781:                                     }
                   8782:                                 }
                   8783:                             }
                   8784:                         }
                   8785:                     }
1.1017    raeburn  8786:                 }
                   8787:                 if ($refused) {
1.947     raeburn  8788:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8789:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8790: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8791:                     return 'refused';
                   8792:                 }
1.932     raeburn  8793:             }
1.1131    raeburn  8794:         } elsif ($role eq 'au') {
                   8795:             if ($url ne '/'.$udom.'/') {
                   8796:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8797:                          ' to assign author role for '.$uname.':'.$udom.
                   8798:                          ' in domain: '.$url.' refused (wrong domain).');
                   8799:                 return 'refused';
                   8800:             }
1.104     www      8801:         }
1.21      www      8802:         $mrole=$role;
                   8803:     }
1.620     albertel 8804:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8805:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8806:     if ($end) { $command.='_'.$end; }
1.21      www      8807:     if ($start) {
                   8808: 	if ($end) { 
1.81      www      8809:            $command.='_'.$start; 
1.21      www      8810:         } else {
1.81      www      8811:            $command.='_0_'.$start;
1.21      www      8812:         }
                   8813:     }
1.739     raeburn  8814:     my $origstart = $start;
                   8815:     my $origend = $end;
1.957     raeburn  8816:     my $delflag;
1.357     www      8817: # actually delete
                   8818:     if ($deleteflag) {
1.373     www      8819: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8820: # modify command to delete the role
1.620     albertel 8821:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8822:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8823: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8824: # set start and finish to negative values for userrolelog
                   8825:            $start=-1;
                   8826:            $end=-1;
1.957     raeburn  8827:            $delflag = 1;
1.357     www      8828:         }
                   8829:     }
                   8830: # send command
1.349     www      8831:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8832: # log new user role if status is ok
1.349     www      8833:     if ($answer eq 'ok') {
1.663     raeburn  8834: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  8835:         if (($role eq 'cc') || ($role eq 'in') ||
                   8836:             ($role eq 'ep') || ($role eq 'ad') ||
                   8837:             ($role eq 'ta') || ($role eq 'st') ||
                   8838:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8839:             ($role eq 'co')) {
1.1200    raeburn  8840: # for course roles, perform group memberships changes triggered by role change.
                   8841:             unless ($role =~ /^gr/) {
                   8842:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8843:                                                  $origstart,$selfenroll,$context);
                   8844:             }
1.1184    raeburn  8845:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8846:                            $selfenroll,$context);
                   8847:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8848:                  ($role eq 'au') || ($role eq 'dc')) {
                   8849:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8850:                            $context);
                   8851:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8852:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8853:                              $context); 
                   8854:         }
1.1053    raeburn  8855:         if ($role eq 'cc') {
                   8856:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8857:         }
1.349     www      8858:     }
                   8859:     return $answer;
1.169     harris41 8860: }
                   8861: 
1.1053    raeburn  8862: sub autoupdate_coowners {
                   8863:     my ($url,$end,$start,$uname,$udom) = @_;
                   8864:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8865:     if (($cdom ne '') && ($cnum ne '')) {
                   8866:         my $now = time;
                   8867:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8868:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8869:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8870:             my $instcode = $coursehash{'internal.coursecode'};
                   8871:             if ($instcode ne '') {
1.1056    raeburn  8872:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8873:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8874:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8875:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8876:                         if ($result eq 'valid') {
                   8877:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8878:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8879:                                     push(@newcoowners,$coowner);
                   8880:                                 }
                   8881:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8882:                                     push(@newcoowners,$uname.':'.$udom);
                   8883:                                 }
                   8884:                                 @newcoowners = sort(@newcoowners);
                   8885:                             } else {
                   8886:                                 push(@newcoowners,$uname.':'.$udom);
                   8887:                             }
                   8888:                         } else {
                   8889:                             if ($coursehash{'internal.co-owners'}) {
                   8890:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8891:                                     unless ($coowner eq $uname.':'.$udom) {
                   8892:                                         push(@newcoowners,$coowner);
                   8893:                                     }
                   8894:                                 }
                   8895:                                 unless (@newcoowners > 0) {
                   8896:                                     $delcoowners = 1;
                   8897:                                     $coowners = '';
                   8898:                                 }
                   8899:                             }
                   8900:                         }
                   8901:                         if (@newcoowners || $delcoowners) {
                   8902:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8903:                                             $delcoowners,@newcoowners);
                   8904:                         }
                   8905:                     }
                   8906:                 }
                   8907:             }
                   8908:         }
                   8909:     }
                   8910: }
                   8911: 
                   8912: sub store_coowners {
                   8913:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8914:     my $cid = $cdom.'_'.$cnum;
                   8915:     my ($coowners,$delresult,$putresult);
                   8916:     if (@newcoowners) {
                   8917:         $coowners = join(',',@newcoowners);
                   8918:         my %coownershash = (
                   8919:                             'internal.co-owners' => $coowners,
                   8920:                            );
                   8921:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8922:         if ($putresult eq 'ok') {
                   8923:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8924:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8925:             }
                   8926:         }
                   8927:     }
                   8928:     if ($delcoowners) {
                   8929:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8930:         if ($delresult eq 'ok') {
                   8931:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8932:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8933:             }
                   8934:         }
                   8935:     }
                   8936:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8937:         my %crsinfo =
                   8938:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8939:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8940:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8941:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8942:         }
                   8943:     }
                   8944: }
                   8945: 
1.169     harris41 8946: # -------------------------------------------------- Modify user authentication
1.197     www      8947: # Overrides without validation
                   8948: 
1.169     harris41 8949: sub modifyuserauth {
                   8950:     my ($udom,$uname,$umode,$upass)=@_;
                   8951:     my $uhome=&homeserver($uname,$udom);
1.197     www      8952:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8953:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8954:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8955:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8956:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8957: 		     &escape($upass),$uhome);
1.620     albertel 8958:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8959:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8960:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8961:     &log($udom,,$uname,$uhome,
1.620     albertel 8962:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8963:                                      $env{'user.name'}.', '.$umode.
1.197     www      8964:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8965:     unless ($reply eq 'ok') {
1.197     www      8966:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8967: 	return 'error: '.$reply;
                   8968:     }   
1.170     harris41 8969:     return 'ok';
1.80      www      8970: }
                   8971: 
1.81      www      8972: # --------------------------------------------------------------- Modify a user
1.80      www      8973: 
1.81      www      8974: sub modifyuser {
1.206     matthew  8975:     my ($udom,    $uname, $uid,
                   8976:         $umode,   $upass, $first,
                   8977:         $middle,  $last,  $gene,
1.1058    raeburn  8978:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8979:     $udom= &LONCAPA::clean_domain($udom);
                   8980:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8981:     my $showcandelete = 'none';
                   8982:     if (ref($candelete) eq 'ARRAY') {
                   8983:         if (@{$candelete} > 0) {
                   8984:             $showcandelete = join(', ',@{$candelete});
                   8985:         }
                   8986:     }
1.81      www      8987:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8988:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8989: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8990:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8991:                                      ' desiredhome not specified'). 
1.620     albertel 8992:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8993:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8994:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8995:     my $newuser;
                   8996:     if ($uhome eq 'no_host') {
                   8997:         $newuser = 1;
                   8998:     }
1.80      www      8999: # ----------------------------------------------------------------- Create User
1.406     albertel 9000:     if (($uhome eq 'no_host') && 
                   9001: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9002:         my $unhome='';
1.844     albertel 9003:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9004:             $unhome = $desiredhome;
1.620     albertel 9005: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9006: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9007:         } else { # load balancing routine for determining $unhome
1.81      www      9008:             my $loadm=10000000;
1.841     albertel 9009: 	    my %servers = &get_servers($udom,'library');
                   9010: 	    foreach my $tryserver (keys(%servers)) {
                   9011: 		my $answer=reply('load',$tryserver);
                   9012: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9013: 		    $loadm=$answer;
                   9014: 		    $unhome=$tryserver;
                   9015: 		}
1.80      www      9016: 	    }
                   9017:         }
                   9018:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9019: 	    return 'error: unable to find a home server for '.$uname.
                   9020:                    ' in domain '.$udom;
1.80      www      9021:         }
                   9022:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9023:                          &escape($upass),$unhome);
                   9024: 	unless ($reply eq 'ok') {
                   9025:             return 'error: '.$reply;
                   9026:         }   
1.230     stredwic 9027:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9028:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9029: 	    return 'error: unable verify users home machine.';
1.80      www      9030:         }
1.209     matthew  9031:     }   # End of creation of new user
1.80      www      9032: # ---------------------------------------------------------------------- Add ID
                   9033:     if ($uid) {
                   9034:        $uid=~tr/A-Z/a-z/;
                   9035:        my %uidhash=&idrget($udom,$uname);
1.196     www      9036:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9037:          && (!$forceid)) {
1.80      www      9038: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9039: 	      return 'error: user id "'.$uid.'" does not match '.
                   9040:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9041:           }
                   9042:        } else {
1.1300    raeburn  9043: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      9044:        }
                   9045:     }
                   9046: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9047:     my @tmp=&get('environment',
1.899     raeburn  9048: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9049:                     'permanentemail','inststatus'],
1.134     albertel 9050: 		   $udom,$uname);
1.1075    raeburn  9051:     my (%names,%oldnames);
1.313     matthew  9052:     if ($tmp[0] =~ m/^error:.*/) { 
                   9053:         %names=(); 
                   9054:     } else {
                   9055:         %names = @tmp;
1.1075    raeburn  9056:         %oldnames = %names;
1.313     matthew  9057:     }
1.388     www      9058: #
1.1058    raeburn  9059: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9060: # of users did not contain them), do not overwrite existing values
                   9061: # unless field is in $candelete array ref.  
                   9062: #
                   9063: 
                   9064:     my @fields = ('firstname','middlename','lastname','generation',
                   9065:                   'permanentemail','id');
                   9066:     my %newvalues;
                   9067:     if (ref($candelete) eq 'ARRAY') {
                   9068:         foreach my $field (@fields) {
                   9069:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9070:                 if ($field eq 'firstname') {
                   9071:                     $names{$field} = $first;
                   9072:                 } elsif ($field eq 'middlename') {
                   9073:                     $names{$field} = $middle;
                   9074:                 } elsif ($field eq 'lastname') {
                   9075:                     $names{$field} = $last;
                   9076:                 } elsif ($field eq 'generation') { 
                   9077:                     $names{$field} = $gene;
                   9078:                 } elsif ($field eq 'permanentemail') {
                   9079:                     $names{$field} = $email;
                   9080:                 } elsif ($field eq 'id') {
                   9081:                     $names{$field}  = $uid;
                   9082:                 }
                   9083:             }
                   9084:         }
                   9085:     }
1.388     www      9086:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9087:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9088:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9089:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9090:     if ($email) {
                   9091:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9092:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9093:     }
1.899     raeburn  9094:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9095:     if (defined($inststatus)) {
                   9096:         $names{'inststatus'} = '';
                   9097:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9098:         if (ref($usertypes) eq 'HASH') {
                   9099:             my @okstatuses; 
                   9100:             foreach my $item (split(/:/,$inststatus)) {
                   9101:                 if (defined($usertypes->{$item})) {
                   9102:                     push(@okstatuses,$item);  
                   9103:                 }
                   9104:             }
                   9105:             if (@okstatuses) {
                   9106:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9107:             }
                   9108:         }
                   9109:     }
1.1075    raeburn  9110:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9111:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9112:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9113:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9114:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9115:     } else {
                   9116:         $logmsg .= ' during self creation';
                   9117:     }
1.1075    raeburn  9118:     my $changed;
                   9119:     if ($newuser) {
                   9120:         $changed = 1;
                   9121:     } else {
                   9122:         foreach my $field (@fields) {
                   9123:             if ($names{$field} ne $oldnames{$field}) {
                   9124:                 $changed = 1;
                   9125:                 last;
                   9126:             }
                   9127:         }
                   9128:     }
                   9129:     unless ($changed) {
                   9130:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9131:         &logthis($logmsg);
                   9132:         return 'ok';
                   9133:     }
                   9134:     my $reply = &put('environment', \%names, $udom,$uname);
                   9135:     if ($reply ne 'ok') { 
                   9136:         return 'error: '.$reply;
                   9137:     }
1.1087    raeburn  9138:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9139:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9140:     }
1.1075    raeburn  9141:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9142:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9143:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9144:     &logthis($logmsg);
1.134     albertel 9145:     return 'ok';
1.80      www      9146: }
                   9147: 
1.81      www      9148: # -------------------------------------------------------------- Modify student
1.80      www      9149: 
1.81      www      9150: sub modifystudent {
                   9151:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9152:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  9153:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9154:     if (!$cid) {
1.620     albertel 9155: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9156: 	    return 'not_in_class';
                   9157: 	}
1.80      www      9158:     }
                   9159: # --------------------------------------------------------------- Make the user
1.81      www      9160:     my $reply=&modifyuser
1.209     matthew  9161: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9162:          $desiredhome,$email,$inststatus);
1.80      www      9163:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9164:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  9165:     # student's environment
1.297     matthew  9166:     $uid = undef if (!$forceid);
1.455     albertel 9167:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  9168:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  9169:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9170:     return $reply;
                   9171: }
                   9172: 
                   9173: sub modify_student_enrollment {
1.1216    raeburn  9174:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  9175:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9176:     my ($cdom,$cnum,$chome);
                   9177:     if (!$cid) {
1.620     albertel 9178: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9179: 	    return 'not_in_class';
                   9180: 	}
1.620     albertel 9181: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9182: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9183:     } else {
                   9184: 	($cdom,$cnum)=split(/_/,$cid);
                   9185:     }
1.620     albertel 9186:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9187:     if (!$chome) {
1.457     raeburn  9188: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9189:     }
1.455     albertel 9190:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9191:     # Make sure the user exists
1.81      www      9192:     my $uhome=&homeserver($uname,$udom);
                   9193:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9194: 	return 'error: no such user';
                   9195:     }
1.297     matthew  9196:     # Get student data if we were not given enough information
                   9197:     if (!defined($first)  || $first  eq '' || 
                   9198:         !defined($last)   || $last   eq '' || 
                   9199:         !defined($uid)    || $uid    eq '' || 
                   9200:         !defined($middle) || $middle eq '' || 
                   9201:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9202:         # They did not supply us with enough data to enroll the student, so
                   9203:         # we need to pick up more information.
1.297     matthew  9204:         my %tmp = &get('environment',
1.294     matthew  9205:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9206:                        ,$udom,$uname);
                   9207: 
1.800     albertel 9208:         #foreach my $key (keys(%tmp)) {
                   9209:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9210:         #}
1.294     matthew  9211:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9212:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9213:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9214:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9215:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9216:     }
1.556     albertel 9217:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9218:     my $user = "$uname:$udom";
                   9219:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9220:     my $reply=cput('classlist',
1.1148    raeburn  9221: 		   {$user => 
1.1314    raeburn  9222: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9223: 		   $cdom,$cnum);
1.1148    raeburn  9224:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9225:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9226:     } else { 
1.81      www      9227: 	return 'error: '.$reply;
                   9228:     }
1.297     matthew  9229:     # Add student role to user
1.83      www      9230:     my $uurl='/'.$cid;
1.81      www      9231:     $uurl=~s/\_/\//g;
                   9232:     if ($usec) {
                   9233: 	$uurl.='/'.$usec;
                   9234:     }
1.1148    raeburn  9235:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9236:                              $selfenroll,$context);
                   9237:     if ($result ne 'ok') {
                   9238:         if ($old_entry{$user} ne '') {
                   9239:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9240:         } else {
                   9241:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9242:         }
                   9243:     }
                   9244:     return $result; 
1.21      www      9245: }
                   9246: 
1.556     albertel 9247: sub format_name {
                   9248:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9249:     my $name;
                   9250:     if ($first ne 'lastname') {
                   9251: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9252:     } else {
                   9253: 	if ($lastname=~/\S/) {
                   9254: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9255: 	    $name=~s/\s+,/,/;
                   9256: 	} else {
                   9257: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9258: 	}
                   9259:     }
                   9260:     $name=~s/^\s+//;
                   9261:     $name=~s/\s+$//;
                   9262:     $name=~s/\s+/ /g;
                   9263:     return $name;
                   9264: }
                   9265: 
1.84      www      9266: # ------------------------------------------------- Write to course preferences
                   9267: 
                   9268: sub writecoursepref {
                   9269:     my ($courseid,%prefs)=@_;
                   9270:     $courseid=~s/^\///;
                   9271:     $courseid=~s/\_/\//g;
                   9272:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9273:     my $chome=homeserver($cnum,$cdomain);
                   9274:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9275: 	return 'error: no such course';
                   9276:     }
                   9277:     my $cstring='';
1.800     albertel 9278:     foreach my $pref (keys(%prefs)) {
                   9279: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9280:     }
1.84      www      9281:     $cstring=~s/\&$//;
                   9282:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9283: }
                   9284: 
                   9285: # ---------------------------------------------------------- Make/modify course
                   9286: 
                   9287: sub createcourse {
1.741     raeburn  9288:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9289:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9290:     $url=&declutter($url);
                   9291:     my $cid='';
1.1028    raeburn  9292:     if ($context eq 'requestcourses') {
                   9293:         my $can_create = 0;
                   9294:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9295:         if ($udom eq $ownerdom) {
                   9296:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9297:                                   $context)) {
                   9298:                 $can_create = 1;
                   9299:             }
                   9300:         } else {
                   9301:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9302:                                            $category);
                   9303:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9304:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9305:                 if (@curr > 0) {
                   9306:                     my @options = qw(approval validate autolimit);
                   9307:                     my $optregex = join('|',@options);
                   9308:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9309:                         $can_create = 1;
                   9310:                     }
                   9311:                 }
                   9312:             }
                   9313:         }
                   9314:         if ($can_create) {
                   9315:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9316:                 unless (&allowed('ccc',$udom)) {
                   9317:                     return 'refused'; 
                   9318:                 }
1.1017    raeburn  9319:             }
                   9320:         } else {
                   9321:             return 'refused';
                   9322:         }
1.1028    raeburn  9323:     } elsif (!&allowed('ccc',$udom)) {
                   9324:         return 'refused';
1.84      www      9325:     }
1.1011    raeburn  9326: # --------------------------------------------------------------- Get Unique ID
                   9327:     my $uname;
                   9328:     if ($cnum =~ /^$match_courseid$/) {
                   9329:         my $chome=&homeserver($cnum,$udom,'true');
                   9330:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9331:             $uname = $cnum;
                   9332:         } else {
1.1038    raeburn  9333:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9334:         }
                   9335:     } else {
1.1038    raeburn  9336:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9337:     }
                   9338:     return $uname if ($uname =~ /^error/);
                   9339: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9340:     if (!defined($course_server)) {
                   9341:         if (defined(&domain($udom,'primary'))) {
                   9342:             $course_server = &domain($udom,'primary');
                   9343:         } else {
                   9344:             $course_server = $env{'user.home'}; 
                   9345:         }
                   9346:     }
                   9347:     my %host_servers =
                   9348:         &Apache::lonnet::get_servers($udom,'library');
                   9349:     unless ($host_servers{$course_server}) {
                   9350:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9351:     }
1.84      www      9352: # ------------------------------------------------------------- Make the course
                   9353:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9354:                       $course_server);
1.84      www      9355:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9356:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9357:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9358: 	return 'error: no such course';
                   9359:     }
1.271     www      9360: # ----------------------------------------------------------------- Course made
1.516     raeburn  9361: # log existence
1.1029    raeburn  9362:     my $now = time;
1.918     raeburn  9363:     my $newcourse = {
                   9364:                     $udom.'_'.$uname => {
1.921     raeburn  9365:                                      description => $description,
                   9366:                                      inst_code   => $inst_code,
                   9367:                                      owner       => $course_owner,
                   9368:                                      type        => $crstype,
1.1029    raeburn  9369:                                      creator     => $env{'user.name'}.':'.
                   9370:                                                     $env{'user.domain'},
                   9371:                                      created     => $now,
                   9372:                                      context     => $context,
1.918     raeburn  9373:                                                 },
                   9374:                     };
1.921     raeburn  9375:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9376: # set toplevel url
1.271     www      9377:     my $topurl=$url;
                   9378:     unless ($nonstandard) {
                   9379: # ------------------------------------------ For standard courses, make top url
                   9380:         my $mapurl=&clutter($url);
1.278     www      9381:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9382:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9383: <map>
                   9384: <resource id="1" type="start"></resource>
                   9385: <resource id="2" src="$mapurl"></resource>
                   9386: <resource id="3" type="finish"></resource>
                   9387: <link index="1" from="1" to="2"></link>
                   9388: <link index="2" from="2" to="3"></link>
                   9389: </map>
                   9390: ENDINITMAP
                   9391:         $topurl=&declutter(
1.638     albertel 9392:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9393:                           );
                   9394:     }
                   9395: # ----------------------------------------------------------- Write preferences
1.84      www      9396:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9397:                      ('description'              => $description,
                   9398:                       'url'                      => $topurl,
                   9399:                       'internal.creator'         => $env{'user.name'}.':'.
                   9400:                                                     $env{'user.domain'},
                   9401:                       'internal.created'         => $now,
                   9402:                       'internal.creationcontext' => $context)
                   9403:                     );
1.84      www      9404:     return '/'.$udom.'/'.$uname;
                   9405: }
                   9406: 
1.1011    raeburn  9407: # ------------------------------------------------------------------- Create ID
                   9408: sub generate_coursenum {
1.1038    raeburn  9409:     my ($udom,$crstype) = @_;
1.1011    raeburn  9410:     my $domdesc = &domain($udom);
                   9411:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9412:     my $first;
                   9413:     if ($crstype eq 'Community') {
                   9414:         $first = '0';
                   9415:     } else {
                   9416:         $first = int(1+rand(9)); 
                   9417:     } 
                   9418:     my $uname=$first.
1.1011    raeburn  9419:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9420:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9421:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9422: # ----------------------------------------------- Make sure that does not exist
                   9423:     my $uhome=&homeserver($uname,$udom,'true');
                   9424:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9425:         if ($crstype eq 'Community') {
                   9426:             $first = '0';
                   9427:         } else {
                   9428:             $first = int(1+rand(9));
                   9429:         }
                   9430:         $uname=$first.
1.1011    raeburn  9431:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9432:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9433:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9434:         $uhome=&homeserver($uname,$udom,'true');
                   9435:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9436:             return 'error: unable to generate unique course-ID';
                   9437:         }
                   9438:     }
                   9439:     return $uname;
                   9440: }
                   9441: 
1.813     albertel 9442: sub is_course {
1.1167    droeschl 9443:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9444:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   9445: 
                   9446:     return unless $cdom and $cnum;
                   9447: 
                   9448:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   9449:         '.');
                   9450: 
1.1219    raeburn  9451:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 9452:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9453: }
                   9454: 
1.1015    raeburn  9455: sub store_userdata {
                   9456:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9457:     my $result;
1.1016    raeburn  9458:     if ($datakey ne '') {
1.1013    raeburn  9459:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9460:             if ($udom eq '' || $uname eq '') {
                   9461:                 $udom = $env{'user.domain'};
                   9462:                 $uname = $env{'user.name'};
                   9463:             }
                   9464:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9465:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9466:                 $result = 'error: no_host';
                   9467:             } else {
                   9468:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9469:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9470: 
                   9471:                 my $namevalue='';
                   9472:                 foreach my $key (keys(%{$storehash})) {
                   9473:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9474:                 }
                   9475:                 $namevalue=~s/\&$//;
1.1224    raeburn  9476:                 unless ($namespace eq 'courserequests') {
                   9477:                     $datakey = &escape($datakey);
                   9478:                 }
1.1105    raeburn  9479:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9480:                                   $namevalue,$uhome);
1.1013    raeburn  9481:             }
                   9482:         } else {
                   9483:             $result = 'error: data to store was not a hash reference'; 
                   9484:         }
                   9485:     } else {
                   9486:         $result= 'error: invalid requestkey'; 
                   9487:     }
                   9488:     return $result;
                   9489: }
                   9490: 
1.21      www      9491: # ---------------------------------------------------------- Assign Custom Role
                   9492: 
                   9493: sub assigncustomrole {
1.957     raeburn  9494:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9495:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9496:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9497: }
                   9498: 
                   9499: # ----------------------------------------------------------------- Revoke Role
                   9500: 
                   9501: sub revokerole {
1.957     raeburn  9502:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9503:     my $now=time;
1.965     raeburn  9504:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9505: }
                   9506: 
                   9507: # ---------------------------------------------------------- Revoke Custom Role
                   9508: 
                   9509: sub revokecustomrole {
1.957     raeburn  9510:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9511:     my $now=time;
1.357     www      9512:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9513:            $deleteflag,$selfenroll,$context);
1.17      www      9514: }
                   9515: 
1.533     banghart 9516: # ------------------------------------------------------------ Disk usage
1.535     albertel 9517: sub diskusage {
1.955     raeburn  9518:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9519:     $directorypath =~ s/\/$//;
                   9520:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9521:                        .&escape($getpropath).':'.&escape($uname).':'
                   9522:                        .&escape($udom),homeserver($uname,$udom));
                   9523:     if ($listing eq 'unknown_cmd') {
                   9524:         if ($getpropath) {
                   9525:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9526:         }
                   9527:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9528:     }
1.514     albertel 9529:     return $listing;
1.512     banghart 9530: }
                   9531: 
1.566     banghart 9532: sub is_locked {
1.1096    raeburn  9533:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9534:     my @check;
                   9535:     my $is_locked;
1.1093    raeburn  9536:     push (@check,$file_name);
1.613     albertel 9537:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9538: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9539:     my ($tmp)=keys(%locked);
                   9540:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9541:     
1.566     banghart 9542:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9543:         $is_locked = 'false';
                   9544:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9545:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9546:                $is_locked = 'true';
1.1096    raeburn  9547:                if (ref($which) eq 'ARRAY') {
                   9548:                    push(@{$which},$entry);
                   9549:                } else {
                   9550:                    last;
                   9551:                }
1.745     raeburn  9552:            }
                   9553:        }
1.566     banghart 9554:     } else {
                   9555:         $is_locked = 'false';
                   9556:     }
1.1093    raeburn  9557:     return $is_locked;
1.566     banghart 9558: }
                   9559: 
1.759     albertel 9560: sub declutter_portfile {
                   9561:     my ($file) = @_;
1.833     albertel 9562:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9563:     return $file;
                   9564: }
                   9565: 
1.559     banghart 9566: # ------------------------------------------------------------- Mark as Read Only
                   9567: 
                   9568: sub mark_as_readonly {
                   9569:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9570:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9571:     my ($tmp)=keys(%current_permissions);
                   9572:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9573:     foreach my $file (@{$files}) {
1.759     albertel 9574: 	$file = &declutter_portfile($file);
1.561     banghart 9575:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9576:     }
1.613     albertel 9577:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9578:     return;
                   9579: }
                   9580: 
1.572     banghart 9581: # ------------------------------------------------------------Save Selected Files
                   9582: 
                   9583: sub save_selected_files {
                   9584:     my ($user, $path, @files) = @_;
                   9585:     my $filename = $user."savedfiles";
1.573     banghart 9586:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9587:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9588:     foreach my $file (@files) {
1.620     albertel 9589:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9590:     }
                   9591:     foreach my $file (@other_files) {
1.574     banghart 9592:         print (OUT $file."\n");
1.572     banghart 9593:     }
1.574     banghart 9594:     close (OUT);
1.572     banghart 9595:     return 'ok';
                   9596: }
                   9597: 
1.574     banghart 9598: sub clear_selected_files {
                   9599:     my ($user) = @_;
                   9600:     my $filename = $user."savedfiles";
1.1117    foxr     9601:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9602:     print (OUT undef);
                   9603:     close (OUT);
                   9604:     return ("ok");    
                   9605: }
                   9606: 
1.572     banghart 9607: sub files_in_path {
                   9608:     my ($user, $path) = @_;
                   9609:     my $filename = $user."savedfiles";
                   9610:     my %return_files;
1.1117    foxr     9611:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9612:     while (my $line_in = <IN>) {
1.574     banghart 9613:         chomp ($line_in);
                   9614:         my @paths_and_file = split (m!/!, $line_in);
                   9615:         my $file_part = pop (@paths_and_file);
                   9616:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9617:         $path_part.='/';
                   9618:         my $path_and_file = $path_part.$file_part;
                   9619:         if ($path_part eq $path) {
                   9620:             $return_files{$file_part}= 'selected';
                   9621:         }
                   9622:     }
1.574     banghart 9623:     close (IN);
                   9624:     return (\%return_files);
1.572     banghart 9625: }
                   9626: 
                   9627: # called in portfolio select mode, to show files selected NOT in current directory
                   9628: sub files_not_in_path {
                   9629:     my ($user, $path) = @_;
                   9630:     my $filename = $user."savedfiles";
                   9631:     my @return_files;
                   9632:     my $path_part;
1.1117    foxr     9633:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9634:     while (my $line = <IN>) {
1.572     banghart 9635:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9636:         my @paths_and_file = split(m|/|, $line);
                   9637:         my $file_part = pop(@paths_and_file);
                   9638:         chomp($file_part);
                   9639:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9640:         $path_part .= '/';
                   9641:         my $path_and_file = $path_part.$file_part;
                   9642:         if ($path_part ne $path) {
1.800     albertel 9643:             push(@return_files, ($path_and_file));
1.572     banghart 9644:         }
                   9645:     }
1.800     albertel 9646:     close(OUT);
1.574     banghart 9647:     return (@return_files);
1.572     banghart 9648: }
                   9649: 
1.1273    raeburn  9650: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   9651:  
                   9652: sub portfiles_versioning {
                   9653:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   9654:     my $portfolio_root = '/userfiles/portfolio';
                   9655:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   9656:     foreach my $file (@{$portfiles}) {
                   9657:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   9658:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   9659:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   9660:         my $getpropath = 1;
                   9661:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   9662:                                              $stu_name,$getpropath);
                   9663:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   9664:         my $new_answer = 
                   9665:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   9666:         if ($new_answer ne 'problem getting file') {
                   9667:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   9668:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   9669:                               [$symb,$env{'request.course.id'},'graded']);
                   9670:         }
                   9671:     }
                   9672: }
                   9673: 
                   9674: sub get_next_version {
                   9675:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   9676:     my $version;
                   9677:     if (ref($dir_list) eq 'ARRAY') {
                   9678:         foreach my $row (@{$dir_list}) {
                   9679:             my ($file) = split(/\&/,$row,2);
                   9680:             my ($file_name,$file_version,$file_ext) =
                   9681:                 &file_name_version_ext($file);
                   9682:             if (($file_name eq $answer_name) &&
                   9683:                 ($file_ext eq $answer_ext)) {
                   9684:                      # gets here if filename and extension match,
                   9685:                      # regardless of version
                   9686:                 if ($file_version ne '') {
                   9687:                     # a versioned file is found  so save it for later
                   9688:                     if ($file_version > $version) {
                   9689:                         $version = $file_version;
                   9690:                     }
                   9691:                 }
                   9692:             }
                   9693:         }
                   9694:     }
                   9695:     $version ++;
                   9696:     return($version);
                   9697: }
                   9698: 
                   9699: sub version_selected_portfile {
                   9700:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   9701:     my ($answer_name,$answer_ver,$answer_ext) =
                   9702:         &file_name_version_ext($file_name);
                   9703:     my $new_answer;
                   9704:     $env{'form.copy'} =
                   9705:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   9706:     if($env{'form.copy'} eq '-1') {
                   9707:         $new_answer = 'problem getting file';
                   9708:     } else {
                   9709:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   9710:         my $copy_result = 
                   9711:             &finishuserfileupload($stu_name,$domain,'copy',
                   9712:                                   '/portfolio'.$directory.$new_answer);
                   9713:     }
                   9714:     undef($env{'form.copy'});
                   9715:     return ($new_answer);
                   9716: }
                   9717: 
                   9718: sub file_name_version_ext {
                   9719:     my ($file)=@_;
                   9720:     my @file_parts = split(/\./, $file);
                   9721:     my ($name,$version,$ext);
                   9722:     if (@file_parts > 1) {
                   9723:         $ext=pop(@file_parts);
                   9724:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   9725:             $version=pop(@file_parts);
                   9726:         }
                   9727:         $name=join('.',@file_parts);
                   9728:     } else {
                   9729:         $name=join('.',@file_parts);
                   9730:     }
                   9731:     return($name,$version,$ext);
                   9732: }
                   9733: 
1.745     raeburn  9734: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9735: 
1.745     raeburn  9736: sub get_portfile_permissions {
                   9737:     my ($domain,$user) = @_;
1.613     albertel 9738:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9739:     my ($tmp)=keys(%current_permissions);
                   9740:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9741:     return \%current_permissions;
                   9742: }
                   9743: 
                   9744: #---------------------------------------------Get portfolio file access controls
                   9745: 
1.749     raeburn  9746: sub get_access_controls {
1.745     raeburn  9747:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9748:     my %access;
                   9749:     my $real_file = $file;
                   9750:     $file =~ s/\.meta$//;
1.745     raeburn  9751:     if (defined($file)) {
1.749     raeburn  9752:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9753:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9754:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9755:             }
                   9756:         }
1.745     raeburn  9757:     } else {
1.749     raeburn  9758:         foreach my $key (keys(%{$current_permissions})) {
                   9759:             if ($key =~ /\0accesscontrol$/) {
                   9760:                 if (defined($group)) {
                   9761:                     if ($key !~ m-^\Q$group\E/-) {
                   9762:                         next;
                   9763:                     }
                   9764:                 }
                   9765:                 my ($fullpath) = split(/\0/,$key);
                   9766:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9767:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9768:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9769:                     }
                   9770:                 }
                   9771:             }
                   9772:         }
                   9773:     }
                   9774:     return %access;
                   9775: }
                   9776: 
                   9777: sub modify_access_controls {
                   9778:     my ($file_name,$changes,$domain,$user)=@_;
                   9779:     my ($outcome,$deloutcome);
                   9780:     my %store_permissions;
                   9781:     my %new_values;
                   9782:     my %new_control;
                   9783:     my %translation;
                   9784:     my @deletions = ();
                   9785:     my $now = time;
                   9786:     if (exists($$changes{'activate'})) {
                   9787:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9788:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9789:             my $numnew = scalar(@newitems);
                   9790:             for (my $i=0; $i<$numnew; $i++) {
                   9791:                 my $newkey = $newitems[$i];
                   9792:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9793:                 if ($newkey =~ /^\d+:/) { 
                   9794:                     $newkey =~ s/^(\d+)/$newid/;
                   9795:                     $translation{$1} = $newid;
                   9796:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9797:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9798:                     $translation{$1} = $newid;
                   9799:                 }
1.749     raeburn  9800:                 $new_values{$file_name."\0".$newkey} = 
                   9801:                                           $$changes{'activate'}{$newitems[$i]};
                   9802:                 $new_control{$newkey} = $now;
                   9803:             }
                   9804:         }
                   9805:     }
                   9806:     my %todelete;
                   9807:     my %changed_items;
                   9808:     foreach my $action ('delete','update') {
                   9809:         if (exists($$changes{$action})) {
                   9810:             if (ref($$changes{$action}) eq 'HASH') {
                   9811:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9812:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9813:                     if ($action eq 'delete') { 
                   9814:                         $todelete{$itemnum} = 1;
                   9815:                     } else {
                   9816:                         $changed_items{$itemnum} = $key;
                   9817:                     }
                   9818:                 }
1.745     raeburn  9819:             }
                   9820:         }
1.749     raeburn  9821:     }
                   9822:     # get lock on access controls for file.
                   9823:     my $lockhash = {
                   9824:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9825:                                                        ':'.$env{'user.domain'},
                   9826:                    }; 
                   9827:     my $tries = 0;
                   9828:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9829:    
1.1288    damieng  9830:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  9831:         $tries ++;
1.1289    damieng  9832:         sleep(0.1);
1.749     raeburn  9833:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9834:     }
                   9835:     if ($gotlock eq 'ok') {
                   9836:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9837:         my ($tmp)=keys(%curr_permissions);
                   9838:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9839:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9840:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9841:             if (ref($curr_controls) eq 'HASH') {
                   9842:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9843:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9844:                     if (defined($todelete{$itemnum})) {
                   9845:                         push(@deletions,$file_name."\0".$control_item);
                   9846:                     } else {
                   9847:                         if (defined($changed_items{$itemnum})) {
                   9848:                             $new_control{$changed_items{$itemnum}} = $now;
                   9849:                             push(@deletions,$file_name."\0".$control_item);
                   9850:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9851:                         } else {
                   9852:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9853:                         }
                   9854:                     }
1.745     raeburn  9855:                 }
                   9856:             }
                   9857:         }
1.970     raeburn  9858:         my ($group);
                   9859:         if (&is_course($domain,$user)) {
                   9860:             ($group,my $file) = split(/\//,$file_name,2);
                   9861:         }
1.749     raeburn  9862:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9863:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9864:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9865:         #  remove lock
                   9866:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9867:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9868:         my $sqlresult =
1.970     raeburn  9869:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9870:                                     $group);
1.749     raeburn  9871:     } else {
                   9872:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9873:     }
1.749     raeburn  9874:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9875: }
                   9876: 
1.827     raeburn  9877: sub make_public_indefinitely {
1.1271    raeburn  9878:     my (@requrl) = @_;
                   9879:     return &automated_portfile_access('public',\@requrl);
                   9880: }
                   9881: 
                   9882: sub automated_portfile_access {
                   9883:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  9884:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   9885:         return 'invalid';
                   9886:     }
1.1271    raeburn  9887:     my %urls;
                   9888:     if (ref($addsref) eq 'ARRAY') {
                   9889:         foreach my $requrl (@{$addsref}) {
                   9890:             if (&is_portfolio_url($requrl)) {
                   9891:                 unless (exists($urls{$requrl})) {
                   9892:                     $urls{$requrl} = 'add';
                   9893:                 }
                   9894:             }
                   9895:         }
                   9896:     }
                   9897:     if (ref($delsref) eq 'ARRAY') {
                   9898:         foreach my $requrl (@{$delsref}) { 
                   9899:             if (&is_portfolio_url($requrl)) {
                   9900:                 unless (exists($urls{$requrl})) {
                   9901:                     $urls{$requrl} = 'delete'; 
                   9902:                 }
                   9903:             }
                   9904:         }
                   9905:     }
                   9906:     unless (keys(%urls)) {
                   9907:         return 'invalid';
                   9908:     }
                   9909:     my $ip;
                   9910:     if ($accesstype eq 'ip') {
                   9911:         if (ref($info) eq 'HASH') {
                   9912:             if ($info->{'ip'} ne '') {
                   9913:                 $ip = $info->{'ip'};
                   9914:             }
                   9915:         }
                   9916:         if ($ip eq '') {
                   9917:             return 'invalid';
                   9918:         }
                   9919:     }
                   9920:     my $errors;
1.827     raeburn  9921:     my $now = time;
1.1271    raeburn  9922:     my %current_perms;
                   9923:     foreach my $requrl (sort(keys(%urls))) {
                   9924:         my $action;
                   9925:         if ($urls{$requrl} eq 'add') {
                   9926:             $action = 'activate';
                   9927:         } else {
                   9928:             $action = 'none';
                   9929:         }
                   9930:         my $aclnum = 0;
1.827     raeburn  9931:         my (undef,$udom,$unum,$file_name,$group) =
                   9932:             &parse_portfolio_url($requrl);
1.1271    raeburn  9933:         unless (exists($current_perms{$unum.':'.$udom})) {
                   9934:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   9935:         }
                   9936:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  9937:                                                    $group,$file_name);
                   9938:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9939:             my ($num,$scope,$end,$start) = 
                   9940:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  9941:             if ($scope eq $accesstype) {
                   9942:                 if (($start <= $now) && ($end == 0)) {
                   9943:                     if ($accesstype eq 'ip') {
                   9944:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   9945:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   9946:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   9947:                                     if ($urls{$requrl} eq 'add') {
                   9948:                                         $action = 'none';
                   9949:                                         last;
                   9950:                                     } else {
                   9951:                                         $action = 'delete';
                   9952:                                         $aclnum = $num;
                   9953:                                         last;
                   9954:                                     }
                   9955:                                 }
                   9956:                             }
                   9957:                         }
                   9958:                     } elsif ($accesstype eq 'public') {
                   9959:                         if ($urls{$requrl} eq 'add') {
                   9960:                             $action = 'none';
                   9961:                             last;
                   9962:                         } else {
                   9963:                             $action = 'delete';
                   9964:                             $aclnum = $num;
                   9965:                             last;
                   9966:                         }
                   9967:                     }
                   9968:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  9969:                     $action = 'update';
                   9970:                     $aclnum = $num;
1.1271    raeburn  9971:                     last;
1.827     raeburn  9972:                 }
                   9973:             }
                   9974:         }
                   9975:         if ($action eq 'none') {
1.1271    raeburn  9976:             next;
1.827     raeburn  9977:         } else {
                   9978:             my %changes;
                   9979:             my $newend = 0;
                   9980:             my $newstart = $now;
1.1271    raeburn  9981:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  9982:             $changes{$action}{$newkey} = {
1.1271    raeburn  9983:                 type => $accesstype,
1.827     raeburn  9984:                 time => {
                   9985:                     start => $newstart,
                   9986:                     end   => $newend,
                   9987:                 },
                   9988:             };
1.1271    raeburn  9989:             if ($accesstype eq 'ip') {
                   9990:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   9991:             }
1.827     raeburn  9992:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9993:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  9994:             unless ($outcome eq 'ok') {
                   9995:                 $errors .= $outcome.' ';
                   9996:             }
1.827     raeburn  9997:         }
1.1271    raeburn  9998:     }
                   9999:     if ($errors) {
                   10000:         $errors =~ s/\s$//;
                   10001:         return $errors;
1.827     raeburn  10002:     } else {
1.1271    raeburn  10003:         return 'ok';
1.827     raeburn  10004:     }
                   10005: }
                   10006: 
1.745     raeburn  10007: #------------------------------------------------------Get Marked as Read Only
                   10008: 
                   10009: sub get_marked_as_readonly {
                   10010:     my ($domain,$user,$what,$group) = @_;
                   10011:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10012:     my @readonly_files;
1.629     banghart 10013:     my $cmp1=$what;
                   10014:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10015:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10016:         if (defined($group)) {
                   10017:             if ($file_name !~ m-^\Q$group\E/-) {
                   10018:                 next;
                   10019:             }
                   10020:         }
1.561     banghart 10021:         if (ref($value) eq "ARRAY"){
                   10022:             foreach my $stored_what (@{$value}) {
1.629     banghart 10023:                 my $cmp2=$stored_what;
1.759     albertel 10024:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10025:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10026:                 }
1.629     banghart 10027:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10028:                     push(@readonly_files, $file_name);
1.745     raeburn  10029:                     last;
1.563     banghart 10030:                 } elsif (!defined($what)) {
                   10031:                     push(@readonly_files, $file_name);
1.745     raeburn  10032:                     last;
1.561     banghart 10033:                 }
                   10034:             }
1.745     raeburn  10035:         }
1.561     banghart 10036:     }
                   10037:     return @readonly_files;
                   10038: }
1.577     banghart 10039: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10040: 
1.577     banghart 10041: sub get_marked_as_readonly_hash {
1.745     raeburn  10042:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10043:     my %readonly_files;
1.745     raeburn  10044:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10045:         if (defined($group)) {
                   10046:             if ($file_name !~ m-^\Q$group\E/-) {
                   10047:                 next;
                   10048:             }
                   10049:         }
1.577     banghart 10050:         if (ref($value) eq "ARRAY"){
                   10051:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10052:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10053:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10054:                         if ($lock_descriptor eq 'graded') {
                   10055:                             $readonly_files{$file_name} = 'graded';
                   10056:                         } elsif ($lock_descriptor eq 'handback') {
                   10057:                             $readonly_files{$file_name} = 'handback';
                   10058:                         } else {
                   10059:                             if (!exists($readonly_files{$file_name})) {
                   10060:                                 $readonly_files{$file_name} = 'locked';
                   10061:                             }
                   10062:                         }
1.745     raeburn  10063:                     }
1.750     banghart 10064:                 } 
1.577     banghart 10065:             }
                   10066:         } 
                   10067:     }
                   10068:     return %readonly_files;
                   10069: }
1.559     banghart 10070: # ------------------------------------------------------------ Unmark as Read Only
                   10071: 
                   10072: sub unmark_as_readonly {
1.629     banghart 10073:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10074:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10075:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10076:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10077:     my $symb_crs = $what;
                   10078:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10079:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10080:     my ($tmp)=keys(%current_permissions);
                   10081:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10082:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10083:     foreach my $file (@readonly_files) {
1.759     albertel 10084: 	my $clean_file = &declutter_portfile($file);
                   10085: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10086: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10087:         my @new_locks;
                   10088:         my @del_keys;
                   10089:         if (ref($current_locks) eq "ARRAY"){
                   10090:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10091:                 my $compare=$locker;
1.749     raeburn  10092:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10093:                     $compare=join('',@{$locker});
1.746     raeburn  10094:                     if ($compare ne $symb_crs) {
                   10095:                         push(@new_locks, $locker);
                   10096:                     }
1.563     banghart 10097:                 }
                   10098:             }
1.650     albertel 10099:             if (scalar(@new_locks) > 0) {
1.563     banghart 10100:                 $current_permissions{$file} = \@new_locks;
                   10101:             } else {
                   10102:                 push(@del_keys, $file);
1.613     albertel 10103:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10104:                 delete($current_permissions{$file});
1.563     banghart 10105:             }
                   10106:         }
1.561     banghart 10107:     }
1.613     albertel 10108:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10109:     return;
                   10110: }
1.512     banghart 10111: 
1.17      www      10112: # ------------------------------------------------------------ Directory lister
                   10113: 
                   10114: sub dirlist {
1.955     raeburn  10115:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10116:     $uri=~s/^\///;
                   10117:     $uri=~s/\/$//;
1.253     stredwic 10118:     my ($udom, $uname);
1.955     raeburn  10119:     if ($getuserdir) {
1.253     stredwic 10120:         $udom = $userdomain;
                   10121:         $uname = $username;
1.955     raeburn  10122:     } else {
                   10123:         (undef,$udom,$uname)=split(/\//,$uri);
                   10124:         if(defined($userdomain)) {
                   10125:             $udom = $userdomain;
                   10126:         }
                   10127:         if(defined($username)) {
                   10128:             $uname = $username;
                   10129:         }
1.253     stredwic 10130:     }
1.955     raeburn  10131:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10132: 
1.955     raeburn  10133:     $dirRoot = $perlvar{'lonDocRoot'};
                   10134:     if (defined($getpropath)) {
                   10135:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10136:         $dirRoot =~ s/\/$//;
1.955     raeburn  10137:     } elsif (defined($getuserdir)) {
                   10138:         my $subdir=$uname.'__';
                   10139:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10140:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10141:                    ."/$udom/$subdir/$uname";
                   10142:     } elsif (defined($alternateRoot)) {
                   10143:         $dirRoot = $alternateRoot;
1.751     banghart 10144:     }
1.253     stredwic 10145: 
                   10146:     if($udom) {
                   10147:         if($uname) {
1.1135    raeburn  10148:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10149:             if ($uhome eq 'no_host') {
                   10150:                 return ([],'no_host');
                   10151:             }
1.955     raeburn  10152:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10153:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10154:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10155:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10156:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10157:             } else {
                   10158:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10159:             }
1.605     matthew  10160:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10161:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10162:                 @listing_results = split(/:/,$listing);
                   10163:             } else {
                   10164:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10165:             }
1.1135    raeburn  10166:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10167:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10168:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10169:                 return ([],$listing);
                   10170:             } else {
                   10171:                 return (\@listing_results);
1.1135    raeburn  10172:             }
1.955     raeburn  10173:         } elsif(!$alternateRoot) {
1.1136    raeburn  10174:             my (%allusers,%listerror);
1.841     albertel 10175: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10176:  	    foreach my $tryserver (keys(%servers)) {
                   10177:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10178:                                   &escape($udom),$tryserver);
                   10179:                 if ($listing eq 'unknown_cmd') {
                   10180: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10181: 				      $udom, $tryserver);
                   10182:                 } else {
                   10183:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10184:                 }
1.841     albertel 10185: 		if ($listing eq 'unknown_cmd') {
                   10186: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10187: 				      $udom, $tryserver);
                   10188: 		    @listing_results = split(/:/,$listing);
                   10189: 		} else {
                   10190: 		    @listing_results =
                   10191: 			map { &unescape($_); } split(/:/,$listing);
                   10192: 		}
1.1136    raeburn  10193:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10194:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10195:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10196:                     $listerror{$tryserver} = $listing;
                   10197:                 } else {
1.841     albertel 10198: 		    foreach my $line (@listing_results) {
                   10199: 			my ($entry) = split(/&/,$line,2);
                   10200: 			$allusers{$entry} = 1;
                   10201: 		    }
                   10202: 		}
1.253     stredwic 10203:             }
1.1136    raeburn  10204:             my @alluserslist=();
1.800     albertel 10205:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10206:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10207:             }
1.1318    droeschl 10208: 
                   10209:             if (!%listerror) {
                   10210:                 # no errors
                   10211:                 return (\@alluserslist);
                   10212:             } elsif (scalar(keys(%servers)) == 1) {
                   10213:                 # one library server, one error 
                   10214:                 my ($key) = keys(%listerror);
                   10215:                 return (\@alluserslist, $listerror{$key});
                   10216:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10217:                 # con_lost indicates that we might miss data from at least one
                   10218:                 # library server
                   10219:                 return (\@alluserslist, 'con_lost');
                   10220:             } else {
                   10221:                 # multiple library servers and no con_lost -> data should be
                   10222:                 # complete. 
                   10223:                 return (\@alluserslist);
                   10224:             }
                   10225: 
1.253     stredwic 10226:         } else {
1.1136    raeburn  10227:             return ([],'missing username');
1.253     stredwic 10228:         }
1.955     raeburn  10229:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10230:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10231:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10232:         return (\@all_domains);
1.955     raeburn  10233:     } else {
1.1136    raeburn  10234:         return ([],'missing domain');
1.275     stredwic 10235:     }
                   10236: }
                   10237: 
                   10238: # --------------------------------------------- GetFileTimestamp
                   10239: # This function utilizes dirlist and returns the date stamp for
                   10240: # when it was last modified.  It will also return an error of -1
                   10241: # if an error occurs
                   10242: 
                   10243: sub GetFileTimestamp {
1.955     raeburn  10244:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10245:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10246:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10247:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10248:                                     undef,$getuserdir);
                   10249:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10250:         return -1;
                   10251:     }
                   10252:     if (ref($fileref) eq 'ARRAY') {
                   10253:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10254:         # @stats contains first the filename, then the stat output
                   10255:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10256:     } else {
                   10257:         return -1;
1.253     stredwic 10258:     }
1.26      www      10259: }
                   10260: 
1.712     albertel 10261: sub stat_file {
                   10262:     my ($uri) = @_;
1.787     albertel 10263:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10264: 
1.955     raeburn  10265:     my ($udom,$uname,$file);
1.712     albertel 10266:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10267: 	($udom,$uname,$file) =
1.811     albertel 10268: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10269: 	$file = 'userfiles/'.$file;
                   10270:     }
                   10271:     if ($uri =~ m-^/res/-) {
                   10272: 	($udom,$uname) = 
1.807     albertel 10273: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10274: 	$file = $uri;
                   10275:     }
                   10276: 
                   10277:     if (!$udom || !$uname || !$file) {
                   10278: 	# unable to handle the uri
                   10279: 	return ();
                   10280:     }
1.956     raeburn  10281:     my $getpropath;
                   10282:     if ($file =~ /^userfiles\//) {
                   10283:         $getpropath = 1;
                   10284:     }
1.1136    raeburn  10285:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10286:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10287:         return ();
                   10288:     } else {
                   10289:         if (ref($listref) eq 'ARRAY') {
                   10290:             my @stats = split('&',$listref->[0]);
                   10291: 	    shift(@stats); #filename is first
                   10292: 	    return @stats;
                   10293:         }
1.712     albertel 10294:     }
                   10295:     return ();
                   10296: }
                   10297: 
1.1313    raeburn  10298: # --------------------------------------------------------- recursedirs
                   10299: # Recursive function to traverse either a specific user's Authoring Space
                   10300: # or corresponding Published Resource Space, and populate the hash ref:
                   10301: # $dirhashref with URLs of all directories, and if $filehashref hash
                   10302: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   10303: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   10304: # files in Authoring Space.
                   10305: #
                   10306: # Inputs:
                   10307: #
                   10308: # $is_home - true if current server is home server for user's space
                   10309: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   10310: # $docroot - Document root (i.e., /home/httpd/html
                   10311: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   10312: # $relpath - Current path (relative to top level).
                   10313: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   10314: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   10315: #
                   10316: # Returns: nothing
                   10317: #
                   10318: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   10319: #
                   10320: # Currently used by interface/londocs.pm to create linked select boxes for
                   10321: # directory and filename to import a Course "Author" resource into a course, and
                   10322: # also to create linked select boxes for Authoring Space and Directory to choose
                   10323: # save location for creation of a new "standard" problem from the Course Editor.
                   10324: #
                   10325: 
                   10326: sub recursedirs {
                   10327:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   10328:     return unless (ref($dirhashref) eq 'HASH');
                   10329:     my $currpath = $docroot.$toppath;
                   10330:     if ($relpath) {
                   10331:         $currpath .= "/$relpath";
                   10332:     }
                   10333:     my $savefile;
                   10334:     if (ref($filehashref)) {
                   10335:         $savefile = 1;
                   10336:     }
                   10337:     if ($is_home) {
                   10338:         if (opendir(my $dirh,$currpath)) {
                   10339:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   10340:                 next if ($item eq '');
                   10341:                 if (-d "$currpath/$item") {
                   10342:                     my $newpath;
                   10343:                     if ($relpath) {
                   10344:                         $newpath = "$relpath/$item";
                   10345:                     } else {
                   10346:                         $newpath = $item;
                   10347:                     }
                   10348:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10349:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10350:                 } elsif ($savefile) {
                   10351:                     if ($context eq 'priv') {
                   10352:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10353:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10354:                         }
                   10355:                     } else {
                   10356:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   10357:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10358:                         }
                   10359:                     }
                   10360:                 }
                   10361:             }
                   10362:             closedir($dirh);
                   10363:         }
                   10364:     } else {
                   10365:         my ($dirlistref,$listerror) =
                   10366:             &dirlist($toppath.$relpath);
                   10367:         my @dir_lines;
                   10368:         my $dirptr=16384;
                   10369:         if (ref($dirlistref) eq 'ARRAY') {
                   10370:             foreach my $dir_line (sort
                   10371:                               {
                   10372:                                   my ($afile)=split('&',$a,2);
                   10373:                                   my ($bfile)=split('&',$b,2);
                   10374:                                   return (lc($afile) cmp lc($bfile));
                   10375:                               } (@{$dirlistref})) {
                   10376:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   10377:                     split(/\&/,$dir_line,16);
                   10378:                 $item =~ s/\s+$//;
                   10379:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   10380:                 if ($dirptr&$testdir) {
                   10381:                     my $newpath;
                   10382:                     if ($relpath) {
                   10383:                         $newpath = "$relpath/$item";
                   10384:                     } else {
                   10385:                         $relpath = '/';
                   10386:                         $newpath = $item;
                   10387:                     }
                   10388:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10389:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10390:                 } elsif ($savefile) {
                   10391:                     if ($context eq 'priv') {
                   10392:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10393:                             $filehashref->{$relpath}{$item} = 1;
                   10394:                         }
                   10395:                     } else {
                   10396:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   10397:                             $filehashref->{$relpath}{$item} = 1;
                   10398:                         }
                   10399:                     }
                   10400:                 }
                   10401:             }
                   10402:         }
                   10403:     }
                   10404:     return;
                   10405: }
                   10406: 
1.26      www      10407: # -------------------------------------------------------- Value of a Condition
                   10408: 
1.713     albertel 10409: # gets the value of a specific preevaluated condition
                   10410: #    stored in the string  $env{user.state.<cid>}
                   10411: # or looks up a condition reference in the bighash and if if hasn't
                   10412: # already been evaluated recurses into docondval to get the value of
                   10413: # the condition, then memoizing it to 
                   10414: #   $env{user.state.<cid>.<condition>}
1.40      www      10415: sub directcondval {
                   10416:     my $number=shift;
1.620     albertel 10417:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10418: 	&Apache::lonuserstate::evalstate();
                   10419:     }
1.713     albertel 10420:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10421: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10422:     } elsif ($number =~ /^_/) {
                   10423: 	my $sub_condition;
                   10424: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10425: 		&GDBM_READER(),0640)) {
                   10426: 	    $sub_condition=$bighash{'conditions'.$number};
                   10427: 	    untie(%bighash);
                   10428: 	}
                   10429: 	my $value = &docondval($sub_condition);
1.949     raeburn  10430: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10431: 	return $value;
                   10432:     }
1.620     albertel 10433:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10434:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10435:     } else {
                   10436:        return 2;
                   10437:     }
                   10438: }
                   10439: 
1.713     albertel 10440: # get the collection of conditions for this resource
1.26      www      10441: sub condval {
                   10442:     my $condidx=shift;
1.54      www      10443:     my $allpathcond='';
1.713     albertel 10444:     foreach my $cond (split(/\|/,$condidx)) {
                   10445: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10446: 	    $allpathcond.=
                   10447: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10448: 	}
1.191     harris41 10449:     }
1.54      www      10450:     $allpathcond=~s/\|$//;
1.713     albertel 10451:     return &docondval($allpathcond);
                   10452: }
                   10453: 
                   10454: #evaluates an expression of conditions
                   10455: sub docondval {
                   10456:     my ($allpathcond) = @_;
                   10457:     my $result=0;
                   10458:     if ($env{'request.course.id'}
                   10459: 	&& defined($allpathcond)) {
                   10460: 	my $operand='|';
                   10461: 	my @stack;
                   10462: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10463: 	    if ($chunk eq '(') {
                   10464: 		push @stack,($operand,$result);
                   10465: 	    } elsif ($chunk eq ')') {
                   10466: 		my $before=pop @stack;
                   10467: 		if (pop @stack eq '&') {
                   10468: 		    $result=$result>$before?$before:$result;
                   10469: 		} else {
                   10470: 		    $result=$result>$before?$result:$before;
                   10471: 		}
                   10472: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10473: 		$operand=$chunk;
                   10474: 	    } else {
                   10475: 		my $new=directcondval($chunk);
                   10476: 		if ($operand eq '&') {
                   10477: 		    $result=$result>$new?$new:$result;
                   10478: 		} else {
                   10479: 		    $result=$result>$new?$result:$new;
                   10480: 		}
                   10481: 	    }
                   10482: 	}
1.26      www      10483:     }
                   10484:     return $result;
1.421     albertel 10485: }
                   10486: 
                   10487: # ---------------------------------------------------- Devalidate courseresdata
                   10488: 
                   10489: sub devalidatecourseresdata {
                   10490:     my ($coursenum,$coursedomain)=@_;
                   10491:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10492:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10493: }
                   10494: 
1.763     www      10495: 
1.200     www      10496: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10497: #
                   10498: #  Parameters:
                   10499: #      $coursenum    - Number of the course.
                   10500: #      $coursedomain - Domain at which the course was created.
                   10501: #  Returns:
                   10502: #     A hash of the course parameters along (I think) with timestamps
                   10503: #     and version info.
1.877     foxr     10504: 
1.624     albertel 10505: sub get_courseresdata {
                   10506:     my ($coursenum,$coursedomain)=@_;
1.200     www      10507:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10508:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10509:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10510:     my %dumpreply;
1.417     albertel 10511:     unless (defined($cached)) {
1.624     albertel 10512: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10513: 	$result=\%dumpreply;
1.251     albertel 10514: 	my ($tmp) = keys(%dumpreply);
                   10515: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10516: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10517: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10518: 	    return $tmp;
1.416     albertel 10519: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10520: 	    $result=undef;
1.599     albertel 10521: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10522: 	}
                   10523:     }
1.624     albertel 10524:     return $result;
                   10525: }
                   10526: 
1.633     albertel 10527: sub devalidateuserresdata {
                   10528:     my ($uname,$udom)=@_;
                   10529:     my $hashid="$udom:$uname";
                   10530:     &devalidate_cache_new('userres',$hashid);
                   10531: }
                   10532: 
1.624     albertel 10533: sub get_userresdata {
                   10534:     my ($uname,$udom)=@_;
                   10535:     #most student don\'t have any data set, check if there is some data
                   10536:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10537: 
                   10538:     my $hashid="$udom:$uname";
                   10539:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10540:     if (!defined($cached)) {
                   10541: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10542: 	$result=\%resourcedata;
                   10543: 	&do_cache_new('userres',$hashid,$result,600);
                   10544:     }
                   10545:     my ($tmp)=keys(%$result);
                   10546:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10547: 	return $result;
                   10548:     }
                   10549:     #error 2 occurs when the .db doesn't exist
                   10550:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  10551:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   10552: 	    &logthis("<font color=\"blue\">WARNING:".
                   10553: 		     " Trying to get resource data for ".
                   10554: 		     $uname." at ".$udom.": ".
                   10555: 		     $tmp."</font>");
                   10556:         }
1.624     albertel 10557:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10558: 	#&EXT_cache_set($udom,$uname);
                   10559: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10560: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10561:     }
                   10562:     return $tmp;
                   10563: }
1.879     foxr     10564: #----------------------------------------------- resdata - return resource data
                   10565: #  Purpose:
                   10566: #    Return resource data for either users or for a course.
                   10567: #  Parameters:
                   10568: #     $name      - Course/user name.
                   10569: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  10570: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  10571: #     $mapp      - decluttered URL of enclosing map  
                   10572: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   10573: #     $recurseup - Ref to array of map URLs, starting with map containing
                   10574: #                  $mapp up through hierarchy of nested maps to top level map.  
                   10575: #     $courseid  - CourseID (first part of param identifier).
                   10576: #     $modifier  - Middle part of param identifier.
                   10577: #     $what      - Last part of param identifier.
1.879     foxr     10578: #     @which     - Array of names of resources desired.
                   10579: #  Returns:
                   10580: #     The value of the first reasource in @which that is found in the
                   10581: #     resource hash.
                   10582: #  Exceptional Conditions:
                   10583: #     If the $type passed in is not valid (not the string 'course' or 
                   10584: #     'user', an undefined  reference is returned.
                   10585: #     If none of the resources are found, an undef is returned
1.624     albertel 10586: sub resdata {
1.1301    raeburn  10587:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   10588:         $modifier,$what,@which)=@_;
1.624     albertel 10589:     my $result;
                   10590:     if ($type eq 'course') {
                   10591: 	$result=&get_courseresdata($name,$domain);
                   10592:     } elsif ($type eq 'user') {
                   10593: 	$result=&get_userresdata($name,$domain);
                   10594:     }
                   10595:     if (!ref($result)) { return $result; }    
1.251     albertel 10596:     foreach my $item (@which) {
1.1301    raeburn  10597:         if ($item->[1] eq 'course') {
                   10598:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   10599:                 unless ($$recursed) {
1.1302    raeburn  10600:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  10601:                     $$recursed = 1;
                   10602:                 }
                   10603:                 foreach my $item (@${recurseup}) {
                   10604:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   10605:                     last if (defined($result->{$norecursechk}));
                   10606:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   10607:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   10608:                 }
                   10609:             }
                   10610:         }
                   10611:         if (defined($result->{$item->[0]})) {
1.927     albertel 10612: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 10613: 	}
1.250     albertel 10614:     }
1.291     albertel 10615:     return undef;
1.200     www      10616: }
                   10617: 
1.1298    raeburn  10618: sub get_domain_ltitools {
                   10619:     my ($cdom) = @_;
                   10620:     my %ltitools;
                   10621:     my ($result,$cached)=&is_cached_new('ltitools',$cdom);
                   10622:     if (defined($cached)) {
                   10623:         if (ref($result) eq 'HASH') {
                   10624:             %ltitools = %{$result};
                   10625:         }
                   10626:     } else {
                   10627:         my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
                   10628:         if (ref($domconfig{'ltitools'}) eq 'HASH') {
                   10629:             %ltitools = %{$domconfig{'ltitools'}};
                   10630:         }
                   10631:         my $cachetime = 24*60*60;
                   10632:         &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
                   10633:     }
                   10634:     return %ltitools;
                   10635: }
                   10636: 
1.1236    raeburn  10637: sub get_numsuppfiles {
                   10638:     my ($cnum,$cdom,$ignorecache)=@_;
                   10639:     my $hashid=$cnum.':'.$cdom;
                   10640:     my ($suppcount,$cached);
                   10641:     unless ($ignorecache) {
                   10642:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10643:     }
                   10644:     unless (defined($cached)) {
                   10645:         my $chome=&homeserver($cnum,$cdom);
                   10646:         unless ($chome eq 'no_host') {
                   10647:             ($suppcount,my $errors) = (0,0);
                   10648:             my $suppmap = 'supplemental.sequence';
                   10649:             ($suppcount,$errors) = 
                   10650:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10651:         }
                   10652:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10653:     }
                   10654:     return $suppcount;
                   10655: }
                   10656: 
1.379     matthew  10657: #
                   10658: # EXT resource caching routines
                   10659: #
                   10660: 
1.1302    raeburn  10661: {
                   10662: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   10663: #
                   10664: # The course for which we cache
                   10665: my $cachedmapkey='';
                   10666: # The cached recursive maps for this course
                   10667: my %cachedmaps=();
                   10668: # When this was last done
                   10669: my $cachedmaptime='';
                   10670: 
1.379     matthew  10671: sub clear_EXT_cache_status {
1.383     albertel 10672:     &delenv('cache.EXT.');
1.379     matthew  10673: }
                   10674: 
                   10675: sub EXT_cache_status {
                   10676:     my ($target_domain,$target_user) = @_;
1.383     albertel 10677:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10678:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10679:         # We know already the user has no data
                   10680:         return 1;
                   10681:     } else {
                   10682:         return 0;
                   10683:     }
                   10684: }
                   10685: 
                   10686: sub EXT_cache_set {
                   10687:     my ($target_domain,$target_user) = @_;
1.383     albertel 10688:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10689:     #&appenv({$cachename => time});
1.379     matthew  10690: }
                   10691: 
1.28      www      10692: # --------------------------------------------------------- Value of a Variable
1.58      www      10693: sub EXT {
1.715     albertel 10694: 
1.1228    raeburn  10695:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10696:     unless ($varname) { return ''; }
1.218     albertel 10697:     #get real user name/domain, courseid and symb
                   10698:     my $courseid;
1.359     albertel 10699:     my $publicuser;
1.427     www      10700:     if ($symbparm) {
                   10701: 	$symbparm=&get_symb_from_alias($symbparm);
                   10702:     }
1.218     albertel 10703:     if (!($uname && $udom)) {
1.790     albertel 10704:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10705:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10706:     } else {
1.620     albertel 10707: 	$courseid=$env{'request.course.id'};
1.218     albertel 10708:     }
1.48      www      10709:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10710:     my $rest;
1.320     albertel 10711:     if (defined($therest[0])) {
1.48      www      10712:        $rest=join('.',@therest);
                   10713:     } else {
                   10714:        $rest='';
                   10715:     }
1.320     albertel 10716: 
1.57      www      10717:     my $qualifierrest=$qualifier;
                   10718:     if ($rest) { $qualifierrest.='.'.$rest; }
                   10719:     my $spacequalifierrest=$space;
                   10720:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      10721:     if ($realm eq 'user') {
1.48      www      10722: # --------------------------------------------------------------- user.resource
                   10723: 	if ($space eq 'resource') {
1.651     albertel 10724: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   10725: 		  || defined($Apache::lonhomework::parsing_a_task))
                   10726: 		 &&
1.744     albertel 10727: 		 ($symbparm eq &symbread()) ) {	
                   10728: 		# if we are in the middle of processing the resource the
                   10729: 		# get the value we are planning on committing
                   10730:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   10731:                     return $Apache::lonhomework::results{$qualifierrest};
                   10732:                 } else {
                   10733:                     return $Apache::lonhomework::history{$qualifierrest};
                   10734:                 }
1.335     albertel 10735: 	    } else {
1.359     albertel 10736: 		my %restored;
1.620     albertel 10737: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 10738: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   10739: 		} else {
                   10740: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   10741: 		}
1.335     albertel 10742: 		return $restored{$qualifierrest};
                   10743: 	    }
1.48      www      10744: # ----------------------------------------------------------------- user.access
                   10745:         } elsif ($space eq 'access') {
1.218     albertel 10746: 	    # FIXME - not supporting calls for a specific user
1.48      www      10747:             return &allowed($qualifier,$rest);
                   10748: # ------------------------------------------ user.preferences, user.environment
                   10749:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 10750: 	    if (($uname eq $env{'user.name'}) &&
                   10751: 		($udom eq $env{'user.domain'})) {
                   10752: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10753: 	    } else {
1.359     albertel 10754: 		my %returnhash;
                   10755: 		if (!$publicuser) {
                   10756: 		    %returnhash=&userenvironment($udom,$uname,
                   10757: 						 $qualifierrest);
                   10758: 		}
1.218     albertel 10759: 		return $returnhash{$qualifierrest};
                   10760: 	    }
1.48      www      10761: # ----------------------------------------------------------------- user.course
                   10762:         } elsif ($space eq 'course') {
1.218     albertel 10763: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10764:             return $env{join('.',('request.course',$qualifier))};
1.48      www      10765: # ------------------------------------------------------------------- user.role
                   10766:         } elsif ($space eq 'role') {
1.218     albertel 10767: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10768:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      10769:             if ($qualifier eq 'value') {
                   10770: 		return $role;
                   10771:             } elsif ($qualifier eq 'extent') {
                   10772:                 return $where;
                   10773:             }
                   10774: # ----------------------------------------------------------------- user.domain
                   10775:         } elsif ($space eq 'domain') {
1.218     albertel 10776:             return $udom;
1.48      www      10777: # ------------------------------------------------------------------- user.name
                   10778:         } elsif ($space eq 'name') {
1.218     albertel 10779:             return $uname;
1.48      www      10780: # ---------------------------------------------------- Any other user namespace
1.29      www      10781:         } else {
1.359     albertel 10782: 	    my %reply;
                   10783: 	    if (!$publicuser) {
                   10784: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10785: 	    }
                   10786: 	    return $reply{$qualifierrest};
1.48      www      10787:         }
1.236     www      10788:     } elsif ($realm eq 'query') {
                   10789: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10790:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10791: 						[$spacequalifierrest]);
1.620     albertel 10792: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10793:    } elsif ($realm eq 'request') {
1.48      www      10794: # ------------------------------------------------------------- request.browser
                   10795:         if ($space eq 'browser') {
1.1145    bisitz   10796:             return $env{'browser.'.$qualifier};
1.57      www      10797: # ------------------------------------------------------------ request.filename
                   10798:         } else {
1.620     albertel 10799:             return $env{'request.'.$spacequalifierrest};
1.29      www      10800:         }
1.28      www      10801:     } elsif ($realm eq 'course') {
1.48      www      10802: # ---------------------------------------------------------- course.description
1.620     albertel 10803:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10804:     } elsif ($realm eq 'resource') {
1.165     www      10805: 
1.620     albertel 10806: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10807: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10808: 	}
1.693     albertel 10809: 
1.1232    raeburn  10810:         if ($qualifier eq '') {
                   10811: 	    if ($space eq 'title') {
                   10812: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10813: 	        return &gettitle($symbparm);
                   10814: 	    }
1.693     albertel 10815: 	
1.1232    raeburn  10816: 	    if ($space eq 'map') {
                   10817: 	        my ($map) = &decode_symb($symbparm);
                   10818: 	        return &symbread($map);
                   10819: 	    }
                   10820:             if ($space eq 'maptitle') {
                   10821:                 my ($map) = &decode_symb($symbparm);
                   10822:                 return &gettitle($map);
                   10823:             }
                   10824: 	    if ($space eq 'filename') {
                   10825: 	        if ($symbparm) {
                   10826: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10827: 	        }
                   10828: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10829: 	    }
1.1232    raeburn  10830: 
1.1233    raeburn  10831:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10832:                 if ($space eq 'visibleparts') {
                   10833:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10834:                     my $item;
                   10835:                     if (ref($navmap)) {
                   10836:                         my $res = $navmap->getBySymb($symbparm);
                   10837:                         my $parts = $res->parts();
                   10838:                         if (ref($parts) eq 'ARRAY') {
                   10839:                             $item = join(',',@{$parts});
                   10840:                         }
                   10841:                         undef($navmap);
1.1232    raeburn  10842:                     }
1.1233    raeburn  10843:                     return $item;
1.1232    raeburn  10844:                 }
                   10845:             }
                   10846:         }
1.693     albertel 10847: 
1.1301    raeburn  10848: 	my ($section, $group, @groups, @recurseup, $recursed);
                   10849: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  10850:         if (($courseid eq '') && ($cid)) {
                   10851:             $courseid = $cid;
                   10852:         }
                   10853: 	if (($symbparm && $courseid) && 
                   10854: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      10855: 
1.218     albertel 10856: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10857: 
1.60      www      10858: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10859: 	    my $symbp=$symbparm;
1.1301    raeburn  10860: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10861: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  10862:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 10863: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 10864: 	    if (($env{'user.name'} eq $uname) &&
                   10865: 		($env{'user.domain'} eq $udom)) {
                   10866: 		$section=$env{'request.course.sec'};
1.733     raeburn  10867:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10868:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10869: 	    } else {
1.539     albertel 10870: 		if (! defined($usection)) {
1.551     albertel 10871: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10872: 		} else {
                   10873: 		    $section = $usection;
                   10874: 		}
1.733     raeburn  10875:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10876: 	    }
                   10877: 
                   10878: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10879: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  10880:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 10881: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10882: 
1.593     albertel 10883: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10884: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  10885:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 10886: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10887: 
1.60      www      10888: # ----------------------------------------------------------- first, check user
1.624     albertel 10889: 
1.1301    raeburn  10890: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   10891:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 10892: 				       ([$courselevelr,'resource'],
                   10893: 					[$courselevelm,'map'     ],
1.1301    raeburn  10894:                                         [$courseleveli,'map'     ],
1.927     albertel 10895: 					[$courselevel, 'course'  ]));
1.931     albertel 10896: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10897: 
1.594     albertel 10898: # ------------------------------------------------ second, check some of course
1.684     raeburn  10899:             my $coursereply;
1.691     raeburn  10900:             if (@groups > 0) {
                   10901:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  10902:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   10903:                                        $mapp,\$recursed,\@recurseup);
                   10904:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  10905:             }
1.96      www      10906: 
1.684     raeburn  10907: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10908: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  10909: 				  'course',$mapp,\$recursed,\@recurseup,
                   10910:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 10911: 				  ([$seclevelr,   'resource'],
                   10912: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  10913:                                    [$secleveli,   'map'     ],
1.927     albertel 10914: 				   [$seclevel,    'course'  ],
                   10915: 				   [$courselevelr,'resource']));
                   10916: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10917: 
1.60      www      10918: # ------------------------------------------------------ third, check map parms
1.218     albertel 10919: 	    my %parmhash=();
                   10920: 	    my $thisparm='';
                   10921: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10922: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10923: 		    &GDBM_READER(),0640)) {
1.218     albertel 10924: 		$thisparm=$parmhash{$symbparm};
                   10925: 		untie(%parmhash);
                   10926: 	    }
1.927     albertel 10927: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10928: 	}
1.594     albertel 10929: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  10930:  
                   10931:         my $what = $spacequalifierrest;
                   10932: 	$what=~s/\./\_/;
1.282     albertel 10933: 	my $filename;
                   10934: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10935: 	if ($symbparm) {
1.409     www      10936: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10937: 	} else {
1.620     albertel 10938: 	    $filename=$env{'request.filename'};
1.282     albertel 10939: 	}
1.1301    raeburn  10940: 	my $metadata=&metadata($filename,$what);
1.927     albertel 10941: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1301    raeburn  10942: 	$metadata=&metadata($filename,'parameter_'.$what);
1.927     albertel 10943: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10944: 
1.1301    raeburn  10945: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 10946: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10947: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10948: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10949: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  10950: 				     'course',$mapp,\$recursed,\@recurseup,
                   10951:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 10952: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  10953:                                       [$courseleveli,'map'   ],
1.927     albertel 10954: 				      [$courselevel, 'course']));
                   10955: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10956: 	}
1.145     www      10957: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10958: 	unless ($space eq '0') {
1.336     albertel 10959: 	    my @parts=split(/_/,$space);
                   10960: 	    my $id=pop(@parts);
                   10961: 	    my $part=join('_',@parts);
                   10962: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10963: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10964: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10965: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10966: 	}
1.395     albertel 10967: 	if ($recurse) { return undef; }
                   10968: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10969: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10970: # ---------------------------------------------------- Any other user namespace
                   10971:     } elsif ($realm eq 'environment') {
                   10972: # ----------------------------------------------------------------- environment
1.620     albertel 10973: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10974: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10975: 	} else {
1.770     albertel 10976: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10977: 		return '';
                   10978: 	    }
1.219     albertel 10979: 	    my %returnhash=&userenvironment($udom,$uname,
                   10980: 					    $spacequalifierrest);
                   10981: 	    return $returnhash{$spacequalifierrest};
                   10982: 	}
1.28      www      10983:     } elsif ($realm eq 'system') {
1.48      www      10984: # ----------------------------------------------------------------- system.time
                   10985: 	if ($space eq 'time') {
                   10986: 	    return time;
                   10987:         }
1.696     albertel 10988:     } elsif ($realm eq 'server') {
                   10989: # ----------------------------------------------------------------- system.time
                   10990: 	if ($space eq 'name') {
                   10991: 	    return $ENV{'SERVER_NAME'};
                   10992:         }
1.28      www      10993:     }
1.48      www      10994:     return '';
1.61      www      10995: }
                   10996: 
1.927     albertel 10997: sub get_reply {
                   10998:     my ($reply_value) = @_;
1.940     raeburn  10999:     if (ref($reply_value) eq 'ARRAY') {
                   11000:         if (wantarray) {
                   11001: 	    return @$reply_value;
                   11002:         }
                   11003:         return $reply_value->[0];
                   11004:     } else {
                   11005:         return $reply_value;
1.927     albertel 11006:     }
                   11007: }
                   11008: 
1.691     raeburn  11009: sub check_group_parms {
1.1301    raeburn  11010:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   11011:         $recursed,$recurseupref) = @_;
                   11012:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   11013:                   [$what,'course']);
                   11014:     my $coursereply;
1.691     raeburn  11015:     foreach my $group (@{$groups}) {
1.1301    raeburn  11016:         my @groupitems = ();
1.691     raeburn  11017:         foreach my $level (@levels) {
1.927     albertel 11018:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11019:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11020:         }
1.1301    raeburn  11021:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11022:                                    $env{'course.'.$courseid.'.domain'},
                   11023:                                    'course',$mapp,$recursed,$recurseupref,
                   11024:                                    $courseid,'.['.$group.'].',$what,
                   11025:                                    @groupitems);
                   11026:         last if (defined($coursereply));
1.691     raeburn  11027:     }
                   11028:     return $coursereply;
                   11029: }
                   11030: 
1.1301    raeburn  11031: sub get_map_hierarchy {
1.1302    raeburn  11032:     my ($mapname,$courseid) = @_;
                   11033:     my @recurseup = ();
1.1301    raeburn  11034:     if ($mapname) {
1.1302    raeburn  11035:         if (($cachedmapkey eq $courseid) &&
                   11036:             (abs($cachedmaptime-time)<5)) {
                   11037:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   11038:                 return @{$cachedmaps{$mapname}};
                   11039:             }
                   11040:         }
1.1301    raeburn  11041:         my $navmap = Apache::lonnavmaps::navmap->new();
                   11042:         if (ref($navmap)) {
                   11043:             @recurseup = $navmap->recurseup_maps($mapname);
                   11044:             undef($navmap);
1.1302    raeburn  11045:             $cachedmaps{$mapname} = \@recurseup;
                   11046:             $cachedmaptime=time;
                   11047:             $cachedmapkey=$courseid;
1.1301    raeburn  11048:         }
                   11049:     }
                   11050:     return @recurseup;
                   11051: }
                   11052: 
1.1302    raeburn  11053: }
                   11054: 
1.691     raeburn  11055: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11056:     my ($courseid,@groups) = @_;
                   11057:     @groups = sort(@groups);
1.691     raeburn  11058:     return @groups;
                   11059: }
                   11060: 
1.395     albertel 11061: sub packages_tab_default {
                   11062:     my ($uri,$varname)=@_;
                   11063:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11064: 
                   11065:     my (@extension,@specifics,$do_default);
                   11066:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11067: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11068: 	if ($pack_type eq 'default') {
                   11069: 	    $do_default=1;
                   11070: 	} elsif ($pack_type eq 'extension') {
                   11071: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11072: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11073: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11074: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11075: 	}
                   11076:     }
                   11077:     # first look for a package that matches the requested part id
                   11078:     foreach my $package (@specifics) {
                   11079: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11080: 	next if ($pack_part ne $part);
                   11081: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11082: 	    return $packagetab{"$pack_type&$name&default"};
                   11083: 	}
                   11084:     }
                   11085:     # look for any possible matching non extension_ package
                   11086:     foreach my $package (@specifics) {
                   11087: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11088: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11089: 	    return $packagetab{"$pack_type&$name&default"};
                   11090: 	}
1.585     albertel 11091: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11092: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11093: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11094: 	}
                   11095:     }
1.738     albertel 11096:     # look for any posible extension_ match
                   11097:     foreach my $package (@extension) {
                   11098: 	my ($package,$pack_type)=@{$package};
                   11099: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11100: 	    return $packagetab{"$pack_type&$name&default"};
                   11101: 	}
                   11102: 	if (defined($packagetab{$package."&$name&default"})) {
                   11103: 	    return $packagetab{$package."&$name&default"};
                   11104: 	}
                   11105:     }
                   11106:     # look for a global default setting
                   11107:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11108: 	return $packagetab{"default&$name&default"};
                   11109:     }
1.395     albertel 11110:     return undef;
                   11111: }
                   11112: 
1.334     albertel 11113: sub add_prefix_and_part {
                   11114:     my ($prefix,$part)=@_;
                   11115:     my $keyroot;
                   11116:     if (defined($prefix) && $prefix !~ /^__/) {
                   11117: 	# prefix that has a part already
                   11118: 	$keyroot=$prefix;
                   11119:     } elsif (defined($prefix)) {
                   11120: 	# prefix that is missing a part
                   11121: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11122:     } else {
                   11123: 	# no prefix at all
                   11124: 	if (defined($part)) { $keyroot='_'.$part; }
                   11125:     }
                   11126:     return $keyroot;
                   11127: }
                   11128: 
1.71      www      11129: # ---------------------------------------------------------------- Get metadata
                   11130: 
1.599     albertel 11131: my %metaentry;
1.1070    www      11132: my %importedpartids;
1.71      www      11133: sub metadata {
1.176     www      11134:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11135:     $uri=&declutter($uri);
1.288     albertel 11136:     # if it is a non metadata possible uri return quickly
1.529     albertel 11137:     if (($uri eq '') || 
                   11138: 	(($uri =~ m|^/*adm/|) && 
1.1298    raeburn  11139: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|exttools?)$})) ||
1.1108    raeburn  11140:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11141: 	return undef;
                   11142:     }
1.1261    raeburn  11143:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11144: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11145: 	return undef;
1.288     albertel 11146:     }
1.73      www      11147:     my $filename=$uri;
                   11148:     $uri=~s/\.meta$//;
1.172     www      11149: #
                   11150: # Is the metadata already cached?
1.177     www      11151: # Look at timestamp of caching
1.172     www      11152: # Everything is cached by the main uri, libraries are never directly cached
                   11153: #
1.428     albertel 11154:     if (!defined($liburi)) {
1.599     albertel 11155: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11156: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11157:     }
                   11158:     {
1.1069    www      11159: # Imported parts would go here
1.1070    www      11160:         my %importedids=();
                   11161:         my @origfileimportpartids=();
1.1069    www      11162:         my $importedparts=0;
1.172     www      11163: #
                   11164: # Is this a recursive call for a library?
                   11165: #
1.599     albertel 11166: #	if (! exists($metacache{$uri})) {
                   11167: #	    $metacache{$uri}={};
                   11168: #	}
1.924     albertel 11169: 	my $cachetime = 60*60;
1.171     www      11170:         if ($liburi) {
                   11171: 	    $liburi=&declutter($liburi);
                   11172:             $filename=$liburi;
1.401     bowersj2 11173:         } else {
1.599     albertel 11174: 	    &devalidate_cache_new('meta',$uri);
                   11175: 	    undef(%metaentry);
1.401     bowersj2 11176: 	}
1.140     www      11177:         my %metathesekeys=();
1.73      www      11178:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11179: 	my $metastring;
1.1140    www      11180: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11181: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11182: 	    $metastring = 
1.929     albertel 11183: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11184: 					  ('grade_target' => 'meta'));
                   11185: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11186: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11187:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11188: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11189: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11190: 	    $metastring=&getfile($file);
1.489     albertel 11191: 	}
1.208     albertel 11192:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11193:         my $token;
1.140     www      11194:         undef %metathesekeys;
1.71      www      11195:         while ($token=$parser->get_token) {
1.339     albertel 11196: 	    if ($token->[0] eq 'S') {
                   11197: 		if (defined($token->[2]->{'package'})) {
1.172     www      11198: #
                   11199: # This is a package - get package info
                   11200: #
1.339     albertel 11201: 		    my $package=$token->[2]->{'package'};
                   11202: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11203: 		    if (defined($token->[2]->{'id'})) { 
                   11204: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11205: 		    }
1.599     albertel 11206: 		    if ($metaentry{':packages'}) {
                   11207: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11208: 		    } else {
1.599     albertel 11209: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11210: 		    }
1.736     albertel 11211: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11212: 			my $part=$keyroot;
                   11213: 			$part=~s/^\_//;
1.736     albertel 11214: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11215: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11216: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11217: 			    # ignore package.tab specified default values
                   11218:                             # here &package_tab_default() will fetch those
                   11219: 			    if ($subp eq 'default') { next; }
1.736     albertel 11220: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11221: 			    my $unikey;
                   11222: 			    if ($pack =~ /_0$/) {
                   11223: 				$unikey='parameter_0_'.$name;
                   11224: 				$part=0;
                   11225: 			    } else {
                   11226: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11227: 			    }
1.339     albertel 11228: 			    if ($subp eq 'display') {
                   11229: 				$value.=' [Part: '.$part.']';
                   11230: 			    }
1.599     albertel 11231: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11232: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11233: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11234: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11235: 			    }
1.599     albertel 11236: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11237: 				$metaentry{':'.$unikey}=
                   11238: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11239: 			    }
1.339     albertel 11240: 			}
                   11241: 		    }
                   11242: 		} else {
1.172     www      11243: #
                   11244: # This is not a package - some other kind of start tag
1.339     albertel 11245: #
                   11246: 		    my $entry=$token->[1];
1.1068    www      11247: 		    my $unikey='';
1.175     www      11248: 
1.339     albertel 11249: 		    if ($entry eq 'import') {
1.175     www      11250: #
                   11251: # Importing a library here
1.339     albertel 11252: #
1.1067    www      11253:                         my $location=$parser->get_text('/import');
                   11254:                         my $dir=$filename;
                   11255:                         $dir=~s|[^/]*$||;
                   11256:                         $location=&filelocation($dir,$location);
1.1069    www      11257:                        
1.1068    www      11258:                         my $importmode=$token->[2]->{'importmode'};
                   11259:                         if ($importmode eq 'problem') {
1.1069    www      11260: # Import as problem/response
1.1068    www      11261:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11262:                         } elsif ($importmode eq 'part') {
                   11263: # Import as part(s)
1.1069    www      11264:                            $importedparts=1;
                   11265: # We need to get the original file and the imported file to get the part order correct
                   11266: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   11267: # Load and inspect original file
1.1070    www      11268:                            if ($#origfileimportpartids<0) {
                   11269:                               undef(%importedpartids);
                   11270:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11271:                               my $origfile=&getfile($origfilelocation);
                   11272:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11273:                            }
                   11274: 
1.1069    www      11275: # Load and inspect imported file
                   11276:                            my $impfile=&getfile($location);
                   11277:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11278:                            if ($#impfilepartids>=0) {
                   11279: # This problem had parts
1.1070    www      11280:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11281:                            } else {
                   11282: # Importing by turning a single problem into a problem part
                   11283: # It gets the import-tags ID as part-ID
                   11284:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11285:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11286:                            }
1.1068    www      11287:                         } else {
                   11288: # Normal import
                   11289:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11290:                            if (defined($token->[2]->{'id'})) {
                   11291:                               $unikey.='_'.$token->[2]->{'id'};
                   11292:                            }
1.1067    www      11293:                         }
                   11294: 
1.339     albertel 11295: 			if ($depthcount<20) {
1.736     albertel 11296: 			    my $metadata = 
                   11297: 				&metadata($uri,'keys', $location,$unikey,
                   11298: 					  $depthcount+1);
                   11299: 			    foreach my $meta (split(',',$metadata)) {
                   11300: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11301: 				$metathesekeys{$meta}=1;
1.339     albertel 11302: 			    }
1.1068    www      11303: 			
                   11304:                         }
1.1067    www      11305: 		    } else {
                   11306: #
                   11307: # Not importing, some other kind of non-package, non-library start tag
                   11308: # 
                   11309:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11310:                         if (defined($token->[2]->{'id'})) {
                   11311:                             $unikey.='_'.$token->[2]->{'id'};
                   11312:                         }
1.339     albertel 11313: 			if (defined($token->[2]->{'name'})) { 
                   11314: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11315: 			}
                   11316: 			$metathesekeys{$unikey}=1;
1.736     albertel 11317: 			foreach my $param (@{$token->[3]}) {
                   11318: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11319: 				$token->[2]->{$param};
1.339     albertel 11320: 			}
                   11321: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11322: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11323: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11324: 		 # only ws inside the tag, and not in default, so use default
                   11325: 		 # as value
1.599     albertel 11326: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11327: 			} elsif ( $internaltext =~ /\S/ ) {
                   11328: 		  # something interesting inside the tag
                   11329: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11330: 			} else {
1.908     albertel 11331: 		  # no interesting values, don't set a default
1.339     albertel 11332: 			}
1.172     www      11333: # end of not-a-package not-a-library import
1.339     albertel 11334: 		    }
1.172     www      11335: # end of not-a-package start tag
1.339     albertel 11336: 		}
1.172     www      11337: # the next is the end of "start tag"
1.339     albertel 11338: 	    }
                   11339: 	}
1.483     albertel 11340: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11341: 	$extension = lc($extension);
                   11342: 	if ($extension eq 'htm') { $extension='html'; }
                   11343: 
1.737     albertel 11344: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11345: 	    #no specific packages #how's our extension
                   11346: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11347: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11348: 					 \%metathesekeys);
                   11349: 	}
1.883     albertel 11350: 
                   11351: 	if (!exists($metaentry{':packages'})
                   11352: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11353: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11354: 		#no specific packages well let's get default then
                   11355: 		if ($key!~/^default&/) { next; }
1.488     albertel 11356: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11357: 					     \%metathesekeys);
                   11358: 	    }
                   11359: 	}
1.338     www      11360: # are there custom rights to evaluate
1.599     albertel 11361: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11362: 
1.338     www      11363:     #
                   11364:     # Importing a rights file here
1.339     albertel 11365:     #
                   11366: 	    unless ($depthcount) {
1.599     albertel 11367: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11368: 		my $dir=$filename;
                   11369: 		$dir=~s|[^/]*$||;
                   11370: 		$location=&filelocation($dir,$location);
1.736     albertel 11371: 		my $rights_metadata =
                   11372: 		    &metadata($uri,'keys',$location,'_rights',
                   11373: 			      $depthcount+1);
                   11374: 		foreach my $rights (split(',',$rights_metadata)) {
                   11375: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11376: 		    $metathesekeys{$rights}=1;
1.339     albertel 11377: 		}
                   11378: 	    }
                   11379: 	}
1.737     albertel 11380: 	# uniqifiy package listing
                   11381: 	my %seen;
                   11382: 	my @uniq_packages =
                   11383: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11384: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11385: 
1.1070    www      11386:         if ($importedparts) {
                   11387: # We had imported parts and need to rebuild partorder
                   11388:            $metaentry{':partorder'}='';
                   11389:            $metathesekeys{'partorder'}=1;
                   11390:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   11391:                if ($origfileimportpartids[$index] eq 'part') {
                   11392: # original part, part of the problem
                   11393:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   11394:                } else {
                   11395: # we have imported parts at this position
                   11396:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   11397:                }
                   11398:            }
                   11399:            $metaentry{':partorder'}=~s/^\,//;
                   11400:         }
                   11401: 
1.737     albertel 11402: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11403: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  11404: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 11405: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      11406: # this is the end of "was not already recently cached
1.71      www      11407:     }
1.599     albertel 11408:     return $metaentry{':'.$what};
1.261     albertel 11409: }
                   11410: 
1.488     albertel 11411: sub metadata_create_package_def {
1.483     albertel 11412:     my ($uri,$key,$package,$metathesekeys)=@_;
                   11413:     my ($pack,$name,$subp)=split(/\&/,$key);
                   11414:     if ($subp eq 'default') { next; }
                   11415:     
1.599     albertel 11416:     if (defined($metaentry{':packages'})) {
                   11417: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 11418:     } else {
1.599     albertel 11419: 	$metaentry{':packages'}=$package;
1.483     albertel 11420:     }
                   11421:     my $value=$packagetab{$key};
                   11422:     my $unikey;
                   11423:     $unikey='parameter_0_'.$name;
1.599     albertel 11424:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 11425:     $$metathesekeys{$unikey}=1;
1.599     albertel 11426:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11427: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 11428:     }
1.599     albertel 11429:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   11430: 	$metaentry{':'.$unikey}=
                   11431: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 11432:     }
                   11433: }
                   11434: 
1.261     albertel 11435: sub metadata_generate_part0 {
                   11436:     my ($metadata,$metacache,$uri) = @_;
                   11437:     my %allnames;
1.737     albertel 11438:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 11439: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 11440: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   11441: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 11442: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 11443: 	    $allnames{$name}=$part;
                   11444: 	  }
                   11445: 	}
                   11446:     }
                   11447:     foreach my $name (keys(%allnames)) {
                   11448:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 11449:       my $key=":parameter_0_$name";
1.261     albertel 11450:       $$metacache{"$key.part"}='0';
                   11451:       $$metacache{"$key.name"}=$name;
1.428     albertel 11452:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 11453: 					   $allnames{$name}.'_'.$name.
                   11454: 					   '.type'};
1.428     albertel 11455:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 11456: 			     '.display'};
1.644     www      11457:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11458:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11459:       $$metacache{"$key.display"}=$olddis;
                   11460:     }
1.71      www      11461: }
                   11462: 
1.764     albertel 11463: # ------------------------------------------------------ Devalidate title cache
                   11464: 
                   11465: sub devalidate_title_cache {
                   11466:     my ($url)=@_;
                   11467:     if (!$env{'request.course.id'}) { return; }
                   11468:     my $symb=&symbread($url);
                   11469:     if (!$symb) { return; }
                   11470:     my $key=$env{'request.course.id'}."\0".$symb;
                   11471:     &devalidate_cache_new('title',$key);
                   11472: }
                   11473: 
1.1014    droeschl 11474: # ------------------------------------------------- Get the title of a course
                   11475: 
                   11476: sub current_course_title {
                   11477:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11478: }
1.301     www      11479: # ------------------------------------------------- Get the title of a resource
                   11480: 
                   11481: sub gettitle {
                   11482:     my $urlsymb=shift;
                   11483:     my $symb=&symbread($urlsymb);
1.534     albertel 11484:     if ($symb) {
1.620     albertel 11485: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11486: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11487: 	if (defined($cached)) { 
                   11488: 	    return $result;
                   11489: 	}
1.534     albertel 11490: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11491: 	my $title='';
1.907     albertel 11492: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11493: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11494: 	} else {
                   11495: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11496: 		    &GDBM_READER(),0640)) {
                   11497: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11498: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11499: 		untie(%bighash);
                   11500: 	    }
1.534     albertel 11501: 	}
                   11502: 	$title=~s/\&colon\;/\:/gs;
                   11503: 	if ($title) {
1.1159    www      11504: # Remember both $symb and $title for dynamic metadata
                   11505:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11506:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11507: # Cache this title and then return it
1.599     albertel 11508: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11509: 	}
                   11510: 	$urlsymb=$url;
                   11511:     }
                   11512:     my $title=&metadata($urlsymb,'title');
                   11513:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11514:     return $title;
1.301     www      11515: }
1.613     albertel 11516: 
1.614     albertel 11517: sub get_slot {
                   11518:     my ($which,$cnum,$cdom)=@_;
                   11519:     if (!$cnum || !$cdom) {
1.790     albertel 11520: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11521: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11522: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11523:     }
1.703     albertel 11524:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11525:     my %slotinfo;
                   11526:     if (exists($remembered{$key})) {
                   11527: 	$slotinfo{$which} = $remembered{$key};
                   11528:     } else {
                   11529: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11530: 	&Apache::lonhomework::showhash(%slotinfo);
                   11531: 	my ($tmp)=keys(%slotinfo);
                   11532: 	if ($tmp=~/^error:/) { return (); }
                   11533: 	$remembered{$key} = $slotinfo{$which};
                   11534:     }
1.616     albertel 11535:     if (ref($slotinfo{$which}) eq 'HASH') {
                   11536: 	return %{$slotinfo{$which}};
                   11537:     }
                   11538:     return $slotinfo{$which};
1.614     albertel 11539: }
1.1150    raeburn  11540: 
                   11541: sub get_reservable_slots {
                   11542:     my ($cnum,$cdom,$uname,$udom) = @_;
                   11543:     my $now = time;
                   11544:     my $reservable_info;
                   11545:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   11546:     if (exists($remembered{$key})) {
                   11547:         $reservable_info = $remembered{$key};
                   11548:     } else {
                   11549:         my %resv;
                   11550:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   11551:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   11552:         $reservable_info = \%resv;
                   11553:         $remembered{$key} = $reservable_info;
                   11554:     }
                   11555:     return $reservable_info;
                   11556: }
                   11557: 
                   11558: sub get_course_slots {
                   11559:     my ($cnum,$cdom) = @_;
                   11560:     my $hashid=$cnum.':'.$cdom;
                   11561:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   11562:     if (defined($cached)) {
                   11563:         if (ref($result) eq 'HASH') {
                   11564:             return %{$result};
                   11565:         }
                   11566:     } else {
                   11567:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   11568:         my ($tmp) = keys(%slots);
                   11569:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  11570:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  11571:             return %slots;
                   11572:         }
                   11573:     }
                   11574:     return;
                   11575: }
                   11576: 
                   11577: sub devalidate_slots_cache {
                   11578:     my ($cnum,$cdom)=@_;
                   11579:     my $hashid=$cnum.':'.$cdom;
                   11580:     &devalidate_cache_new('allslots',$hashid);
                   11581: }
                   11582: 
1.1181    raeburn  11583: sub get_coursechange {
                   11584:     my ($cdom,$cnum) = @_;
                   11585:     if ($cdom eq '' || $cnum eq '') {
                   11586:         return unless ($env{'request.course.id'});
                   11587:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11588:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11589:     }
                   11590:     my $hashid=$cdom.'_'.$cnum;
                   11591:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   11592:     if ((defined($cached)) && ($change ne '')) {
                   11593:         return $change;
                   11594:     } else {
                   11595:         my %crshash;
                   11596:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   11597:         if ($crshash{'internal.contentchange'} eq '') {
                   11598:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   11599:             if ($change eq '') {
                   11600:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   11601:                 $change = $crshash{'internal.created'};
                   11602:             }
                   11603:         } else {
                   11604:             $change = $crshash{'internal.contentchange'};
                   11605:         }
                   11606:         my $cachetime = 600;
                   11607:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   11608:     }
                   11609:     return $change;
                   11610: }
                   11611: 
                   11612: sub devalidate_coursechange_cache {
                   11613:     my ($cnum,$cdom)=@_;
                   11614:     my $hashid=$cnum.':'.$cdom;
                   11615:     &devalidate_cache_new('crschange',$hashid);
                   11616: }
                   11617: 
1.31      www      11618: # ------------------------------------------------- Update symbolic store links
                   11619: 
                   11620: sub symblist {
                   11621:     my ($mapname,%newhash)=@_;
1.438     www      11622:     $mapname=&deversion(&declutter($mapname));
1.31      www      11623:     my %hash;
1.620     albertel 11624:     if (($env{'request.course.fn'}) && (%newhash)) {
                   11625:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11626:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  11627: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 11628: 		next if ($url eq 'last_known'
                   11629: 			 && $env{'form.no_update_last_known'});
                   11630: 		$hash{declutter($url)}=&encode_symb($mapname,
                   11631: 						    $newhash{$url}->[1],
                   11632: 						    $newhash{$url}->[0]);
1.191     harris41 11633:             }
1.31      www      11634:             if (untie(%hash)) {
                   11635: 		return 'ok';
                   11636:             }
                   11637:         }
                   11638:     }
                   11639:     return 'error';
1.212     www      11640: }
                   11641: 
                   11642: # --------------------------------------------------------------- Verify a symb
                   11643: 
                   11644: sub symbverify {
1.1190    raeburn  11645:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      11646:     my $thisfn=$thisurl;
1.439     www      11647:     $thisfn=&declutter($thisfn);
1.215     www      11648: # direct jump to resource in page or to a sequence - will construct own symbs
                   11649:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   11650: # check URL part
1.409     www      11651:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      11652: 
1.431     www      11653:     unless ($url eq $thisfn) { return 0; }
1.213     www      11654: 
1.216     www      11655:     $symb=&symbclean($symb);
1.510     www      11656:     $thisurl=&deversion($thisurl);
1.439     www      11657:     $thisfn=&deversion($thisfn);
1.213     www      11658: 
                   11659:     my %bighash;
                   11660:     my $okay=0;
1.431     www      11661: 
1.620     albertel 11662:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11663:                             &GDBM_READER(),0640)) {
1.1204    raeburn  11664:         my $noclutter;
1.1032    raeburn  11665:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   11666:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  11667:             if ($map =~ m{^uploaded/.+\.page$}) {
                   11668:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   11669:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   11670:                 $noclutter = 1;
                   11671:             }
                   11672:         }
                   11673:         my $ids;
                   11674:         if ($noclutter) {
                   11675:             $ids=$bighash{'ids_'.$thisurl};
                   11676:         } else {
                   11677:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  11678:         }
1.1102    raeburn  11679:         unless ($ids) {
                   11680:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   11681:             $ids=$bighash{$idkey};
1.216     www      11682:         }
                   11683:         if ($ids) {
                   11684: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  11685:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  11686:                 $symb =~ s/\?.+$//;
1.1202    raeburn  11687:             }
1.800     albertel 11688: 	    foreach my $id (split(/\,/,$ids)) {
                   11689: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      11690:                if (
                   11691:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  11692:    eq $symb) {
                   11693:                    if (ref($encstate)) {
                   11694:                        $$encstate = $bighash{'encrypted_'.$id};
                   11695:                    }
1.620     albertel 11696: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  11697: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   11698:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  11699: 		       $okay=1;
1.1202    raeburn  11700:                        last;
1.582     albertel 11701: 		   }
                   11702: 	       }
1.216     www      11703: 	   }
                   11704:         }
1.213     www      11705: 	untie(%bighash);
                   11706:     }
                   11707:     return $okay;
1.31      www      11708: }
                   11709: 
1.210     www      11710: # --------------------------------------------------------------- Clean-up symb
                   11711: 
                   11712: sub symbclean {
                   11713:     my $symb=shift;
1.568     albertel 11714:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11715: # remove version from map
                   11716:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11717: 
1.210     www      11718: # remove version from URL
                   11719:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      11720: 
1.507     www      11721: # remove wrapper
                   11722: 
1.510     www      11723:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 11724:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      11725:     return $symb;
1.409     www      11726: }
                   11727: 
                   11728: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 11729: 
                   11730: sub encode_symb {
                   11731:     my ($map,$resid,$url)=@_;
                   11732:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   11733: }
1.409     www      11734: 
                   11735: sub decode_symb {
1.568     albertel 11736:     my $symb=shift;
                   11737:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   11738:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      11739:     return (&fixversion($map),$resid,&fixversion($url));
                   11740: }
                   11741: 
                   11742: sub fixversion {
                   11743:     my $fn=shift;
1.609     banghart 11744:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      11745:     my %bighash;
                   11746:     my $uri=&clutter($fn);
1.620     albertel 11747:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      11748: # is this cached?
1.599     albertel 11749:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      11750:     if (defined($cached)) { return $result; }
                   11751: # unfortunately not cached, or expired
1.620     albertel 11752:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      11753: 	    &GDBM_READER(),0640)) {
                   11754:  	if ($bighash{'version_'.$uri}) {
                   11755:  	    my $version=$bighash{'version_'.$uri};
1.444     www      11756:  	    unless (($version eq 'mostrecent') || 
                   11757: 		    ($version==&getversion($uri))) {
1.440     www      11758:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   11759:  	    }
                   11760:  	}
                   11761:  	untie %bighash;
1.413     www      11762:     }
1.599     albertel 11763:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      11764: }
                   11765: 
                   11766: sub deversion {
                   11767:     my $url=shift;
                   11768:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   11769:     return $url;
1.210     www      11770: }
                   11771: 
1.31      www      11772: # ------------------------------------------------------ Return symb list entry
                   11773: 
                   11774: sub symbread {
1.1282    raeburn  11775:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  11776:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  11777:     if (defined($env{$cache_str})) {
                   11778:         if ($ignorecachednull) {
                   11779:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   11780:         } else {
                   11781:             return $env{$cache_str};
                   11782:         }
                   11783:     }
1.242     www      11784: # no filename provided? try from environment
1.1265    raeburn  11785:     unless ($thisfn) {
1.620     albertel 11786:         if ($env{'request.symb'}) {
                   11787: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 11788: 	}
1.620     albertel 11789: 	$thisfn=$env{'request.filename'};
1.44      www      11790:     }
1.569     albertel 11791:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      11792: # is that filename actually a symb? Verify, clean, and return
                   11793:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 11794: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 11795: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 11796: 	}
1.242     www      11797:     }
1.44      www      11798:     $thisfn=declutter($thisfn);
1.31      www      11799:     my %hash;
1.37      www      11800:     my %bighash;
                   11801:     my $syval='';
1.620     albertel 11802:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  11803:         my $targetfn = $thisfn;
1.609     banghart 11804:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  11805:             $targetfn = 'adm/wrapper/'.$thisfn;
                   11806:         }
1.687     albertel 11807: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   11808: 	    $targetfn=$1;
                   11809: 	}
1.620     albertel 11810:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11811:                       &GDBM_READER(),0640)) {
1.481     raeburn  11812: 	    $syval=$hash{$targetfn};
1.37      www      11813:             untie(%hash);
                   11814:         }
                   11815: # ---------------------------------------------------------- There was an entry
                   11816:         if ($syval) {
1.601     albertel 11817: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 11818: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  11819: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11820: 		    #return $env{$cache_str}='';
1.601     albertel 11821: 		#}    
                   11822: 		#$syval.=$1;
                   11823: 	    #}
1.37      www      11824:         } else {
                   11825: # ------------------------------------------------------- Was not in symb table
1.620     albertel 11826:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11827:                             &GDBM_READER(),0640)) {
1.37      www      11828: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      11829:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      11830:               unless ($ids) { 
                   11831:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      11832:               }
                   11833:               unless ($ids) {
                   11834: # alias?
                   11835: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      11836:               }
1.37      www      11837:               if ($ids) {
                   11838: # ------------------------------------------------------------------- Has ID(s)
                   11839:                  my @possibilities=split(/\,/,$ids);
1.39      www      11840:                  if ($#possibilities==0) {
                   11841: # ----------------------------------------------- There is only one possibility
1.37      www      11842: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 11843: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11844: 						    $resid,$thisfn);
1.1282    raeburn  11845:                      if (ref($possibles) eq 'HASH') {
                   11846:                          $possibles->{$syval} = 1;    
                   11847:                      }
                   11848:                      if ($checkforblock) {
                   11849:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   11850:                          if (@blockers) {
                   11851:                              $syval = '';
                   11852:                              return;
                   11853:                          }
                   11854:                      }
                   11855:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      11856: # ------------------------------------------ There is more than one possibility
                   11857:                      my $realpossible=0;
1.800     albertel 11858:                      foreach my $id (@possibilities) {
                   11859: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  11860:                          my $canaccess;
                   11861:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   11862:                              $canaccess = 1;
                   11863:                          } else { 
                   11864:                              $canaccess = &allowed('bre',$file);
                   11865:                          }
                   11866:                          if ($canaccess) {
                   11867:          		     my ($mapid,$resid)=split(/\./,$id);
                   11868:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11869:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11870: 						             $resid,$thisfn);
                   11871:                                  if (ref($possibles) eq 'HASH') {
                   11872:                                      $possibles->{$syval} = 1;
                   11873:                                  }
                   11874:                                  if ($checkforblock) {
                   11875:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   11876:                                      unless (@blockers > 0) {
                   11877:                                          $syval = $poss_syval;
                   11878:                                          $realpossible++;
                   11879:                                      }
                   11880:                                  } else {
                   11881:                                      $syval = $poss_syval;
                   11882:                                      $realpossible++;
                   11883:                                  }
                   11884:                              }
1.39      www      11885: 			 }
1.191     harris41 11886:                      }
1.39      www      11887: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11888:                  } else {
                   11889:                      $syval='';
1.37      www      11890:                  }
                   11891: 	      }
1.1282    raeburn  11892:               untie(%bighash);
1.481     raeburn  11893:            }
1.31      www      11894:         }
1.62      www      11895:         if ($syval) {
1.620     albertel 11896: 	    return $env{$cache_str}=$syval;
1.62      www      11897:         }
1.31      www      11898:     }
1.949     raeburn  11899:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11900:     return $env{$cache_str}='';
1.31      www      11901: }
                   11902: 
                   11903: # ---------------------------------------------------------- Return random seed
                   11904: 
1.32      www      11905: sub numval {
                   11906:     my $txt=shift;
                   11907:     $txt=~tr/A-J/0-9/;
                   11908:     $txt=~tr/a-j/0-9/;
                   11909:     $txt=~tr/K-T/0-9/;
                   11910:     $txt=~tr/k-t/0-9/;
                   11911:     $txt=~tr/U-Z/0-5/;
                   11912:     $txt=~tr/u-z/0-5/;
                   11913:     $txt=~s/\D//g;
1.564     albertel 11914:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      11915:     return int($txt);
1.368     albertel 11916: }
                   11917: 
1.484     albertel 11918: sub numval2 {
                   11919:     my $txt=shift;
                   11920:     $txt=~tr/A-J/0-9/;
                   11921:     $txt=~tr/a-j/0-9/;
                   11922:     $txt=~tr/K-T/0-9/;
                   11923:     $txt=~tr/k-t/0-9/;
                   11924:     $txt=~tr/U-Z/0-5/;
                   11925:     $txt=~tr/u-z/0-5/;
                   11926:     $txt=~s/\D//g;
                   11927:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11928:     my $total;
                   11929:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 11930:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 11931:     return int($total);
                   11932: }
                   11933: 
1.575     albertel 11934: sub numval3 {
                   11935:     use integer;
                   11936:     my $txt=shift;
                   11937:     $txt=~tr/A-J/0-9/;
                   11938:     $txt=~tr/a-j/0-9/;
                   11939:     $txt=~tr/K-T/0-9/;
                   11940:     $txt=~tr/k-t/0-9/;
                   11941:     $txt=~tr/U-Z/0-5/;
                   11942:     $txt=~tr/u-z/0-5/;
                   11943:     $txt=~s/\D//g;
                   11944:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11945:     my $total;
                   11946:     foreach my $val (@txts) { $total+=$val; }
                   11947:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11948:     return $total;
                   11949: }
                   11950: 
1.675     albertel 11951: sub digest {
                   11952:     my ($data)=@_;
                   11953:     my $digest=&Digest::MD5::md5($data);
                   11954:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11955:     my ($e,$f);
                   11956:     {
                   11957:         use integer;
                   11958:         $e=($a+$b);
                   11959:         $f=($c+$d);
                   11960:         if ($_64bit) {
                   11961:             $e=(($e<<32)>>32);
                   11962:             $f=(($f<<32)>>32);
                   11963:         }
                   11964:     }
                   11965:     if (wantarray) {
                   11966: 	return ($e,$f);
                   11967:     } else {
                   11968: 	my $g;
                   11969: 	{
                   11970: 	    use integer;
                   11971: 	    $g=($e+$f);
                   11972: 	    if ($_64bit) {
                   11973: 		$g=(($g<<32)>>32);
                   11974: 	    }
                   11975: 	}
                   11976: 	return $g;
                   11977:     }
                   11978: }
                   11979: 
1.368     albertel 11980: sub latest_rnd_algorithm_id {
1.675     albertel 11981:     return '64bit5';
1.366     albertel 11982: }
1.32      www      11983: 
1.503     albertel 11984: sub get_rand_alg {
                   11985:     my ($courseid)=@_;
1.790     albertel 11986:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 11987:     if ($courseid) {
1.620     albertel 11988: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 11989:     }
                   11990:     return &latest_rnd_algorithm_id();
                   11991: }
                   11992: 
1.562     albertel 11993: sub validCODE {
                   11994:     my ($CODE)=@_;
                   11995:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   11996:     return 0;
                   11997: }
                   11998: 
1.491     albertel 11999: sub getCODE {
1.620     albertel 12000:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12001:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12002: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12003: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12004: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12005:     }
                   12006:     return undef;
                   12007: }
1.1133    foxr     12008: #
                   12009: #  Determines the random seed for a specific context:
                   12010: #
                   12011: # parameters:
                   12012: #   symb      - in course context the symb for the seed.
                   12013: #   course_id - The course id of the form domain_coursenum.
                   12014: #   domain    - Domain for the user.
                   12015: #   course    - Course for the user.
                   12016: #   cenv      - environment of the course.
                   12017: #
                   12018: # NOTE:
                   12019: #   All parameters are picked out of the environment if missing
                   12020: #   or not defined.
                   12021: #   If a symb cannot be determined the current time is used instead.
                   12022: #
                   12023: #  For a given well defined symb, courside, domain, username,
                   12024: #  and course environment, the seed is reproducible.
                   12025: #
1.31      www      12026: sub rndseed {
1.1133    foxr     12027:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12028:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12029:     if (!defined($symb)) {
1.366     albertel 12030: 	unless ($symb=$wsymb) { return time; }
                   12031:     }
1.1146    foxr     12032:     if (!defined $courseid) { 
                   12033: 	$courseid=$wcourseid; 
                   12034:     }
                   12035:     if (!defined $domain) { $domain=$wdomain; }
                   12036:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12037: 
                   12038:     my $which;
                   12039:     if (defined($cenv->{'rndseed'})) {
                   12040: 	$which = $cenv->{'rndseed'};
                   12041:     } else {
                   12042: 	$which =&get_rand_alg($courseid);
                   12043:     }
1.491     albertel 12044:     if (defined(&getCODE())) {
1.1133    foxr     12045: 
1.675     albertel 12046: 	if ($which eq '64bit5') {
                   12047: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12048: 	} elsif ($which eq '64bit4') {
1.575     albertel 12049: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12050: 	} else {
                   12051: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12052: 	}
1.675     albertel 12053:     } elsif ($which eq '64bit5') {
                   12054: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12055:     } elsif ($which eq '64bit4') {
                   12056: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12057:     } elsif ($which eq '64bit3') {
                   12058: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12059:     } elsif ($which eq '64bit2') {
                   12060: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12061:     } elsif ($which eq '64bit') {
                   12062: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12063:     }
                   12064:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12065: }
                   12066: 
                   12067: sub rndseed_32bit {
                   12068:     my ($symb,$courseid,$domain,$username)=@_;
                   12069:     {
                   12070: 	use integer;
                   12071: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12072: 	my $symbseed=numval($symb) << 22;
                   12073: 	my $namechck=unpack("%32C*",$username) << 17;
                   12074: 	my $nameseed=numval($username) << 12;
                   12075: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12076: 	my $courseseed=unpack("%32C*",$courseid);
                   12077: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12078: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12079: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12080: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12081: 	return $num;
                   12082:     }
                   12083: }
                   12084: 
                   12085: sub rndseed_64bit {
                   12086:     my ($symb,$courseid,$domain,$username)=@_;
                   12087:     {
                   12088: 	use integer;
                   12089: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12090: 	my $symbseed=numval($symb) << 10;
                   12091: 	my $namechck=unpack("%32S*",$username);
                   12092: 	
                   12093: 	my $nameseed=numval($username) << 21;
                   12094: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12095: 	my $courseseed=unpack("%32S*",$courseid);
                   12096: 	
                   12097: 	my $num1=$symbchck+$symbseed+$namechck;
                   12098: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12099: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12100: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12101: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12102: 	return "$num1,$num2";
1.155     albertel 12103:     }
1.366     albertel 12104: }
                   12105: 
1.443     albertel 12106: sub rndseed_64bit2 {
                   12107:     my ($symb,$courseid,$domain,$username)=@_;
                   12108:     {
                   12109: 	use integer;
                   12110: 	# strings need to be an even # of cahracters long, it it is odd the
                   12111:         # last characters gets thrown away
                   12112: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12113: 	my $symbseed=numval($symb) << 10;
                   12114: 	my $namechck=unpack("%32S*",$username.' ');
                   12115: 	
                   12116: 	my $nameseed=numval($username) << 21;
1.501     albertel 12117: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12118: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12119: 	
                   12120: 	my $num1=$symbchck+$symbseed+$namechck;
                   12121: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12122: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12123: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12124: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12125: 	return "$num1,$num2";
                   12126:     }
                   12127: }
                   12128: 
                   12129: sub rndseed_64bit3 {
                   12130:     my ($symb,$courseid,$domain,$username)=@_;
                   12131:     {
                   12132: 	use integer;
                   12133: 	# strings need to be an even # of cahracters long, it it is odd the
                   12134:         # last characters gets thrown away
                   12135: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12136: 	my $symbseed=numval2($symb) << 10;
                   12137: 	my $namechck=unpack("%32S*",$username.' ');
                   12138: 	
                   12139: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12140: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12141: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12142: 	
                   12143: 	my $num1=$symbchck+$symbseed+$namechck;
                   12144: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12145: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12146: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12147: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12148: 	
1.503     albertel 12149: 	return "$num1:$num2";
1.443     albertel 12150:     }
                   12151: }
                   12152: 
1.575     albertel 12153: sub rndseed_64bit4 {
                   12154:     my ($symb,$courseid,$domain,$username)=@_;
                   12155:     {
                   12156: 	use integer;
                   12157: 	# strings need to be an even # of cahracters long, it it is odd the
                   12158:         # last characters gets thrown away
                   12159: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12160: 	my $symbseed=numval3($symb) << 10;
                   12161: 	my $namechck=unpack("%32S*",$username.' ');
                   12162: 	
                   12163: 	my $nameseed=numval3($username) << 21;
                   12164: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12165: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12166: 	
                   12167: 	my $num1=$symbchck+$symbseed+$namechck;
                   12168: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12169: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12170: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12171: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12172: 	
1.575     albertel 12173: 	return "$num1:$num2";
                   12174:     }
                   12175: }
                   12176: 
1.675     albertel 12177: sub rndseed_64bit5 {
                   12178:     my ($symb,$courseid,$domain,$username)=@_;
                   12179:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12180:     return "$num1:$num2";
                   12181: }
                   12182: 
1.366     albertel 12183: sub rndseed_CODE_64bit {
                   12184:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12185:     {
1.366     albertel 12186: 	use integer;
1.443     albertel 12187: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12188: 	my $symbseed=numval2($symb);
1.491     albertel 12189: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12190: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12191: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12192: 	my $num1=$symbseed+$CODEchck;
                   12193: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12194: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12195: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12196: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12197: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12198: 	return "$num1:$num2";
1.366     albertel 12199:     }
                   12200: }
                   12201: 
1.575     albertel 12202: sub rndseed_CODE_64bit4 {
                   12203:     my ($symb,$courseid,$domain,$username)=@_;
                   12204:     {
                   12205: 	use integer;
                   12206: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12207: 	my $symbseed=numval3($symb);
                   12208: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12209: 	my $CODEseed=numval3(&getCODE());
                   12210: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12211: 	my $num1=$symbseed+$CODEchck;
                   12212: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12213: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12214: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12215: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12216: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12217: 	return "$num1:$num2";
                   12218:     }
                   12219: }
                   12220: 
1.675     albertel 12221: sub rndseed_CODE_64bit5 {
                   12222:     my ($symb,$courseid,$domain,$username)=@_;
                   12223:     my $code = &getCODE();
                   12224:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12225:     return "$num1:$num2";
                   12226: }
                   12227: 
1.366     albertel 12228: sub setup_random_from_rndseed {
                   12229:     my ($rndseed)=@_;
1.503     albertel 12230:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  12231:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12232:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12233:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12234:         } else {
                   12235:             &Math::Random::random_set_seed($num1,$num2);
                   12236:         }
1.366     albertel 12237:     } else {
                   12238: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12239:     }
1.36      albertel 12240: }
                   12241: 
1.474     albertel 12242: sub latest_receipt_algorithm_id {
1.835     albertel 12243:     return 'receipt3';
1.474     albertel 12244: }
                   12245: 
1.480     www      12246: sub recunique {
                   12247:     my $fucourseid=shift;
                   12248:     my $unique;
1.835     albertel 12249:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12250: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12251: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12252:     } else {
                   12253: 	$unique=$perlvar{'lonReceipt'};
                   12254:     }
                   12255:     return unpack("%32C*",$unique);
                   12256: }
                   12257: 
                   12258: sub recprefix {
                   12259:     my $fucourseid=shift;
                   12260:     my $prefix;
1.835     albertel 12261:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12262: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12263: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12264:     } else {
                   12265: 	$prefix=$perlvar{'lonHostID'};
                   12266:     }
                   12267:     return unpack("%32C*",$prefix);
                   12268: }
                   12269: 
1.76      www      12270: sub ireceipt {
1.474     albertel 12271:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12272: 
                   12273:     my $return =&recprefix($fucourseid).'-';
                   12274: 
                   12275:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12276: 	$env{'request.state'} eq 'construct') {
                   12277: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12278: 	return $return;
                   12279:     }
                   12280: 
1.76      www      12281:     my $cuname=unpack("%32C*",$funame);
                   12282:     my $cudom=unpack("%32C*",$fudom);
                   12283:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12284:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12285:     my $cunique=&recunique($fucourseid);
1.474     albertel 12286:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12287:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12288: 
1.790     albertel 12289: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12290: 			       
                   12291: 	$return.= ($cunique%$cuname+
                   12292: 		   $cunique%$cudom+
                   12293: 		   $cusymb%$cuname+
                   12294: 		   $cusymb%$cudom+
                   12295: 		   $cucourseid%$cuname+
                   12296: 		   $cucourseid%$cudom+
                   12297: 		   $cpart%$cuname+
                   12298: 		   $cpart%$cudom);
                   12299:     } else {
                   12300: 	$return.= ($cunique%$cuname+
                   12301: 		   $cunique%$cudom+
                   12302: 		   $cusymb%$cuname+
                   12303: 		   $cusymb%$cudom+
                   12304: 		   $cucourseid%$cuname+
                   12305: 		   $cucourseid%$cudom);
                   12306:     }
                   12307:     return $return;
1.76      www      12308: }
                   12309: 
                   12310: sub receipt {
1.474     albertel 12311:     my ($part)=@_;
1.790     albertel 12312:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12313:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12314: }
1.260     ng       12315: 
1.790     albertel 12316: sub whichuser {
                   12317:     my ($passedsymb)=@_;
                   12318:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12319:     if (defined($env{'form.grade_symb'})) {
                   12320: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12321: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12322: 	if (!$allowed &&
                   12323: 	    exists($env{'request.course.sec'}) &&
                   12324: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12325: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12326: 			      '/'.$env{'request.course.sec'});
                   12327: 	}
                   12328: 	if ($allowed) {
                   12329: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12330: 	    $courseid=$tmp_courseid;
                   12331: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12332: 	    ($name)=&get_env_multiple('form.grade_username');
                   12333: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12334: 	}
                   12335:     }
                   12336:     if (!$passedsymb) {
                   12337: 	$symb=&symbread();
                   12338:     } else {
                   12339: 	$symb=$passedsymb;
                   12340:     }
                   12341:     $courseid=$env{'request.course.id'};
                   12342:     $domain=$env{'user.domain'};
                   12343:     $name=$env{'user.name'};
                   12344:     if ($name eq 'public' && $domain eq 'public') {
                   12345: 	if (!defined($env{'form.username'})) {
                   12346: 	    $env{'form.username'}.=time.rand(10000000);
                   12347: 	}
                   12348: 	$name.=$env{'form.username'};
                   12349:     }
                   12350:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12351: 
                   12352: }
                   12353: 
1.36      albertel 12354: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12355: # returns either the contents of the file or 
                   12356: # -1 if the file doesn't exist
1.481     raeburn  12357: #
                   12358: # if the target is a file that was uploaded via DOCS, 
                   12359: # a check will be made to see if a current copy exists on the local server,
                   12360: # if it does this will be served, otherwise a copy will be retrieved from
                   12361: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12362: # the local server.   
1.472     albertel 12363: 
1.36      albertel 12364: sub getfile {
1.538     albertel 12365:     my ($file) = @_;
1.609     banghart 12366:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12367:     &repcopy($file);
                   12368:     return &readfile($file);
                   12369: }
                   12370: 
                   12371: sub repcopy_userfile {
                   12372:     my ($file)=@_;
1.1142    raeburn  12373:     my $londocroot = $perlvar{'lonDocRoot'};
                   12374:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12375:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12376:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12377: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12378:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12379:     if (-e "$file") {
1.828     www      12380: # we already have a local copy, check it out
1.538     albertel 12381: 	my @fileinfo = stat($file);
1.828     www      12382: 	my $rtncode;
                   12383: 	my $info;
1.538     albertel 12384: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12385: 	if ($lwpresp ne 'ok') {
1.828     www      12386: # there is no such file anymore, even though we had a local copy
1.482     albertel 12387: 	    if ($rtncode eq '404') {
1.538     albertel 12388: 		unlink($file);
1.482     albertel 12389: 	    }
                   12390: 	    return -1;
                   12391: 	}
                   12392: 	if ($info < $fileinfo[9]) {
1.828     www      12393: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12394: 	    return 'ok';
1.828     www      12395: 	} else {
                   12396: # the file is outdated, get rid of it
                   12397: 	    unlink($file);
1.482     albertel 12398: 	}
1.828     www      12399:     }
                   12400: # one way or the other, at this point, we don't have the file
                   12401: # construct the correct path for the file
                   12402:     my @parts = ($cdom,$cnum); 
                   12403:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12404: 	push @parts, split(/\//,$1);
                   12405:     }
                   12406:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   12407:     foreach my $part (@parts) {
                   12408: 	$path .= '/'.$part;
                   12409: 	if (!-e $path) {
                   12410: 	    mkdir($path,0770);
1.482     albertel 12411: 	}
                   12412:     }
1.828     www      12413: # now the path exists for sure
                   12414: # get a user agent
                   12415:     my $ua=new LWP::UserAgent;
                   12416:     my $transferfile=$file.'.in.transfer';
                   12417: # FIXME: this should flock
                   12418:     if (-e $transferfile) { return 'ok'; }
                   12419:     my $request;
                   12420:     $uri=~s/^\///;
1.980     raeburn  12421:     my $homeserver = &homeserver($cnum,$cdom);
                   12422:     my $protocol = $protocol{$homeserver};
                   12423:     $protocol = 'http' if ($protocol ne 'https');
                   12424:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      12425:     my $response=$ua->request($request,$transferfile);
                   12426: # did it work?
                   12427:     if ($response->is_error()) {
                   12428: 	unlink($transferfile);
                   12429: 	&logthis("Userfile repcopy failed for $uri");
                   12430: 	return -1;
                   12431:     }
                   12432: # worked, rename the transfer file
                   12433:     rename($transferfile,$file);
1.607     raeburn  12434:     return 'ok';
1.481     raeburn  12435: }
                   12436: 
1.517     albertel 12437: sub tokenwrapper {
                   12438:     my $uri=shift;
1.980     raeburn  12439:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 12440:     $uri=~s|^/||;
1.620     albertel 12441:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 12442:     my $token=$1;
1.552     albertel 12443:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   12444:     if ($udom && $uname && $file) {
                   12445: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  12446:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  12447:         my $homeserver = &homeserver($uname,$udom);
                   12448:         my $protocol = $protocol{$homeserver};
                   12449:         $protocol = 'http' if ($protocol ne 'https');
                   12450:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 12451:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   12452:                                '&tokenissued='.$perlvar{'lonHostID'};
                   12453:     } else {
                   12454:         return '/adm/notfound.html';
                   12455:     }
                   12456: }
                   12457: 
1.828     www      12458: # call with reqtype HEAD: get last modification time
                   12459: # call with reqtype GET: get the file contents
                   12460: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12461: #
1.481     raeburn  12462: sub getuploaded {
                   12463:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12464:     $uri=~s/^\///;
1.980     raeburn  12465:     my $homeserver = &homeserver($cnum,$cdom);
                   12466:     my $protocol = $protocol{$homeserver};
                   12467:     $protocol = 'http' if ($protocol ne 'https');
                   12468:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12469:     my $ua=new LWP::UserAgent;
                   12470:     my $request=new HTTP::Request($reqtype,$uri);
                   12471:     my $response=$ua->request($request);
                   12472:     $$rtncode = $response->code;
1.482     albertel 12473:     if (! $response->is_success()) {
                   12474: 	return 'failed';
                   12475:     }      
                   12476:     if ($reqtype eq 'HEAD') {
1.486     www      12477: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12478:     } elsif ($reqtype eq 'GET') {
                   12479: 	$$info = $response->content;
1.472     albertel 12480:     }
1.482     albertel 12481:     return 'ok';
1.36      albertel 12482: }
                   12483: 
1.481     raeburn  12484: sub readfile {
                   12485:     my $file = shift;
                   12486:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12487:     my $fh;
                   12488:     open($fh,"<$file");
                   12489:     my $a='';
1.800     albertel 12490:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12491:     return $a;
                   12492: }
                   12493: 
1.36      albertel 12494: sub filelocation {
1.590     banghart 12495:     my ($dir,$file) = @_;
                   12496:     my $location;
                   12497:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12498: 
                   12499:     if ($file =~ m-^/adm/-) {
                   12500: 	$file=~s-^/adm/wrapper/-/-;
                   12501: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12502:     }
1.882     albertel 12503: 
1.1139    www      12504:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12505:         $location = $file;
1.609     banghart 12506:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12507:         my ($udom,$uname,$filename)=
1.811     albertel 12508:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12509:         my $home=&homeserver($uname,$udom);
                   12510:         my $is_me=0;
                   12511:         my @ids=&current_machine_ids();
                   12512:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12513:         if ($is_me) {
1.1117    foxr     12514:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12515:         } else {
                   12516:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12517:   	      $udom.'/'.$uname.'/'.$filename;
                   12518:         }
1.882     albertel 12519:     } elsif ($file =~ m-^/adm/-) {
                   12520: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12521:     } else {
                   12522:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12523:         $file=~s:^/(res|priv)/:/:;
                   12524:         my $space=$1;
1.590     banghart 12525:         if ( !( $file =~ m:^/:) ) {
                   12526:             $location = $dir. '/'.$file;
                   12527:         } else {
1.1142    raeburn  12528:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12529:         }
1.59      albertel 12530:     }
1.590     banghart 12531:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12532:     while ($location=~m{/\.\./}) {
                   12533: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12534: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   12535: 	} else {
                   12536: 	    $location=~ s{/\.\./}{/}g;
                   12537: 	}
                   12538:     } #remove dir/..
1.590     banghart 12539:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   12540:     return $location;
1.46      www      12541: }
1.36      albertel 12542: 
1.46      www      12543: sub hreflocation {
                   12544:     my ($dir,$file)=@_;
1.980     raeburn  12545:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 12546: 	$file=filelocation($dir,$file);
1.700     albertel 12547:     } elsif ($file=~m-^/adm/-) {
                   12548: 	$file=~s-^/adm/wrapper/-/-;
                   12549: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 12550:     }
                   12551:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   12552: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   12553:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  12554: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   12555: 	        {/uploaded/$1/$2/}x;
1.46      www      12556:     }
1.913     albertel 12557:     if ($file=~ m{^/userfiles/}) {
                   12558: 	$file =~ s{^/userfiles/}{/uploaded/};
                   12559:     }
1.462     albertel 12560:     return $file;
1.465     albertel 12561: }
                   12562: 
1.1139    www      12563: 
                   12564: 
                   12565: 
                   12566: 
1.465     albertel 12567: sub current_machine_domains {
1.853     albertel 12568:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   12569: }
                   12570: 
                   12571: sub machine_domains {
                   12572:     my ($hostname) = @_;
1.465     albertel 12573:     my @domains;
1.838     albertel 12574:     my %hostname = &all_hostnames();
1.465     albertel 12575:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  12576: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 12577: 	if ($hostname eq $name) {
1.844     albertel 12578: 	    push(@domains,&host_domain($id));
1.465     albertel 12579: 	}
                   12580:     }
                   12581:     return @domains;
                   12582: }
                   12583: 
                   12584: sub current_machine_ids {
1.853     albertel 12585:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   12586: }
                   12587: 
                   12588: sub machine_ids {
                   12589:     my ($hostname) = @_;
                   12590:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 12591:     my @ids;
1.888     albertel 12592:     my %name_to_host = &all_names();
1.889     albertel 12593:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   12594: 	return @{ $name_to_host{$hostname} };
                   12595:     }
                   12596:     return;
1.31      www      12597: }
                   12598: 
1.824     raeburn  12599: sub additional_machine_domains {
                   12600:     my @domains;
                   12601:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   12602:     while( my $line = <$fh>) {
                   12603:         $line =~ s/\s//g;
                   12604:         push(@domains,$line);
                   12605:     }
                   12606:     return @domains;
                   12607: }
                   12608: 
                   12609: sub default_login_domain {
                   12610:     my $domain = $perlvar{'lonDefDomain'};
                   12611:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   12612:     foreach my $posdom (&current_machine_domains(),
                   12613:                         &additional_machine_domains()) {
                   12614:         if (lc($posdom) eq lc($testdomain)) {
                   12615:             $domain=$posdom;
                   12616:             last;
                   12617:         }
                   12618:     }
                   12619:     return $domain;
                   12620: }
                   12621: 
1.31      www      12622: # ------------------------------------------------------------- Declutters URLs
                   12623: 
                   12624: sub declutter {
                   12625:     my $thisfn=shift;
1.569     albertel 12626:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  12627:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   12628:         $thisfn=~s{^/home/httpd/html}{};
                   12629:     }
1.31      www      12630:     $thisfn=~s/^\///;
1.697     albertel 12631:     $thisfn=~s|^adm/wrapper/||;
                   12632:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12633:     $thisfn=~s/^res\///;
1.1172    bisitz   12634:     $thisfn=~s/^priv\///;
1.1032    raeburn  12635:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12636:         $thisfn=~s/\?.+$//;
                   12637:     }
1.268     www      12638:     return $thisfn;
                   12639: }
                   12640: 
                   12641: # ------------------------------------------------------------- Clutter up URLs
                   12642: 
                   12643: sub clutter {
                   12644:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12645:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 12646: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      12647:        $thisfn='/res'.$thisfn; 
                   12648:     }
1.1031    raeburn  12649:     if ($thisfn !~m|^/adm|) {
                   12650: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 12651: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 12652: 	} else {
                   12653: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   12654: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 12655: 	    if ($embstyle eq 'ssi'
                   12656: 		|| ($embstyle eq 'hdn')
                   12657: 		|| ($embstyle eq 'rat')
                   12658: 		|| ($embstyle eq 'prv')
                   12659: 		|| ($embstyle eq 'ign')) {
                   12660: 		#do nothing with these
                   12661: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 12662: 		|| ($embstyle eq 'emb')
                   12663: 		|| ($embstyle eq 'wrp')) {
                   12664: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 12665: 	    } elsif ($embstyle eq 'unk'
                   12666: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 12667: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 12668: 	    } else {
1.718     www      12669: #		&logthis("Got a blank emb style");
1.695     albertel 12670: 	    }
1.694     albertel 12671: 	}
1.1298    raeburn  12672:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/exttools?$}) {
                   12673:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 12674:     }
1.31      www      12675:     return $thisfn;
1.12      www      12676: }
                   12677: 
1.787     albertel 12678: sub clutter_with_no_wrapper {
                   12679:     my $uri = &clutter(shift);
                   12680:     if ($uri =~ m-^/adm/-) {
                   12681: 	$uri =~ s-^/adm/wrapper/-/-;
                   12682: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   12683:     }
                   12684:     return $uri;
                   12685: }
                   12686: 
1.557     albertel 12687: sub freeze_escape {
                   12688:     my ($value)=@_;
                   12689:     if (ref($value)) {
                   12690: 	$value=&nfreeze($value);
                   12691: 	return '__FROZEN__'.&escape($value);
                   12692:     }
                   12693:     return &escape($value);
                   12694: }
                   12695: 
1.11      www      12696: 
1.557     albertel 12697: sub thaw_unescape {
                   12698:     my ($value)=@_;
                   12699:     if ($value =~ /^__FROZEN__/) {
                   12700: 	substr($value,0,10,undef);
                   12701: 	$value=&unescape($value);
                   12702: 	return &thaw($value);
                   12703:     }
                   12704:     return &unescape($value);
                   12705: }
                   12706: 
1.436     albertel 12707: sub correct_line_ends {
                   12708:     my ($result)=@_;
                   12709:     $$result =~s/\r\n/\n/mg;
                   12710:     $$result =~s/\r/\n/mg;
1.415     albertel 12711: }
1.1       albertel 12712: # ================================================================ Main Program
                   12713: 
1.184     www      12714: sub goodbye {
1.204     albertel 12715:    &logthis("Starting Shut down");
1.443     albertel 12716: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 12717:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 12718: #converted
1.599     albertel 12719: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 12720:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   12721: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   12722: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 12723: #1.1 only
1.870     albertel 12724: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   12725: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   12726: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   12727: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   12728:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 12729:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   12730:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      12731:    &flushcourselogs();
                   12732:    &logthis("Shutting down");
                   12733: }
                   12734: 
1.852     albertel 12735: sub get_dns {
1.1210    raeburn  12736:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 12737:     if (!$ignore_cache) {
                   12738: 	my ($content,$cached)=
                   12739: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   12740: 	if ($cached) {
1.1210    raeburn  12741: 	    &$func($content,$hashref);
1.869     albertel 12742: 	    return;
                   12743: 	}
                   12744:     }
                   12745: 
                   12746:     my %alldns;
1.852     albertel 12747:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12748:     foreach my $dns (<$config>) {
                   12749: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  12750:         my $line = $1;
                   12751:         my ($host,$protocol) = split(/:/,$line);
                   12752:         if ($protocol ne 'https') {
                   12753:             $protocol = 'http';
                   12754:         }
                   12755: 	$alldns{$host} = $protocol;
1.869     albertel 12756:     }
                   12757:     while (%alldns) {
1.1263    raeburn  12758: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 12759: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  12760:         $ua->timeout(30);
1.979     raeburn  12761: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 12762: 	my $response=$ua->request($request);
1.979     raeburn  12763:         delete($alldns{$dns});
1.852     albertel 12764: 	next if ($response->is_error());
                   12765: 	my @content = split("\n",$response->content);
1.1210    raeburn  12766: 	unless ($nocache) {
1.1219    raeburn  12767: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210    raeburn  12768: 	}
                   12769: 	&$func(\@content,$hashref);
1.869     albertel 12770: 	return;
1.852     albertel 12771:     }
                   12772:     close($config);
1.871     albertel 12773:     my $which = (split('/',$url))[3];
                   12774:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   12775:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 12776:     my @content = <$config>;
1.1210    raeburn  12777:     &$func(\@content,$hashref);
                   12778:     return;
                   12779: }
                   12780: 
                   12781: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  12782: sub parse_dns_checksums_tab {
1.1210    raeburn  12783:     my ($lines,$hashref) = @_;
1.1264    raeburn  12784:     my $lonhost = $perlvar{'lonHostID'};
                   12785:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  12786:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  12787:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   12788:     my $webconfdir = '/etc/httpd/conf';
                   12789:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   12790:         $webconfdir = '/etc/apache2';
                   12791:     } elsif ($distro =~ /^sles(\d+)$/) {
                   12792:         if ($1 >= 10) {
                   12793:             $webconfdir = '/etc/apache2';
                   12794:         }
                   12795:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   12796:         if ($1 >= 10.0) {
                   12797:             $webconfdir = '/etc/apache2';
                   12798:         }
                   12799:     }
1.1210    raeburn  12800:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12801:     my (%chksum,%revnum);
                   12802:     if (ref($lines) eq 'ARRAY') {
                   12803:         chomp(@{$lines});
1.1238    raeburn  12804:         my $version = shift(@{$lines});
                   12805:         if ($version eq $release) {  
1.1210    raeburn  12806:             foreach my $line (@{$lines}) {
1.1238    raeburn  12807:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  12808:                 if ($file =~ m{^/etc/httpd/conf}) {
                   12809:                     if ($webconfdir eq '/etc/apache2') {
                   12810:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   12811:                     }
                   12812:                 }
1.1238    raeburn  12813:                 $chksum{$file} = $shasum;
                   12814:                 $revnum{$file} = $version;
1.1210    raeburn  12815:             }
                   12816:             if (ref($hashref) eq 'HASH') {
                   12817:                 %{$hashref} = (
                   12818:                                 sums     => \%chksum,
                   12819:                                 versions => \%revnum,
                   12820:                               );
                   12821:             }
                   12822:         }
                   12823:     }
1.869     albertel 12824:     return;
1.852     albertel 12825: }
1.1210    raeburn  12826: 
                   12827: sub fetch_dns_checksums {
1.1238    raeburn  12828:     my %checksums;
                   12829:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  12830:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  12831:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12832:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  12833:              \%checksums);
1.1210    raeburn  12834:     return \%checksums;
                   12835: }
                   12836: 
1.327     albertel 12837: # ------------------------------------------------------------ Read domain file
                   12838: {
1.852     albertel 12839:     my $loaded;
1.846     albertel 12840:     my %domain;
                   12841: 
1.852     albertel 12842:     sub parse_domain_tab {
                   12843: 	my ($lines) = @_;
                   12844: 	foreach my $line (@$lines) {
                   12845: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      12846: 
1.846     albertel 12847: 	    chomp($line);
1.852     albertel 12848: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 12849: 	    my %this_domain;
                   12850: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   12851: 			       'lang_def', 'city', 'longi', 'lati',
                   12852: 			       'primary') {
                   12853: 		$this_domain{$field} = shift(@elements);
                   12854: 	    }
                   12855: 	    $domain{$name} = \%this_domain;
1.852     albertel 12856: 	}
                   12857:     }
1.864     albertel 12858: 
                   12859:     sub reset_domain_info {
                   12860: 	undef($loaded);
                   12861: 	undef(%domain);
                   12862:     }
                   12863: 
1.852     albertel 12864:     sub load_domain_tab {
1.1293    raeburn  12865: 	my ($ignore_cache,$nocache) = @_;
                   12866: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 12867: 	my $fh;
                   12868: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   12869: 	    my @lines = <$fh>;
                   12870: 	    &parse_domain_tab(\@lines);
1.448     albertel 12871: 	}
1.852     albertel 12872: 	close($fh);
                   12873: 	$loaded = 1;
1.327     albertel 12874:     }
1.846     albertel 12875: 
                   12876:     sub domain {
1.852     albertel 12877: 	&load_domain_tab() if (!$loaded);
                   12878: 
1.846     albertel 12879: 	my ($name,$what) = @_;
                   12880: 	return if ( !exists($domain{$name}) );
                   12881: 
                   12882: 	if (!$what) {
                   12883: 	    return $domain{$name}{'description'};
                   12884: 	}
                   12885: 	return $domain{$name}{$what};
                   12886:     }
1.974     raeburn  12887: 
                   12888:     sub domain_info {
                   12889:         &load_domain_tab() if (!$loaded);
                   12890:         return %domain;
                   12891:     }
                   12892: 
1.327     albertel 12893: }
                   12894: 
                   12895: 
1.1       albertel 12896: # ------------------------------------------------------------- Read hosts file
                   12897: {
1.838     albertel 12898:     my %hostname;
1.844     albertel 12899:     my %hostdom;
1.845     albertel 12900:     my %libserv;
1.852     albertel 12901:     my $loaded;
1.888     albertel 12902:     my %name_to_host;
1.1074    raeburn  12903:     my %internetdom;
1.1107    raeburn  12904:     my %LC_dns_serv;
1.852     albertel 12905: 
                   12906:     sub parse_hosts_tab {
                   12907: 	my ($file) = @_;
                   12908: 	foreach my $configline (@$file) {
                   12909: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  12910:             chomp($configline);
                   12911: 	    if ($configline =~ /^\^/) {
                   12912:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   12913:                     $LC_dns_serv{$1} = 1;
                   12914:                 }
                   12915:                 next;
                   12916:             }
1.1074    raeburn  12917: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 12918: 	    $name=~s/\s//g;
                   12919: 	    if ($id && $domain && $role && $name) {
                   12920: 		$hostname{$id}=$name;
1.888     albertel 12921: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 12922: 		$hostdom{$id}=$domain;
                   12923: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  12924:                 if (defined($protocol)) {
                   12925:                     if ($protocol eq 'https') {
                   12926:                         $protocol{$id} = $protocol;
                   12927:                     } else {
                   12928:                         $protocol{$id} = 'http'; 
                   12929:                     }
1.968     raeburn  12930:                 } else {
1.969     raeburn  12931:                     $protocol{$id} = 'http';
1.968     raeburn  12932:                 }
1.1074    raeburn  12933:                 if (defined($intdom)) {
                   12934:                     $internetdom{$id} = $intdom;
                   12935:                 }
1.852     albertel 12936: 	    }
                   12937: 	}
                   12938:     }
1.864     albertel 12939:     
                   12940:     sub reset_hosts_info {
1.897     albertel 12941: 	&purge_remembered();
1.864     albertel 12942: 	&reset_domain_info();
                   12943: 	&reset_hosts_ip_info();
1.892     albertel 12944: 	undef(%name_to_host);
1.864     albertel 12945: 	undef(%hostname);
                   12946: 	undef(%hostdom);
                   12947: 	undef(%libserv);
                   12948: 	undef($loaded);
                   12949:     }
1.1       albertel 12950: 
1.852     albertel 12951:     sub load_hosts_tab {
1.1293    raeburn  12952: 	my ($ignore_cache,$nocache) = @_;
                   12953: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852     albertel 12954: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12955: 	my @config = <$config>;
                   12956: 	&parse_hosts_tab(\@config);
                   12957: 	close($config);
                   12958: 	$loaded=1;
1.1       albertel 12959:     }
1.852     albertel 12960: 
1.838     albertel 12961:     sub hostname {
1.852     albertel 12962: 	&load_hosts_tab() if (!$loaded);
                   12963: 
1.838     albertel 12964: 	my ($lonid) = @_;
                   12965: 	return $hostname{$lonid};
                   12966:     }
1.845     albertel 12967: 
1.838     albertel 12968:     sub all_hostnames {
1.852     albertel 12969: 	&load_hosts_tab() if (!$loaded);
                   12970: 
1.838     albertel 12971: 	return %hostname;
                   12972:     }
1.845     albertel 12973: 
1.888     albertel 12974:     sub all_names {
1.1293    raeburn  12975:         my ($ignore_cache,$nocache) = @_;
                   12976: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 12977: 
                   12978: 	return %name_to_host;
                   12979:     }
                   12980: 
1.974     raeburn  12981:     sub all_host_domain {
                   12982:         &load_hosts_tab() if (!$loaded);
                   12983:         return %hostdom;
                   12984:     }
                   12985: 
1.845     albertel 12986:     sub is_library {
1.852     albertel 12987: 	&load_hosts_tab() if (!$loaded);
                   12988: 
1.845     albertel 12989: 	return exists($libserv{$_[0]});
                   12990:     }
                   12991: 
                   12992:     sub all_library {
1.852     albertel 12993: 	&load_hosts_tab() if (!$loaded);
                   12994: 
1.845     albertel 12995: 	return %libserv;
                   12996:     }
                   12997: 
1.1062    droeschl 12998:     sub unique_library {
                   12999: 	#2x reverse removes all hostnames that appear more than once
                   13000:         my %unique = reverse &all_library();
                   13001:         return reverse %unique;
                   13002:     }
                   13003: 
1.841     albertel 13004:     sub get_servers {
1.852     albertel 13005: 	&load_hosts_tab() if (!$loaded);
                   13006: 
1.841     albertel 13007: 	my ($domain,$type) = @_;
                   13008: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13009: 	                                          : %hostname;
                   13010: 	my %result;
1.842     albertel 13011: 	if (ref($domain) eq 'ARRAY') {
                   13012: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13013: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13014: 		    $result{$host} = $hostname;
                   13015: 		}
                   13016: 	    }
                   13017: 	} else {
                   13018: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13019: 		if ($hostdom{$host} eq $domain) {
                   13020: 		    $result{$host} = $hostname;
                   13021: 		}
1.841     albertel 13022: 	    }
                   13023: 	}
                   13024: 	return %result;
                   13025:     }
1.845     albertel 13026: 
1.1062    droeschl 13027:     sub get_unique_servers {
                   13028:         my %unique = reverse &get_servers(@_);
                   13029: 	return reverse %unique;
                   13030:     }
                   13031: 
1.844     albertel 13032:     sub host_domain {
1.852     albertel 13033: 	&load_hosts_tab() if (!$loaded);
                   13034: 
1.844     albertel 13035: 	my ($lonid) = @_;
                   13036: 	return $hostdom{$lonid};
                   13037:     }
                   13038: 
1.841     albertel 13039:     sub all_domains {
1.852     albertel 13040: 	&load_hosts_tab() if (!$loaded);
                   13041: 
1.841     albertel 13042: 	my %seen;
                   13043: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13044: 	return @uniq;
                   13045:     }
1.1074    raeburn  13046: 
                   13047:     sub internet_dom {
                   13048:         &load_hosts_tab() if (!$loaded);
                   13049: 
                   13050:         my ($lonid) = @_;
                   13051:         return $internetdom{$lonid};
                   13052:     }
1.1107    raeburn  13053: 
                   13054:     sub is_LC_dns {
                   13055:         &load_hosts_tab() if (!$loaded);
                   13056: 
                   13057:         my ($hostname) = @_;
                   13058:         return exists($LC_dns_serv{$hostname});
                   13059:     }
                   13060: 
1.1       albertel 13061: }
                   13062: 
1.847     albertel 13063: { 
                   13064:     my %iphost;
1.856     albertel 13065:     my %name_to_ip;
                   13066:     my %lonid_to_ip;
1.869     albertel 13067: 
1.847     albertel 13068:     sub get_hosts_from_ip {
                   13069: 	my ($ip) = @_;
                   13070: 	my %iphosts = &get_iphost();
                   13071: 	if (ref($iphosts{$ip})) {
                   13072: 	    return @{$iphosts{$ip}};
                   13073: 	}
                   13074: 	return;
1.839     albertel 13075:     }
1.864     albertel 13076:     
                   13077:     sub reset_hosts_ip_info {
                   13078: 	undef(%iphost);
                   13079: 	undef(%name_to_ip);
                   13080: 	undef(%lonid_to_ip);
                   13081:     }
1.856     albertel 13082: 
                   13083:     sub get_host_ip {
                   13084: 	my ($lonid) = @_;
                   13085: 	if (exists($lonid_to_ip{$lonid})) {
                   13086: 	    return $lonid_to_ip{$lonid};
                   13087: 	}
                   13088: 	my $name=&hostname($lonid);
                   13089:    	my $ip = gethostbyname($name);
                   13090: 	return if (!$ip || length($ip) ne 4);
                   13091: 	$ip=inet_ntoa($ip);
                   13092: 	$name_to_ip{$name}   = $ip;
                   13093: 	$lonid_to_ip{$lonid} = $ip;
                   13094: 	return $ip;
                   13095:     }
1.847     albertel 13096:     
                   13097:     sub get_iphost {
1.1293    raeburn  13098: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13099: 
1.869     albertel 13100: 	if (!$ignore_cache) {
                   13101: 	    if (%iphost) {
                   13102: 		return %iphost;
                   13103: 	    }
                   13104: 	    my ($ip_info,$cached)=
                   13105: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13106: 	    if ($cached) {
                   13107: 		%iphost      = %{$ip_info->[0]};
                   13108: 		%name_to_ip  = %{$ip_info->[1]};
                   13109: 		%lonid_to_ip = %{$ip_info->[2]};
                   13110: 		return %iphost;
                   13111: 	    }
                   13112: 	}
1.894     albertel 13113: 
                   13114: 	# get yesterday's info for fallback
                   13115: 	my %old_name_to_ip;
                   13116: 	my ($ip_info,$cached)=
                   13117: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13118: 	if ($cached) {
                   13119: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13120: 	}
                   13121: 
1.1293    raeburn  13122: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13123: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13124: 	    my $ip;
                   13125: 	    if (!exists($name_to_ip{$name})) {
                   13126: 		$ip = gethostbyname($name);
                   13127: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13128: 		    if (defined($old_name_to_ip{$name})) {
                   13129: 			$ip = $old_name_to_ip{$name};
                   13130: 			&logthis("Can't find $name defaulting to old $ip");
                   13131: 		    } else {
                   13132: 			&logthis("Name $name no IP found");
                   13133: 			next;
                   13134: 		    }
                   13135: 		} else {
                   13136: 		    $ip=inet_ntoa($ip);
1.847     albertel 13137: 		}
                   13138: 		$name_to_ip{$name} = $ip;
                   13139: 	    } else {
                   13140: 		$ip = $name_to_ip{$name};
1.653     albertel 13141: 	    }
1.888     albertel 13142: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13143: 		$lonid_to_ip{$id} = $ip;
                   13144: 	    }
                   13145: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13146: 	}
1.1293    raeburn  13147:         unless ($nocache) {
                   13148: 	    &do_cache_new('iphost','iphost',
                   13149: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13150: 		          48*60*60);
                   13151:         }
1.869     albertel 13152: 
1.847     albertel 13153: 	return %iphost;
1.598     albertel 13154:     }
                   13155: 
1.992     raeburn  13156:     #
                   13157:     #  Given a DNS returns the loncapa host name for that DNS 
                   13158:     # 
                   13159:     sub host_from_dns {
                   13160:         my ($dns) = @_;
                   13161:         my @hosts;
                   13162:         my $ip;
                   13163: 
1.993     raeburn  13164:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13165:             $ip = $name_to_ip{$dns};
                   13166:         }
                   13167:         if (!$ip) {
                   13168:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13169:             if (length($ip) == 4) { 
                   13170: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13171:             }
                   13172:         }
                   13173:         if ($ip) {
                   13174: 	    @hosts = get_hosts_from_ip($ip);
                   13175: 	    return $hosts[0];
                   13176:         }
                   13177:         return undef;
1.986     foxr     13178:     }
1.992     raeburn  13179: 
1.1074    raeburn  13180:     sub get_internet_names {
                   13181:         my ($lonid) = @_;
                   13182:         return if ($lonid eq '');
                   13183:         my ($idnref,$cached)=
                   13184:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13185:         if ($cached) {
                   13186:             return $idnref;
                   13187:         }
                   13188:         my $ip = &get_host_ip($lonid);
                   13189:         my @hosts = &get_hosts_from_ip($ip);
                   13190:         my %iphost = &get_iphost();
                   13191:         my (@idns,%seen);
                   13192:         foreach my $id (@hosts) {
                   13193:             my $dom = &host_domain($id);
                   13194:             my $prim_id = &domain($dom,'primary');
                   13195:             my $prim_ip = &get_host_ip($prim_id);
                   13196:             next if ($seen{$prim_ip});
                   13197:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13198:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13199:                     my $intdom = &internet_dom($id);
                   13200:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13201:                         push(@idns,$intdom);
                   13202:                     }
                   13203:                 }
                   13204:             }
                   13205:             $seen{$prim_ip} = 1;
                   13206:         }
1.1219    raeburn  13207:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13208:     }
                   13209: 
1.986     foxr     13210: }
                   13211: 
1.1079    raeburn  13212: sub all_loncaparevs {
1.1249    raeburn  13213:     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  13214: }
                   13215: 
1.1227    raeburn  13216: # ---------------------------------------------------------- Read loncaparev table
                   13217: {
                   13218:     sub load_loncaparevs { 
                   13219:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   13220:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   13221:                 while (my $configline=<$config>) {
                   13222:                     chomp($configline);
                   13223:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13224:                     $loncaparevs{$hostid}=$loncaparev;
                   13225:                 }
                   13226:                 close($config);
                   13227:             }
                   13228:         }
                   13229:     }
                   13230: }
                   13231: 
                   13232: # ---------------------------------------------------------- Read serverhostID table
                   13233: {
                   13234:     sub load_serverhomeIDs {
                   13235:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   13236:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   13237:                 while (my $configline=<$config>) {
                   13238:                     chomp($configline);
                   13239:                     my ($name,$id)=split(/:/,$configline);
                   13240:                     $serverhomeIDs{$name}=$id;
                   13241:                 }
                   13242:                 close($config);
                   13243:             }
                   13244:         }
                   13245:     }
                   13246: }
                   13247: 
                   13248: 
1.862     albertel 13249: BEGIN {
                   13250: 
                   13251: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13252:     unless ($readit) {
                   13253: {
                   13254:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13255:     %perlvar = (%perlvar,%{$configvars});
                   13256: }
                   13257: 
                   13258: 
1.1       albertel 13259: # ------------------------------------------------------ Read spare server file
                   13260: {
1.448     albertel 13261:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13262: 
                   13263:     while (my $configline=<$config>) {
                   13264:        chomp($configline);
1.284     matthew  13265:        if ($configline) {
1.784     albertel 13266: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13267: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13268: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13269:        }
                   13270:     }
1.448     albertel 13271:     close($config);
1.1       albertel 13272: }
1.11      www      13273: # ------------------------------------------------------------ Read permissions
                   13274: {
1.448     albertel 13275:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13276: 
                   13277:     while (my $configline=<$config>) {
1.448     albertel 13278: 	chomp($configline);
                   13279: 	if ($configline) {
                   13280: 	    my ($role,$perm)=split(/ /,$configline);
                   13281: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13282: 	}
1.11      www      13283:     }
1.448     albertel 13284:     close($config);
1.11      www      13285: }
                   13286: 
                   13287: # -------------------------------------------- Read plain texts for permissions
                   13288: {
1.448     albertel 13289:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13290: 
                   13291:     while (my $configline=<$config>) {
1.448     albertel 13292: 	chomp($configline);
                   13293: 	if ($configline) {
1.742     raeburn  13294: 	    my ($short,@plain)=split(/:/,$configline);
                   13295:             %{$prp{$short}} = ();
                   13296: 	    if (@plain > 0) {
                   13297:                 $prp{$short}{'std'} = $plain[0];
                   13298:                 for (my $i=1; $i<@plain; $i++) {
                   13299:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13300:                 }
                   13301:             }
1.448     albertel 13302: 	}
1.135     www      13303:     }
1.448     albertel 13304:     close($config);
1.135     www      13305: }
                   13306: 
                   13307: # ---------------------------------------------------------- Read package table
                   13308: {
1.448     albertel 13309:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13310: 
                   13311:     while (my $configline=<$config>) {
1.483     albertel 13312: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13313: 	chomp($configline);
                   13314: 	my ($short,$plain)=split(/:/,$configline);
                   13315: 	my ($pack,$name)=split(/\&/,$short);
                   13316: 	if ($plain ne '') {
                   13317: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13318: 	    $packagetab{$short}=$plain; 
                   13319: 	}
1.11      www      13320:     }
1.448     albertel 13321:     close($config);
1.329     matthew  13322: }
                   13323: 
1.1073    raeburn  13324: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  13325: 
                   13326: &load_loncaparevs();
1.1073    raeburn  13327: 
1.1074    raeburn  13328: # ---------------------------------------------------------- Read serverhostID table
                   13329: 
1.1227    raeburn  13330: &load_serverhomeIDs();
                   13331: 
                   13332: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13333: {
                   13334:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13335:     if (-e $file) {
                   13336:         my $parser = HTML::LCParser->new($file);
                   13337:         while (my $token = $parser->get_token()) {
                   13338:             if ($token->[0] eq 'S') {
                   13339:                 my $item = $token->[1];
                   13340:                 my $name = $token->[2]{'name'};
                   13341:                 my $value = $token->[2]{'value'};
1.1285    raeburn  13342:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  13343:                 my $namematch = $token->[2]{'namematch'};
                   13344:                 if ($item eq 'parameter') {
                   13345:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   13346:                         my $release = $parser->get_text();
                   13347:                         $release =~ s/(^\s*|\s*$ )//gx;
                   13348:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   13349:                     }
                   13350:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  13351:                     my $release = $parser->get_text();
                   13352:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  13353:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  13354:                 }
                   13355:             }
                   13356:         }
                   13357:     }
1.1073    raeburn  13358: }
                   13359: 
1.1138    raeburn  13360: # ---------------------------------------------------------- Read managers table
                   13361: {
                   13362:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   13363:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   13364:             while (my $configline=<$config>) {
                   13365:                 chomp($configline);
                   13366:                 next if ($configline =~ /^\#/);
                   13367:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13368:                     $managerstab{$configline} = 1;
                   13369:                 }
                   13370:             }
                   13371:             close($config);
                   13372:         }
                   13373:     }
                   13374: }
                   13375: 
1.329     matthew  13376: # ------------- set up temporary directory
                   13377: {
1.1117    foxr     13378:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  13379: 
1.11      www      13380: }
                   13381: 
1.794     albertel 13382: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   13383: 				'compress_threshold'=> 20_000,
                   13384:  			        });
1.185     www      13385: 
1.281     www      13386: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      13387: $dumpcount=0;
1.958     www      13388: $locknum=0;
1.22      www      13389: 
1.163     harris41 13390: &logtouch();
1.672     albertel 13391: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      13392: $readit=1;
1.564     albertel 13393:     {
                   13394: 	use integer;
                   13395: 	my $test=(2**32)+1;
1.568     albertel 13396: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 13397: 	&logthis(" Detected 64bit platform ($_64bit)");
                   13398:     }
1.195     www      13399: }
1.1       albertel 13400: }
1.179     www      13401: 
1.1       albertel 13402: 1;
1.191     harris41 13403: __END__
                   13404: 
1.243     albertel 13405: =pod
                   13406: 
1.191     harris41 13407: =head1 NAME
                   13408: 
1.243     albertel 13409: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 13410: 
                   13411: =head1 SYNOPSIS
                   13412: 
1.243     albertel 13413: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 13414: 
                   13415:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   13416: 
1.243     albertel 13417: Common parameters:
                   13418: 
                   13419: =over 4
                   13420: 
                   13421: =item *
                   13422: 
                   13423: $uname : an internal username (if $cname expecting a course Id specifically)
                   13424: 
                   13425: =item *
                   13426: 
                   13427: $udom : a domain (if $cdom expecting a course's domain specifically)
                   13428: 
                   13429: =item *
                   13430: 
                   13431: $symb : a resource instance identifier
                   13432: 
                   13433: =item *
                   13434: 
                   13435: $namespace : the name of a .db file that contains the data needed or
                   13436: being set.
                   13437: 
                   13438: =back
                   13439: 
1.394     bowersj2 13440: =head1 OVERVIEW
1.191     harris41 13441: 
1.394     bowersj2 13442: lonnet provides subroutines which interact with the
                   13443: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   13444: about classes, users, and resources.
1.243     albertel 13445: 
                   13446: For many of these objects you can also use this to store data about
                   13447: them or modify them in various ways.
1.191     harris41 13448: 
1.394     bowersj2 13449: =head2 Symbs
1.191     harris41 13450: 
1.394     bowersj2 13451: To identify a specific instance of a resource, LON-CAPA uses symbols
                   13452: or "symbs"X<symb>. These identifiers are built from the URL of the
                   13453: map, the resource number of the resource in the map, and the URL of
                   13454: the resource itself. The latter is somewhat redundant, but might help
                   13455: if maps change.
                   13456: 
                   13457: An example is
                   13458: 
                   13459:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   13460: 
                   13461: The respective map entry is
                   13462: 
                   13463:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   13464:   title="Problem 2">
                   13465:  </resource>
                   13466: 
                   13467: Symbs are used by the random number generator, as well as to store and
                   13468: restore data specific to a certain instance of for example a problem.
                   13469: 
                   13470: =head2 Storing And Retrieving Data
                   13471: 
                   13472: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   13473: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   13474: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   13475: is is the non-critical message twin of cstore. These functions are for
                   13476: handlers to store a perl hash to a user's permanent data space in an
                   13477: easy manner, and to retrieve it again on another call. It is expected
                   13478: that a handler would use this once at the beginning to retrieve data,
                   13479: and then again once at the end to send only the new data back.
                   13480: 
                   13481: The data is stored in the user's data directory on the user's
                   13482: homeserver under the ID of the course.
                   13483: 
                   13484: The hash that is returned by restore will have all of the previous
                   13485: value for all of the elements of the hash.
                   13486: 
                   13487: Example:
                   13488: 
                   13489:  #creating a hash
                   13490:  my %hash;
                   13491:  $hash{'foo'}='bar';
                   13492: 
                   13493:  #storing it
                   13494:  &Apache::lonnet::cstore(\%hash);
                   13495: 
                   13496:  #changing a value
                   13497:  $hash{'foo'}='notbar';
                   13498: 
                   13499:  #adding a new value
                   13500:  $hash{'bar'}='foo';
                   13501:  &Apache::lonnet::cstore(\%hash);
                   13502: 
                   13503:  #retrieving the hash
                   13504:  my %history=&Apache::lonnet::restore();
                   13505: 
                   13506:  #print the hash
                   13507:  foreach my $key (sort(keys(%history))) {
                   13508:    print("\%history{$key} = $history{$key}");
                   13509:  }
                   13510: 
                   13511: Will print out:
1.191     harris41 13512: 
1.394     bowersj2 13513:  %history{1:foo} = bar
                   13514:  %history{1:keys} = foo:timestamp
                   13515:  %history{1:timestamp} = 990455579
                   13516:  %history{2:bar} = foo
                   13517:  %history{2:foo} = notbar
                   13518:  %history{2:keys} = foo:bar:timestamp
                   13519:  %history{2:timestamp} = 990455580
                   13520:  %history{bar} = foo
                   13521:  %history{foo} = notbar
                   13522:  %history{timestamp} = 990455580
                   13523:  %history{version} = 2
                   13524: 
                   13525: Note that the special hash entries C<keys>, C<version> and
                   13526: C<timestamp> were added to the hash. C<version> will be equal to the
                   13527: total number of versions of the data that have been stored. The
                   13528: C<timestamp> attribute will be the UNIX time the hash was
                   13529: stored. C<keys> is available in every historical section to list which
                   13530: keys were added or changed at a specific historical revision of a
                   13531: hash.
                   13532: 
                   13533: B<Warning>: do not store the hash that restore returns directly. This
                   13534: will cause a mess since it will restore the historical keys as if the
                   13535: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 13536: 
1.394     bowersj2 13537: Calling convention:
1.191     harris41 13538: 
1.1225    raeburn  13539:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  13540:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 13541: 
1.394     bowersj2 13542: For more detailed information, see lonnet specific documentation.
1.191     harris41 13543: 
1.394     bowersj2 13544: =head1 RETURN MESSAGES
1.191     harris41 13545: 
1.394     bowersj2 13546: =over 4
1.191     harris41 13547: 
1.394     bowersj2 13548: =item * B<con_lost>: unable to contact remote host
1.191     harris41 13549: 
1.394     bowersj2 13550: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   13551: when the connection is brought back up
1.191     harris41 13552: 
1.394     bowersj2 13553: =item * B<con_failed>: unable to contact remote host and unable to save message
                   13554: for later delivery
1.191     harris41 13555: 
1.967     bisitz   13556: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 13557: 
1.394     bowersj2 13558: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 13559: that was requested
1.191     harris41 13560: 
1.243     albertel 13561: =back
1.191     harris41 13562: 
1.243     albertel 13563: =head1 PUBLIC SUBROUTINES
1.191     harris41 13564: 
1.243     albertel 13565: =head2 Session Environment Functions
1.191     harris41 13566: 
1.243     albertel 13567: =over 4
1.191     harris41 13568: 
1.394     bowersj2 13569: =item * 
                   13570: X<appenv()>
1.949     raeburn  13571: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 13572: the user envirnoment file, and will be restored for each access this
1.620     albertel 13573: user makes during this session, also modifies the %env for the current
1.949     raeburn  13574: process. Optional rolesarrayref - if defined contains a reference to an array
                   13575: of roles which are exempt from the restriction on modifying user.role entries 
                   13576: in the user's environment.db and in %env.    
1.191     harris41 13577: 
                   13578: =item *
1.394     bowersj2 13579: X<delenv()>
1.987     raeburn  13580: B<delenv($delthis,$regexp)>: removes all items from the session
                   13581: environment file that begin with $delthis. If the 
                   13582: optional second arg - $regexp - is true, $delthis is treated as a 
                   13583: regular expression, otherwise \Q$delthis\E is used. 
                   13584: The values are also deleted from the current processes %env.
1.191     harris41 13585: 
1.795     albertel 13586: =item * get_env_multiple($name) 
                   13587: 
                   13588: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   13589: values may be defined and end up as an array ref.
                   13590: 
                   13591: returns an array of values
                   13592: 
1.243     albertel 13593: =back
                   13594: 
                   13595: =head2 User Information
1.191     harris41 13596: 
1.243     albertel 13597: =over 4
1.191     harris41 13598: 
                   13599: =item *
1.394     bowersj2 13600: X<queryauthenticate()>
                   13601: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 13602: authentication scheme
                   13603: 
                   13604: =item *
1.394     bowersj2 13605: X<authenticate()>
1.1073    raeburn  13606: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 13607: authenticate user from domain's lib servers (first use the current
                   13608: one). C<$upass> should be the users password.
1.1073    raeburn  13609: $checkdefauth is optional (value is 1 if a check should be made to
                   13610:    authenticate user using default authentication method, and allow
                   13611:    account creation if username does not have account in the domain).
                   13612: $clientcancheckhost is optional (value is 1 if checking whether the
                   13613:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 13614: 
                   13615: =item *
1.394     bowersj2 13616: X<homeserver()>
                   13617: B<homeserver($uname,$udom)>: find the server which has
                   13618: the user's directory and files (there must be only one), this caches
                   13619: the answer, and also caches if there is a borken connection.
1.191     harris41 13620: 
                   13621: =item *
1.394     bowersj2 13622: X<idget()>
1.1300    raeburn  13623: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   13624: a list of student/employee IDs or clicker IDs
                   13625: (student/employee IDs are a unique resource in a domain, there must be 
                   13626: only 1 ID per username, and only 1 username per ID in a specific domain).
                   13627: clickerIDs are not necessarily unique, as students might share clickers.
                   13628: (returns hash: id=>name,id=>name)
1.191     harris41 13629: 
                   13630: =item *
1.394     bowersj2 13631: X<idrget()>
                   13632: B<idrget($udom,@unames)>: find the IDs behind a list of
                   13633: usernames (returns hash: name=>id,name=>id)
1.191     harris41 13634: 
                   13635: =item *
1.394     bowersj2 13636: X<idput()>
1.1300    raeburn  13637: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   13638: names and associated student/employee IDs or clicker IDs.
                   13639: 
                   13640: =item *
                   13641: X<iddel()>
                   13642: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   13643: student/employee ID or clicker ID username look-ups from domain.
                   13644: The homeserver ($uhome) and namespace ($namespace) are optional.
                   13645: If no $uhome is provided, it will be determined usig &homeserver()
                   13646: for each user.  If no $namespace is provided, the default is ids.
                   13647: 
                   13648: =item *
                   13649: X<updateclickers()>
                   13650: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   13651: clicker ID-to-username look-ups in clickers.db on library server.
                   13652: Permitted actions are add or del (i.e., add or delete). The 
                   13653: clickers.db contains clickerID as keys (escaped), and each corresponding
                   13654: value is an escaped comma-separated list of usernames (for whom the
                   13655: library server is the homeserver), who registered that particular ID.
                   13656: If $critical is true, the update will be sent via &critical, otherwise
                   13657: &reply() will be used.
1.191     harris41 13658: 
                   13659: =item *
1.394     bowersj2 13660: X<rolesinit()>
1.1169    droeschl 13661: B<rolesinit($udom,$username)>: get user privileges.
                   13662: returns user role, first access and timer interval hashes
1.243     albertel 13663: 
                   13664: =item *
1.1171    droeschl 13665: X<privileged()>
                   13666: B<privileged($username,$domain)>: returns a true if user has a
                   13667: privileged and active role (i.e. su or dc), false otherwise.
                   13668: 
                   13669: =item *
1.551     albertel 13670: X<getsection()>
                   13671: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 13672: course $cname, return section name/number or '' for "not in course"
                   13673: and '-1' for "no section"
                   13674: 
                   13675: =item *
1.394     bowersj2 13676: X<userenvironment()>
                   13677: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 13678: passed in @what from the requested user's environment, returns a hash
                   13679: 
1.858     raeburn  13680: =item * 
                   13681: X<userlog_query()>
1.859     albertel 13682: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   13683: activity.log file. %filters defines filters applied when parsing the
                   13684: log file. These can be start or end timestamps, or the type of action
                   13685: - log to look for Login or Logout events, check for Checkin or
                   13686: Checkout, role for role selection. The response is in the form
                   13687: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   13688: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  13689: 
1.243     albertel 13690: =back
                   13691: 
                   13692: =head2 User Roles
                   13693: 
                   13694: =over 4
                   13695: 
                   13696: =item *
                   13697: 
1.1284    raeburn  13698: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   13699: returns codes for allowed actions.
                   13700: 
                   13701: The first argument is required, all others are optional.
                   13702: 
                   13703: $priv is the privilege being checked.
                   13704: $uri contains additional information about what is being checked for access (e.g.,
                   13705: URL, course ID etc.). 
                   13706: $symb is the unique resource instance identifier in a course; if needed,
                   13707: but not provided, it will be retrieved via a call to &symbread(). 
                   13708: $role is the role for which a priv is being checked (only used if priv is evb). 
                   13709: $clientip is the user's IP address (only used when checking for access to portfolio 
                   13710: files).
                   13711: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   13712: prevents recursive calls to &allowed.
                   13713: 
1.243     albertel 13714:  F: full access
                   13715:  U,I,K: authentication modes (cxx only)
                   13716:  '': forbidden
                   13717:  1: user needs to choose course
                   13718:  2: browse allowed
1.766     albertel 13719:  A: passphrase authentication needed
1.1284    raeburn  13720:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 13721: 
                   13722: =item *
                   13723: 
1.1192    raeburn  13724: constructaccess($url,$setpriv) : check for access to construction space URL
                   13725: 
                   13726: See if the owner domain and name in the URL match those in the
                   13727: expected environment.  If so, return three element list
                   13728: ($ownername,$ownerdomain,$ownerhome).
                   13729: 
                   13730: Otherwise return the null string.
                   13731: 
                   13732: If second argument 'setpriv' is true, it assigns the privileges,
                   13733: and returns the same three element list, unless the owner has
                   13734: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   13735: in which case the null string is returned.
                   13736: 
                   13737: =item *
                   13738: 
1.243     albertel 13739: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   13740: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   13741: and course level
                   13742: 
                   13743: =item *
                   13744: 
1.988     raeburn  13745: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   13746: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  13747: $type is Course (default) or Community.
1.988     raeburn  13748: If $forcedefault evaluates to true, text returned will be default 
                   13749: text for $type. Otherwise, if this is a course, the text returned 
                   13750: will be a custom name for the role (if defined in the course's 
                   13751: environment).  If no custom name is defined the default is returned.
                   13752:    
1.832     raeburn  13753: =item *
                   13754: 
1.1219    raeburn  13755: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  13756: All arguments are optional. Returns a hash of a roles, either for
                   13757: co-author/assistant author roles for a user's Construction Space
1.906     albertel 13758: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  13759: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   13760: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   13761: For each key, value is set to colon-separated start and end times for
                   13762: the role.  If no username and domain are specified, will default to
1.934     raeburn  13763: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  13764: of role statuses (active, future or previous), roles 
                   13765: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   13766: to restrict the list of roles reported. If no array ref is 
                   13767: provided for types, will default to return only active roles.
1.834     albertel 13768: 
1.1195    raeburn  13769: =item *
                   13770: 
                   13771: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  13772: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   13773: 
                   13774: Additional optional arguments are: $type (if role checking is to be restricted 
                   13775: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  13776: available roles) or future (roles available in the future), and
                   13777: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  13778: have active Domain Coordinator role in course's domain or in additional
                   13779: domains (specified in 'Domains to check for privileged users' in course
                   13780: environment -- set via:  Course Settings -> Classlists and staff listing).
                   13781: 
                   13782: =item *
                   13783: 
                   13784: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   13785: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   13786: $possdomains and $possroles are optional array refs -- to domains to check and
                   13787: roles to check.  If $possdomains is not specified, a dump will be done of the
                   13788: users' roles.db to check for a dc or su role in any domain. This can be
                   13789: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   13790: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   13791: this then allows &privileged_by_domain() to be used, which caches the identity
                   13792: of privileged users, eliminating the need for repeated calls to &dump().
                   13793: 
                   13794: =item *
                   13795: 
                   13796: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   13797: where the outer hash keys are domains specified in the $possdomains array ref,
                   13798: next inner hash keys are privileged roles specified in the $roles array ref,
                   13799: and the innermost hash contains key = value pairs for username:domain = end:start
                   13800: for active or future "privileged" users with that role in that domain. To avoid
                   13801: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   13802: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  13803: 
1.243     albertel 13804: =back
                   13805: 
                   13806: =head2 User Modification
                   13807: 
                   13808: =over 4
                   13809: 
                   13810: =item *
                   13811: 
1.957     raeburn  13812: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 13813: user for the level given by URL.  Optional start and end dates (leave empty
                   13814: string or zero for "no date")
1.191     harris41 13815: 
                   13816: =item *
                   13817: 
1.243     albertel 13818: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   13819: change a users, password, possible return values are: ok,
                   13820: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   13821: refused
1.191     harris41 13822: 
                   13823: =item *
                   13824: 
1.243     albertel 13825: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 13826: 
                   13827: =item *
                   13828: 
1.1058    raeburn  13829: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   13830:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   13831: 
                   13832: will update user information (firstname,middlename,lastname,generation,
                   13833: permanentemail), and if forceid is true, student/employee ID also.
                   13834: A user's institutional affiliation(s) can also be updated.
                   13835: User information fields will not be overwritten with empty entries 
                   13836: unless the field is included in the $candelete array reference.
                   13837: This array is included when a single user is modified via "Manage Users",
                   13838: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 13839: 
                   13840: =item *
                   13841: 
1.286     matthew  13842: modifystudent
                   13843: 
1.957     raeburn  13844: modify a student's enrollment and identification information.
1.1235    raeburn  13845: The course id is resolved based on the current user's environment.  
                   13846: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  13847: associated with a course.
                   13848: 
1.297     matthew  13849: This call is essentially a wrapper for lonnet::modifyuser and
                   13850: lonnet::modify_student_enrollment
1.286     matthew  13851: 
                   13852: Inputs: 
                   13853: 
                   13854: =over 4
                   13855: 
1.957     raeburn  13856: =item B<$udom> Student's loncapa domain
1.286     matthew  13857: 
1.957     raeburn  13858: =item B<$uname> Student's loncapa login name
1.286     matthew  13859: 
1.964     bisitz   13860: =item B<$uid> Student/Employee ID
1.286     matthew  13861: 
1.957     raeburn  13862: =item B<$umode> Student's authentication mode
1.286     matthew  13863: 
1.957     raeburn  13864: =item B<$upass> Student's password
1.286     matthew  13865: 
1.957     raeburn  13866: =item B<$first> Student's first name
1.286     matthew  13867: 
1.957     raeburn  13868: =item B<$middle> Student's middle name
1.286     matthew  13869: 
1.957     raeburn  13870: =item B<$last> Student's last name
1.286     matthew  13871: 
1.957     raeburn  13872: =item B<$gene> Student's generation
1.286     matthew  13873: 
1.957     raeburn  13874: =item B<$usec> Student's section in course
1.286     matthew  13875: 
                   13876: =item B<$end> Unix time of the roles expiration
                   13877: 
                   13878: =item B<$start> Unix time of the roles start date
                   13879: 
                   13880: =item B<$forceid> If defined, allow $uid to be changed
                   13881: 
                   13882: =item B<$desiredhome> server to use as home server for student
                   13883: 
1.957     raeburn  13884: =item B<$email> Student's permanent e-mail address
                   13885: 
                   13886: =item B<$type> Type of enrollment (auto or manual)
                   13887: 
1.963     raeburn  13888: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   13889: 
                   13890: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  13891: 
1.963     raeburn  13892: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  13893: 
1.963     raeburn  13894: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  13895: 
1.1216    raeburn  13896: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   13897: 
                   13898: =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  13899: 
1.286     matthew  13900: =back
1.297     matthew  13901: 
                   13902: =item *
                   13903: 
                   13904: modify_student_enrollment
                   13905: 
1.1235    raeburn  13906: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  13907: 'role.request.course' must be defined for this function to proceed.
                   13908: 
                   13909: Inputs:
                   13910: 
                   13911: =over 4
                   13912: 
1.1235    raeburn  13913: =item $udom, student's domain
1.297     matthew  13914: 
1.1235    raeburn  13915: =item $uname, student's name
1.297     matthew  13916: 
1.1235    raeburn  13917: =item $uid, student's user id
1.297     matthew  13918: 
1.1235    raeburn  13919: =item $first, student's first name
1.297     matthew  13920: 
                   13921: =item $middle
                   13922: 
                   13923: =item $last
                   13924: 
                   13925: =item $gene
                   13926: 
                   13927: =item $usec
                   13928: 
                   13929: =item $end
                   13930: 
                   13931: =item $start
                   13932: 
1.957     raeburn  13933: =item $type
                   13934: 
                   13935: =item $locktype
                   13936: 
                   13937: =item $cid
                   13938: 
                   13939: =item $selfenroll
                   13940: 
                   13941: =item $context
                   13942: 
1.1216    raeburn  13943: =item $credits, number of credits student will earn from this class
                   13944: 
1.1314    raeburn  13945: =item $instsec, institutional course section code for student
                   13946: 
1.297     matthew  13947: =back
                   13948: 
1.191     harris41 13949: 
                   13950: =item *
                   13951: 
1.243     albertel 13952: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   13953: custom role; give a custom role to a user for the level given by URL.  Specify
                   13954: name and domain of role author, and role name
1.191     harris41 13955: 
                   13956: =item *
                   13957: 
1.243     albertel 13958: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 13959: 
                   13960: =item *
                   13961: 
1.243     albertel 13962: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   13963: 
                   13964: =back
                   13965: 
                   13966: =head2 Course Infomation
                   13967: 
                   13968: =over 4
1.191     harris41 13969: 
                   13970: =item *
                   13971: 
1.1118    foxr     13972: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 13973: specified course id, including all environment settings for the
                   13974: course, the description of the course will be in the hash under the
                   13975: key 'description'
1.191     harris41 13976: 
1.1118    foxr     13977: $options is an optional parameter that if supplied is a hash reference that controls
                   13978: what how this function works.  It has the following key/values:
                   13979: 
                   13980: =over 4
                   13981: 
                   13982: =item freshen_cache
                   13983: 
                   13984: If defined, and the environment cache for the course is valid, it is 
                   13985: returned in the returned hash.
                   13986: 
                   13987: =item one_time
                   13988: 
                   13989: If defined, the last cache time is set to _now_
                   13990: 
                   13991: =item user
                   13992: 
                   13993: If defined, the supplied username is used instead of the current user.
                   13994: 
                   13995: 
                   13996: =back
                   13997: 
1.191     harris41 13998: =item *
                   13999: 
1.624     albertel 14000: resdata($name,$domain,$type,@which) : request for current parameter
                   14001: setting for a specific $type, where $type is either 'course' or 'user',
                   14002: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  14003: answers for 10 minutes.
1.243     albertel 14004: 
1.877     foxr     14005: =item *
                   14006: 
                   14007: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14008: data base, returning a hash that is keyed by the resource name and has
                   14009: values that are the resource value.  I believe that the timestamps and
                   14010: versions are also returned.
                   14011: 
1.1236    raeburn  14012: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14013: supplemental content area. This routine caches the number of files for 
                   14014: 10 minutes.
                   14015: 
1.243     albertel 14016: =back
                   14017: 
                   14018: =head2 Course Modification
                   14019: 
                   14020: =over 4
1.191     harris41 14021: 
                   14022: =item *
                   14023: 
1.243     albertel 14024: writecoursepref($courseid,%prefs) : write preferences (environment
                   14025: database) for a course
1.191     harris41 14026: 
                   14027: =item *
                   14028: 
1.1011    raeburn  14029: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14030: 
                   14031: =item *
                   14032: 
1.1038    raeburn  14033: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14034: 
1.1167    droeschl 14035: =item *
                   14036: 
                   14037: is_course($courseid), is_course($cdom, $cnum)
                   14038: 
                   14039: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14040: two component version $cdom, $cnum. It checks if the specified course exists.
                   14041: 
                   14042: Returns:
                   14043:     undef if the course doesn't exist, otherwise
                   14044:     in scalar context the combined courseid.
                   14045:     in list context the two components of the course identifier, domain and 
                   14046:     courseid.    
                   14047: 
1.243     albertel 14048: =back
                   14049: 
                   14050: =head2 Resource Subroutines
                   14051: 
                   14052: =over 4
1.191     harris41 14053: 
                   14054: =item *
                   14055: 
1.243     albertel 14056: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14057: 
                   14058: =item *
                   14059: 
1.243     albertel 14060: repcopy($filename) : subscribes to the requested file, and attempts to
                   14061: replicate from the owning library server, Might return
1.607     raeburn  14062: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14063: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14064: resource. Expects the local filesystem pathname
                   14065: (/home/httpd/html/res/....)
                   14066: 
                   14067: =back
                   14068: 
                   14069: =head2 Resource Information
                   14070: 
                   14071: =over 4
1.191     harris41 14072: 
                   14073: =item *
                   14074: 
1.1228    raeburn  14075: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14076: and returns the value of a variety of different possible values,
                   14077: $varname should be a request string, and the other parameters can be
                   14078: used to specify who and what one is asking about. Ordinarily, $cid 
                   14079: does not need to be specified, as it is retrived from 
                   14080: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14081: within lonuserstate::loadmap() when initializing a course, before
                   14082: $env{'request.course.id'} has been set, so it needs to be provided
                   14083: in that one case.
1.243     albertel 14084: 
                   14085: Possible values for $varname are environment.lastname (or other item
                   14086: from the envirnment hash), user.name (or someother aspect about the
                   14087: user), resource.0.maxtries (or some other part and parameter of a
                   14088: resource)
1.204     albertel 14089: 
                   14090: =item *
                   14091: 
1.243     albertel 14092: directcondval($number) : get current value of a condition; reads from a state
                   14093: string
1.204     albertel 14094: 
                   14095: =item *
                   14096: 
1.243     albertel 14097: condval($condidx) : value of condition index based on state
1.204     albertel 14098: 
                   14099: =item *
                   14100: 
1.243     albertel 14101: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14102: resource's metadata, $what should be either a specific key, or either
                   14103: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14104: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14105: 
                   14106: this function automatically caches all requests
1.191     harris41 14107: 
                   14108: =item *
                   14109: 
1.243     albertel 14110: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14111: network of library servers; returns file handle of where SQL and regex results
                   14112: will be stored for query
1.191     harris41 14113: 
                   14114: =item *
                   14115: 
1.1282    raeburn  14116: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   14117: return symbolic list entry (all arguments optional). 
                   14118: 
                   14119: Args: filename is the filename (including path) for the file for which a symb 
                   14120: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   14121: to check access status if more than one resource was found in the bighash 
                   14122: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   14123: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   14124: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14125: cause possible symbs to be checked to determine if they are subject to content
                   14126: blocking, if so they will not be included as possible symbs; possibles is a
                   14127: ref to a hash, which, as a side effect, will be populated with all possible 
                   14128: symbs (content blocking not tested).
                   14129:  
1.243     albertel 14130: returns the data handle
1.191     harris41 14131: 
                   14132: =item *
                   14133: 
1.1190    raeburn  14134: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   14135: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14136: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  14137: on failure, user must be in a course, as it assumes the existence of
                   14138: the course initial hash, and uses $env('request.course.id'}.  The third
                   14139: arg is an optional reference to a scalar.  If this arg is passed in the 
                   14140: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14141: encrypted; otherwise it will be null.  
1.191     harris41 14142: 
                   14143: =item *
                   14144: 
1.243     albertel 14145: symbclean($symb) : removes versions numbers from a symb, returns the
                   14146: cleaned symb
1.191     harris41 14147: 
                   14148: =item *
                   14149: 
1.243     albertel 14150: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14151: course map, user must be in a course for it to work.
1.191     harris41 14152: 
                   14153: =item *
                   14154: 
1.243     albertel 14155: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14156: 
                   14157: =item *
                   14158: 
1.243     albertel 14159: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14160: a random seed, all arguments are optional, if they aren't sent it uses the
                   14161: environment to derive them. Note: if symb isn't sent and it can't get one
                   14162: from &symbread it will use the current time as its return value
1.191     harris41 14163: 
                   14164: =item *
                   14165: 
1.243     albertel 14166: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14167: unfakeable, receipt
1.191     harris41 14168: 
                   14169: =item *
                   14170: 
1.620     albertel 14171: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14172: 
                   14173: =item *
                   14174: 
1.243     albertel 14175: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14176: 
                   14177: =item *
                   14178: 
1.243     albertel 14179: 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 14180: 
                   14181: =item *
                   14182: 
1.243     albertel 14183: 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 14184: 
                   14185: =item *
                   14186: 
1.243     albertel 14187: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14188: 
                   14189: =item *
                   14190: 
1.243     albertel 14191: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14192: forcing spreadsheet to reevaluate the resource scores next time.
                   14193: 
1.1195    raeburn  14194: =item * 
                   14195: 
1.1196    raeburn  14196: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14197: when viewing in course context.
1.1195    raeburn  14198: 
1.1196    raeburn  14199:  input: six args -- filename (decluttered), course number, course domain,
                   14200:                     url, symb (if registered) and group (if this is a 
                   14201:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  14202: 
1.1196    raeburn  14203:  output: array of five scalars --
1.1195    raeburn  14204:          $cfile -- url for file editing if editable on current server
                   14205:          $home -- homeserver of resource (i.e., for author if published,
                   14206:                                           or course if uploaded.).
                   14207:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  14208:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   14209:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  14210: 
                   14211: =item *
                   14212: 
                   14213: is_course_upload($file,$cnum,$cdom)
                   14214: 
                   14215: Used in course context to determine if current file was uploaded to 
                   14216: the course (i.e., would be found in /userfiles/docs on the course's 
                   14217: homeserver.
                   14218: 
                   14219:   input: 3 args -- filename (decluttered), course number and course domain.
                   14220:   output: boolean -- 1 if file was uploaded.
                   14221: 
1.243     albertel 14222: =back
                   14223: 
                   14224: =head2 Storing/Retreiving Data
                   14225: 
                   14226: =over 4
1.191     harris41 14227: 
                   14228: =item *
                   14229: 
1.1269    raeburn  14230: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   14231: permanently for this url; hashref needs to be given and should be a \%hashname;
                   14232: the remaining args aren't required and if they aren't passed or are '' they will
                   14233: be derived from the env (with the exception of $laststore, which is an 
                   14234: optional arg used when a user's submission is stored in grading).
                   14235: $laststore is $version=$timestamp, where $version is the most recent version
                   14236: number retrieved for the corresponding $symb in the $namespace db file, and
                   14237: $timestamp is the timestamp for that transaction (UNIX time).
                   14238: $laststore is currently only passed when cstore() is called by 
                   14239: structuretags::finalize_storage().
1.191     harris41 14240: 
                   14241: =item *
                   14242: 
1.1269    raeburn  14243: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   14244: but uses critical subroutine
1.191     harris41 14245: 
                   14246: =item *
                   14247: 
1.243     albertel 14248: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14249: all args are optional
1.191     harris41 14250: 
                   14251: =item *
                   14252: 
1.717     albertel 14253: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14254: dumps the complete (or key matching regexp) namespace into a hash
                   14255: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14256: normally &store()ed into
                   14257: 
                   14258: $range should be either an integer '100' (give me the first 100
                   14259:                                            matching records)
                   14260:               or be  two integers sperated by a - with no spaces
                   14261:                  '30-50' (give me the 30th through the 50th matching
                   14262:                           records)
                   14263: 
                   14264: 
                   14265: =item *
                   14266: 
1.1269    raeburn  14267: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14268: replaces a &store() version of data with a replacement set of data
                   14269: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  14270: reference. If $tolog is true, the transaction is logged in the courselog
                   14271: with an action=PUTSTORE.
1.717     albertel 14272: 
                   14273: =item *
                   14274: 
1.243     albertel 14275: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14276: works very similar to store/cstore, but all data is stored in a
                   14277: temporary location and can be reset using tmpreset, $storehash should
                   14278: be a hash reference, returns nothing on success
1.191     harris41 14279: 
                   14280: =item *
                   14281: 
1.243     albertel 14282: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14283: similar to restore, but all data is stored in a temporary location and
                   14284: can be reset using tmpreset. Returns a hash of values on success,
                   14285: error string otherwise.
1.191     harris41 14286: 
                   14287: =item *
                   14288: 
1.243     albertel 14289: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14290: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14291: 
                   14292: =item *
                   14293: 
1.243     albertel 14294: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14295: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14296: 
                   14297: =item *
                   14298: 
1.243     albertel 14299: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14300: namesp ($udom and $uname are optional)
1.191     harris41 14301: 
                   14302: =item *
                   14303: 
1.702     albertel 14304: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14305: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14306: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  14307: 
1.702     albertel 14308: $range should be either an integer '100' (give me the first 100
                   14309:                                            matching records)
                   14310:               or be  two integers sperated by a - with no spaces
                   14311:                  '30-50' (give me the 30th through the 50th matching
                   14312:                           records)
1.449     matthew  14313: =item *
                   14314: 
                   14315: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   14316: $store can be a scalar, an array reference, or if the amount to be 
                   14317: incremented is > 1, a hash reference.
                   14318: 
                   14319: ($udom and $uname are optional)
1.191     harris41 14320: 
                   14321: =item *
                   14322: 
1.243     albertel 14323: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   14324: ($udom and $uname are optional)
1.191     harris41 14325: 
                   14326: =item *
                   14327: 
1.243     albertel 14328: cput($namespace,$storehash,$udom,$uname) : critical put
                   14329: ($udom and $uname are optional)
1.191     harris41 14330: 
                   14331: =item *
                   14332: 
1.748     albertel 14333: newput($namespace,$storehash,$udom,$uname) :
                   14334: 
                   14335: Attempts to store the items in the $storehash, but only if they don't
                   14336: currently exist, if this succeeds you can be certain that you have 
                   14337: successfully created a new key value pair in the $namespace db.
                   14338: 
                   14339: 
                   14340: Args:
                   14341:  $namespace: name of database to store values to
                   14342:  $storehash: hashref to store to the db
                   14343:  $udom: (optional) domain of user containing the db
                   14344:  $uname: (optional) name of user caontaining the db
                   14345: 
                   14346: Returns:
                   14347:  'ok' -> succeeded in storing all keys of $storehash
                   14348:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   14349:                         least <key> already existed in the db (other
                   14350:                         requested keys may also already exist)
1.967     bisitz   14351:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 14352:  'con_lost' -> unable to contact request server
                   14353:  'refused' -> action was not allowed by remote machine
                   14354: 
                   14355: 
                   14356: =item *
                   14357: 
1.243     albertel 14358: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14359: reference filled in from namesp (encrypts the return communication)
                   14360: ($udom and $uname are optional)
1.191     harris41 14361: 
                   14362: =item *
                   14363: 
1.243     albertel 14364: log($udom,$name,$home,$message) : write to permanent log for user; use
                   14365: critical subroutine
                   14366: 
1.806     raeburn  14367: =item *
                   14368: 
1.860     raeburn  14369: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   14370: array reference filled in from namespace found in domain level on either
                   14371: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  14372: 
                   14373: =item *
                   14374: 
1.860     raeburn  14375: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   14376: domain level either on specified domain server ($uhome) or primary domain 
                   14377: server ($udom and $uhome are optional)
1.806     raeburn  14378: 
1.943     raeburn  14379: =item * 
                   14380: 
1.1240    raeburn  14381: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   14382: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   14383: the target domain.
                   14384: 
                   14385: May also include additional key => value pairs for the following groups:
                   14386: 
                   14387: =over
                   14388: 
                   14389: =item
                   14390: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   14391: 
                   14392: =over
                   14393: 
                   14394: =item defaultquota, authorquota
                   14395: 
                   14396: =back
                   14397: 
                   14398: =item
                   14399: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   14400: portfolio for users).
                   14401: 
                   14402: =over
                   14403: 
                   14404: =item
                   14405: aboutme, blog, webdav, portfolio
                   14406: 
                   14407: =back
                   14408: 
                   14409: =item
                   14410: requestcourses: ability to request courses, and how requests are processed.
                   14411: 
                   14412: =over
                   14413: 
                   14414: =item
1.1305    raeburn  14415: official, unofficial, community, textbook, placement
1.1240    raeburn  14416: 
                   14417: =back
                   14418: 
                   14419: =item
                   14420: inststatus: types of institutional affiliation, and order in which they are displayed.
                   14421: 
                   14422: =over
                   14423: 
                   14424: =item
1.1256    raeburn  14425: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  14426: 
                   14427: =back
                   14428: 
                   14429: =item
                   14430: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   14431: for course's uploaded content.
                   14432: 
                   14433: =over
                   14434: 
                   14435: =item
1.1246    raeburn  14436: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  14437: communityquota, textbookquota, placementquota
1.1240    raeburn  14438: 
                   14439: =back
                   14440: 
                   14441: =item
                   14442: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   14443: on your servers.
                   14444: 
                   14445: =over
                   14446: 
                   14447: =item 
                   14448: remotesessions, hostedsessions
                   14449: 
                   14450: =back
                   14451: 
                   14452: =back
                   14453: 
                   14454: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   14455: utility to create a configuration.db file on a domain's primary library server 
                   14456: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   14457: -- corresponding values are authentication type (internal, krb4, krb5,
                   14458: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   14459: will be available. Values are retrieved from cache (if current), unless the
                   14460: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   14461: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   14462: 
                   14463: Typical usage:
1.943     raeburn  14464: 
1.1240    raeburn  14465: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  14466: 
1.243     albertel 14467: =back
                   14468: 
                   14469: =head2 Network Status Functions
                   14470: 
                   14471: =over 4
1.191     harris41 14472: 
                   14473: =item *
                   14474: 
1.1137    raeburn  14475: dirlist() : return directory list based on URI (first arg).
                   14476: 
                   14477: Inputs: 1 required, 5 optional.
                   14478: 
                   14479: =over
                   14480: 
                   14481: =item 
                   14482: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   14483: 
                   14484: =item
                   14485: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   14486: 
                   14487: =item
                   14488: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   14489: 
                   14490: =item
                   14491: $getpropath - boolean: 1 if prepend path using &propath(). 
                   14492: 
                   14493: =item
                   14494: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   14495: 
                   14496: =item 
                   14497: $alternateRoot - path to prepend in place of path from $uri.
                   14498: 
                   14499: =back
                   14500: 
                   14501: Returns: Array of up to two items.
                   14502: 
                   14503: =over
                   14504: 
                   14505: a reference to an array of files/subdirectories
                   14506: 
                   14507: =over
                   14508: 
                   14509: Each element in the array of files/subdirectories is a & separated list of
                   14510: item name and the result of running stat on the item.  If dirlist was requested
                   14511: for a file instead of a directory, the item name will be ''. For a directory 
                   14512: listing, if the item is a metadata file, the element will end &N&M 
                   14513: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   14514: default copyright set (1).  
                   14515: 
                   14516: =back
                   14517: 
                   14518: a scalar containing error condition (if encountered).
                   14519: 
                   14520: =over
                   14521: 
                   14522: =item 
                   14523: no_host (no homeserver identified for $username:$domain).
                   14524: 
                   14525: =item 
                   14526: no_such_host (server contacted for listing not identified as valid host).
                   14527: 
                   14528: =item 
                   14529: con_lost (connection to remote server failed).
                   14530: 
                   14531: =item 
                   14532: refused (invalid $username:$domain received on lond side).
                   14533: 
                   14534: =item 
                   14535: no_such_dir (directory at specified path on lond side does not exist). 
                   14536: 
                   14537: =item 
                   14538: empty (directory at specified path on lond side is empty).
                   14539: 
                   14540: =over
                   14541: 
                   14542: This is currently not encountered because the &ls3, &ls2, 
                   14543: &ls (_handler) routines on the lond side do not filter out
                   14544: . and .. from a directory listing. 
                   14545: 
                   14546: =back
                   14547: 
                   14548: =back
                   14549: 
                   14550: =back
1.191     harris41 14551: 
                   14552: =item *
                   14553: 
1.243     albertel 14554: spareserver() : find server with least workload from spare.tab
                   14555: 
1.986     foxr     14556: 
                   14557: =item *
                   14558: 
                   14559: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   14560: if there is no corresponding loncapa host.
                   14561: 
1.243     albertel 14562: =back
                   14563: 
1.986     foxr     14564: 
1.243     albertel 14565: =head2 Apache Request
                   14566: 
                   14567: =over 4
1.191     harris41 14568: 
                   14569: =item *
                   14570: 
1.243     albertel 14571: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   14572: localhost, posts hash
                   14573: 
                   14574: =back
                   14575: 
                   14576: =head2 Data to String to Data
                   14577: 
                   14578: =over 4
1.191     harris41 14579: 
                   14580: =item *
                   14581: 
1.243     albertel 14582: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   14583: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 14584: 
                   14585: =item *
                   14586: 
1.243     albertel 14587: hashref2str($hashref) : convert a hashref into a string complete with
                   14588: escaping and '=' and '&' separators, supports elements that are
                   14589: arrayrefs and hashrefs
1.191     harris41 14590: 
                   14591: =item *
                   14592: 
1.243     albertel 14593: arrayref2str($arrayref) : convert an arrayref into a string complete
                   14594: with escaping and '&' separators, supports elements that are arrayrefs
                   14595: and hashrefs
1.191     harris41 14596: 
                   14597: =item *
                   14598: 
1.243     albertel 14599: str2hash($string) : convert string to hash using unescaping and
                   14600: splitting on '=' and '&', supports elements that are arrayrefs and
                   14601: hashrefs
1.191     harris41 14602: 
                   14603: =item *
                   14604: 
1.243     albertel 14605: str2array($string) : convert string to hash using unescaping and
                   14606: splitting on '&', supports elements that are arrayrefs and hashrefs
                   14607: 
                   14608: =back
                   14609: 
                   14610: =head2 Logging Routines
                   14611: 
                   14612: 
                   14613: These routines allow one to make log messages in the lonnet.log and
                   14614: lonnet.perm logfiles.
1.191     harris41 14615: 
1.1119    foxr     14616: =over 4
                   14617: 
1.191     harris41 14618: =item *
                   14619: 
1.243     albertel 14620: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 14621: 
                   14622: =item *
                   14623: 
1.243     albertel 14624: logthis() : append message to the normal lonnet.log file, it gets
                   14625: preiodically rolled over and deleted.
1.191     harris41 14626: 
                   14627: =item *
                   14628: 
1.243     albertel 14629: logperm() : append a permanent message to lonnet.perm.log, this log
                   14630: file never gets deleted by any automated portion of the system, only
                   14631: messages of critical importance should go in here.
                   14632: 
1.1119    foxr     14633: 
1.243     albertel 14634: =back
                   14635: 
                   14636: =head2 General File Helper Routines
                   14637: 
                   14638: =over 4
1.191     harris41 14639: 
                   14640: =item *
                   14641: 
1.481     raeburn  14642: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   14643: (a) files in /uploaded
                   14644:   (i) If a local copy of the file exists - 
                   14645:       compares modification date of local copy with last-modified date for 
                   14646:       definitive version stored on home server for course. If local copy is 
                   14647:       stale, requests a new version from the home server and stores it. 
                   14648:       If the original has been removed from the home server, then local copy 
                   14649:       is unlinked.
                   14650:   (ii) If local copy does not exist -
                   14651:       requests the file from the home server and stores it. 
                   14652:   
                   14653:   If $caller is 'uploadrep':  
                   14654:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   14655:     for request for files originally uploaded via DOCS. 
                   14656:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   14657:   
                   14658:   Otherwise:
                   14659:      This indicates a call from the content generation phase of the request.
                   14660:      -  returns the entire contents of the file or -1.
                   14661:      
                   14662: (b) files in /res
                   14663:    - returns the entire contents of a file or -1; 
                   14664:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 14665: 
1.712     albertel 14666: 
                   14667: =item *
                   14668: 
                   14669: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   14670:                   reference
                   14671: 
                   14672: returns either a stat() list of data about the file or an empty list
                   14673: if the file doesn't exist or couldn't find out about it (connection
                   14674: problems or user unknown)
                   14675: 
1.191     harris41 14676: =item *
                   14677: 
1.243     albertel 14678: filelocation($dir,$file) : returns file system location of a file
                   14679: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   14680: directory that relative $file lookups are to looked in ($dir of /a/dir
                   14681: and a file of ../bob will become /a/bob)
1.191     harris41 14682: 
                   14683: =item *
                   14684: 
                   14685: hreflocation($dir,$file) : returns file system location or a URL; same as
                   14686: filelocation except for hrefs
                   14687: 
                   14688: =item *
                   14689: 
1.1261    raeburn  14690: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   14691: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 14692: 
1.243     albertel 14693: =back
                   14694: 
1.608     albertel 14695: =head2 Usererfile file routines (/uploaded*)
                   14696: 
                   14697: =over 4
                   14698: 
                   14699: =item *
                   14700: 
                   14701: userfileupload(): main rotine for putting a file in a user or course's
                   14702:                   filespace, arguments are,
                   14703: 
1.620     albertel 14704:  formname - required - this is the name of the element in $env where the
1.608     albertel 14705:            filename, and the contents of the file to create/modifed exist
1.620     albertel 14706:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   14707:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  14708:  context - if coursedoc, store the file in the course of the active role
                   14709:              of the current user; 
                   14710:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   14711:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 14712:  subdir - required - subdirectory to put the file in under ../userfiles/
                   14713:          if undefined, it will be placed in "unknown"
                   14714: 
                   14715:  (This routine calls clean_filename() to remove any dangerous
                   14716:  characters from the filename, and then calls finuserfileupload() to
                   14717:  complete the transaction)
                   14718: 
                   14719:  returns either the url of the uploaded file (/uploaded/....) if successful
                   14720:  and /adm/notfound.html if unsuccessful
                   14721: 
                   14722: =item *
                   14723: 
                   14724: clean_filename(): routine for cleaing a filename up for storage in
                   14725:                  userfile space, argument is:
                   14726: 
                   14727:  filename - proposed filename
                   14728: 
                   14729: returns: the new clean filename
                   14730: 
                   14731: =item *
                   14732: 
1.1090    raeburn  14733: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 14734: userspace, probably shouldn't be called directly
                   14735: 
                   14736:   docuname: username or courseid of destination for the file
                   14737:   docudom: domain of user/course of destination for the file
                   14738:   formname: same as for userfileupload()
1.1090    raeburn  14739:   fname: filename (including subdirectories) for the file
                   14740:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   14741:   allfiles: reference to hash used to store objects found by parser
                   14742:   codebase: reference to hash used for codebases of java objects found by parser
                   14743:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   14744:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   14745:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   14746:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   14747:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   14748:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  14749:   mimetype: reference to scalar to accommodate mime type determined
                   14750:             from File::MMagic if $parser = parse.
1.608     albertel 14751: 
                   14752:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  14753:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   14754:  was 'overwrite').
                   14755:  
1.608     albertel 14756: 
                   14757: =item *
                   14758: 
                   14759: renameuserfile(): renames an existing userfile to a new name
                   14760: 
                   14761:   Args:
                   14762:    docuname: username or courseid of destination for the file
                   14763:    docudom: domain of user/course of destination for the file
                   14764:    old: current file name (including any subdirs under userfiles)
                   14765:    new: desired file name (including any subdirs under userfiles)
                   14766: 
                   14767: =item *
                   14768: 
                   14769: mkdiruserfile(): creates a directory is a userfiles dir
                   14770: 
                   14771:   Args:
                   14772:    docuname: username or courseid of destination for the file
                   14773:    docudom: domain of user/course of destination for the file
                   14774:    dir: dir to create (including any subdirs under userfiles)
                   14775: 
                   14776: =item *
                   14777: 
                   14778: removeuserfile(): removes a file that exists in userfiles
                   14779: 
                   14780:   Args:
                   14781:    docuname: username or courseid of destination for the file
                   14782:    docudom: domain of user/course of destination for the file
                   14783:    fname: filname to delete (including any subdirs under userfiles)
                   14784: 
                   14785: =item *
                   14786: 
                   14787: removeuploadedurl(): convience function for removeuserfile()
                   14788: 
                   14789:   Args:
                   14790:    url:  a full /uploaded/... url to delete
                   14791: 
1.747     albertel 14792: =item * 
                   14793: 
                   14794: get_portfile_permissions():
                   14795:   Args:
                   14796:     domain: domain of user or course contain the portfolio files
                   14797:     user: name of user or num of course contain the portfolio files
                   14798:   Returns:
                   14799:     hashref of a dump of the proper file_permissions.db
                   14800:    
                   14801: 
                   14802: =item * 
                   14803: 
                   14804: get_access_controls():
                   14805: 
                   14806: Args:
                   14807:   current_permissions: the hash ref returned from get_portfile_permissions()
                   14808:   group: (optional) the group you want the files associated with
                   14809:   file: (optional) the file you want access info on
                   14810: 
                   14811: Returns:
1.749     raeburn  14812:     a hash (keys are file names) of hashes containing
                   14813:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   14814:         values are XML containing access control settings (see below) 
1.747     albertel 14815: 
                   14816: Internal notes:
                   14817: 
1.749     raeburn  14818:  access controls are stored in file_permissions.db as key=value pairs.
                   14819:     key -> path to file/file_name\0uniqueID:scope_end_start
                   14820:         where scope -> public,guest,course,group,domains or users.
                   14821:               end -> UNIX time for end of access (0 -> no end date)
                   14822:               start -> UNIX time for start of access
                   14823: 
                   14824:     value -> XML description of access control
                   14825:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   14826:             <start></start>
                   14827:             <end></end>
                   14828: 
                   14829:             <password></password>  for scope type = guest
                   14830: 
                   14831:             <domain></domain>     for scope type = course or group
                   14832:             <number></number>
                   14833:             <roles id="">
                   14834:              <role></role>
                   14835:              <access></access>
                   14836:              <section></section>
                   14837:              <group></group>
                   14838:             </roles>
                   14839: 
                   14840:             <dom></dom>         for scope type = domains
                   14841: 
                   14842:             <users>             for scope type = users
                   14843:              <user>
                   14844:               <uname></uname>
                   14845:               <udom></udom>
                   14846:              </user>
                   14847:             </users>
                   14848:            </scope> 
                   14849:               
                   14850:  Access data is also aggregated for each file in an additional key=value pair:
                   14851:  key -> path to file/file_name\0accesscontrol 
                   14852:  value -> reference to hash
                   14853:           hash contains key = value pairs
                   14854:           where key = uniqueID:scope_end_start
                   14855:                 value = UNIX time record was last updated
                   14856: 
                   14857:           Used to improve speed of look-ups of access controls for each file.  
                   14858:  
                   14859:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   14860: 
1.1198    raeburn  14861: =item *
                   14862: 
1.749     raeburn  14863: modify_access_controls():
                   14864: 
                   14865: Modifies access controls for a portfolio file
                   14866: Args
                   14867: 1. file name
                   14868: 2. reference to hash of required changes,
                   14869: 3. domain
                   14870: 4. username
                   14871:   where domain,username are the domain of the portfolio owner 
                   14872:   (either a user or a course) 
                   14873: 
                   14874: Returns:
                   14875: 1. result of additions or updates ('ok' or 'error', with error message). 
                   14876: 2. result of deletions ('ok' or 'error', with error message).
                   14877: 3. reference to hash of any new or updated access controls.
                   14878: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   14879:    key = integer (inbound ID)
1.1198    raeburn  14880:    value = uniqueID
                   14881: 
                   14882: =item *
                   14883: 
                   14884: get_timebased_id():
                   14885: 
                   14886: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   14887: course via the Course Editor (e.g., folders, composite pages, 
                   14888: group bulletin boards).
                   14889: 
                   14890: Args: (first three required; six others optional)
                   14891: 
                   14892: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   14893:    docssequence, or name of group
                   14894: 
                   14895: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   14896:    e.g., num, boardids
                   14897: 
                   14898: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   14899:    file will be named nohist_namespace.db
                   14900: 
                   14901: 4. cdom: domain of course; default is current course domain from %env
                   14902: 
                   14903: 5. cnum: course number; default is current course number from %env
                   14904: 
                   14905: 6. idtype: set to concat if an additional digit is to be appended to the 
                   14906:    unix timestamp to form the suffix, if the plain timestamp is already
                   14907:    in use.  Default is to not do this, but simply increment the unix 
                   14908:    timestamp by 1 until a unique key is obtained.
                   14909: 
                   14910: 7. who: holder of locking key; defaults to user:domain for user.
                   14911: 
                   14912: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   14913:    retrying); default is 3.
                   14914: 
                   14915: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   14916: 
                   14917: Returns:
                   14918: 
                   14919: 1. suffix obtained (numeric)
                   14920: 
                   14921: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   14922: 
                   14923: 3. error: contains (localized) error message if an error occurred.
                   14924: 
1.747     albertel 14925: 
1.608     albertel 14926: =back
                   14927: 
1.243     albertel 14928: =head2 HTTP Helper Routines
                   14929: 
                   14930: =over 4
                   14931: 
1.191     harris41 14932: =item *
                   14933: 
                   14934: escape() : unpack non-word characters into CGI-compatible hex codes
                   14935: 
                   14936: =item *
                   14937: 
                   14938: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   14939: 
1.243     albertel 14940: =back
                   14941: 
                   14942: =head1 PRIVATE SUBROUTINES
                   14943: 
                   14944: =head2 Underlying communication routines (Shouldn't call)
                   14945: 
                   14946: =over 4
                   14947: 
                   14948: =item *
                   14949: 
                   14950: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   14951: 
                   14952: =item *
                   14953: 
                   14954: reply() : uses subreply to send a message to remote machine, logs all failures
                   14955: 
                   14956: =item *
                   14957: 
                   14958: critical() : passes a critical message to another server; if cannot
                   14959: get through then place message in connection buffer directory and
                   14960: returns con_delayed, if incapable of saving message, returns
                   14961: con_failed
                   14962: 
                   14963: =item *
                   14964: 
                   14965: reconlonc() : tries to reconnect lonc client processes.
                   14966: 
                   14967: =back
                   14968: 
                   14969: =head2 Resource Access Logging
                   14970: 
                   14971: =over 4
                   14972: 
                   14973: =item *
                   14974: 
                   14975: flushcourselogs() : flush (save) buffer logs and access logs
                   14976: 
                   14977: =item *
                   14978: 
                   14979: courselog($what) : save message for course in hash
                   14980: 
                   14981: =item *
                   14982: 
                   14983: courseacclog($what) : save message for course using &courselog().  Perform
                   14984: special processing for specific resource types (problems, exams, quizzes, etc).
                   14985: 
1.191     harris41 14986: =item *
                   14987: 
                   14988: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   14989: as a PerlChildExitHandler
1.243     albertel 14990: 
                   14991: =back
                   14992: 
                   14993: =head2 Other
                   14994: 
                   14995: =over 4
                   14996: 
                   14997: =item *
                   14998: 
                   14999: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15000: 
                   15001: =back
                   15002: 
                   15003: =cut
1.877     foxr     15004: 

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